# This location block is specific for SystemInfo
location ~ ^/finesse/api/SystemInfo {
 	  limit_except GET OPTIONS { 
        deny all;
      }
      if ($request_method = OPTIONS ) {
	       rewrite ^ /internaloptions$uri last;
	  }
      
      rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
      proxy_pass $scheme://$backend;
      # Don't cache backend server responses in proxy
      proxy_no_cache 1;
      proxy_cache_bypass 1;
}

location ~ ^/internaloptions/(.*)$ {
    set $upstreamservername "Finesse-${http_origin}";
	internal;
	rewrite ^/internaloptions(?<realurl>/.*)$ $realurl break;
  	access_by_lua_file /usr/local/openresty/nginx/lua/checkcorsheaders.lua;
	proxy_pass $scheme://$backend;
	body_filter_by_lua_file  /usr/local/openresty/nginx/lua/cacheoptionsrequests.lua;
}

# This location block is to get list of agents configured in backend server
location ~ ^/finesse/api/Users {
      # Allow access to users api from localhost only
      # Usually called from lua scripts
      if ($is_accessed_locally = "false") { return 403; }
      
      if ($request_method = OPTIONS ) {
           rewrite ^ /internaloptions$uri last;
      }

      proxy_pass $scheme://$backend;

      proxy_ignore_headers Set-Cookie Cache-Control Expires X-Accel-Expires;
      proxy_cache_methods GET;
      proxy_cache_key "$uri";
      proxy_cache_valid 200 10m;
      proxy_cache $rest_cache;
      proxy_cache_lock on;
      proxy_cache_use_stale updating;
      # peform backgroud update of cache
      proxy_cache_background_update on;
      add_header X-ReverseProxy-Cache-Status $upstream_cache_status;
}

location ~ ^/finesse/api/TeamResource/([0-9]+)/Layout(/.*)?$ {

    if ($request_method = OPTIONS ) {
         rewrite ^ /internaloptions$uri last;
    }

    if ($request_method != GET ) {
        return 405;
    }

    rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;

    include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/proxy_headers;
    proxy_pass $scheme://$backend;
    proxy_ignore_headers Set-Cookie Cache-Control Expires X-Accel-Expires;
    proxy_cache_methods GET;
    # Cache key will not have query params as that can lead to cache misses depending on trivial
    # query params like nocache/_=<timestamp>. Category query param is included as part of cache
    # key since that is required for cached ReasonCodes API responses. If any new api is added to cached block
    # in future, their required query param should be taken into account in cache key if any.
    proxy_cache_key "$uri $http_host $arg_role $arg_finesseLayout";
    proxy_cache_bypass $shindig_cache_bypass;
    # Cache LAYOUT data for 5 minutes
    proxy_cache_valid 200 5m;
    proxy_cache $layout_cache;
    add_header X-ReverseProxy-Cache-Status $upstream_cache_status;

}


location ~ ^/finesse/api/(ECCVariableConfig|TeamResource|ChatConfig|MediaDomain|ReasonCode|ConfigInfo|DigitalChannels)(/.*)?$ {

    limit_except GET OPTIONS { 
        deny all;
    }

    # Enable caching only for GET requests
    if ($request_method = GET ) {
        rewrite ^ /internal$uri last;
    }

    if ($request_method = OPTIONS ) {
       rewrite ^ /internaloptions$uri last;
     }
      
    proxy_pass $scheme://$backend;
    proxy_no_cache 1;
    proxy_cache_bypass 1;
}

location ~ ^/internal/finesse/api/(ECCVariableConfig|TeamResource|ChatConfig|MediaDomain|ReasonCode|ConfigInfo|DigitalChannels)(/.*)?$ {
    internal;
    rewrite ^/internal(?<realurl>/.*)$ $realurl break;
	
	rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
    proxy_set_header Range $http_range;
    # Re include common proxy headers as inherited ones will
    # be ignored if proxy_set_header is used inside block
    include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/proxy_headers;
    proxy_pass $scheme://$backend;
    proxy_ignore_headers Set-Cookie Cache-Control Expires X-Accel-Expires;
    proxy_cache_bypass $cb_bypassServerCache_in_query_param;
    proxy_cache_methods GET;
    # Cache key will not have query params as that can lead to cache misses depending on trivial
    # query params like nocache/_=<timestamp>. Category query param is included as part of cache
    # key since that is required for cached ReasonCodes API responses. If any new api is added to cached block
    # in future, their required query param should be taken into account in cache key if any.
    proxy_cache_key "$uri $arg_category $http_range $http_host";
    # Cache REST data for 5 minutes
    proxy_cache_valid 200 5m;
    proxy_cache $rest_cache;
    add_header X-ReverseProxy-Cache-Status $upstream_cache_status;
}

location ~ ^/finesse/api/ScriptSelectors(/.*)?$ {

    limit_except GET OPTIONS {
        deny all;
    }

    # Enable caching only for GET requests
    if ($request_method = GET ) {
        rewrite ^ /internal$uri last;
    }

    if ($request_method = OPTIONS ) {
       rewrite ^ /internaloptions$uri last;
    }

    proxy_pass $scheme://$backend;
    proxy_no_cache 1;
    proxy_cache_bypass 1;
}

location ~ ^/internal/finesse/api/ScriptSelectors(/.*)?$ {
    internal;
    rewrite ^/internal(?<realurl>/.*)$ $realurl break;

    rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
    proxy_set_header Range $http_range;
    # Re include common proxy headers as inherited ones will
    # be ignored if proxy_set_header is used inside block
    include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/proxy_headers;
    proxy_pass $scheme://$backend;
    proxy_ignore_headers Set-Cookie Cache-Control Expires X-Accel-Expires;
    proxy_cache_bypass $cb_bypassServerCache_in_query_param;
    proxy_cache_methods GET;
    # Cache key will have mrdType as the query parameter.
    proxy_cache_key $scheme$proxy_host$uri$is_args$arg_mrdType;
    # Cache REST data for 5 minutes
    proxy_cache_valid 200 5m;
    proxy_cache $rest_cache;
    add_header X-ReverseProxy-Cache-Status $upstream_cache_status;
}

location ~ ^/internal/finesse/api/TeamResource(/.*)?$ {
    internal;
    rewrite ^/internal(?<realurl>/.*)$ $realurl break;

    rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
    
    proxy_set_header Range $http_range;
    # Re include common proxy headers as inherited ones will
    # be ignored if proxy_set_header is used inside block
    include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/proxy_headers;
    proxy_pass $scheme://$backend;
    proxy_ignore_headers Set-Cookie Cache-Control Expires X-Accel-Expires;
    proxy_cache_bypass $cb_bypassServerCache_in_query_param;
    proxy_cache_methods GET;
    # Cache key will not have query params as that can lead to cache misses depending on trivial
    # query params like nocache/_=<timestamp>. Category query param is included as part of cache
    # key since that is required for cached ReasonCodes API responses. If any new api is added to cached block
    # in future, their required query param should be taken into account in cache key if any.
    proxy_cache_key "$uri $arg_category $http_range $http_host";
    # Cache REST data for 5 minutes
    proxy_cache_valid 200 5m;
    proxy_cache $rest_cache;
    add_header X-ReverseProxy-Cache-Status $upstream_cache_status;
}


# To get UserAuthMode
# UserAuthMode API can contain the username or loginid in the URL
location ~ "^/finesse/api/UserAuthMode/([^/]+)/?$" { 

      limit_except GET OPTIONS {
        deny all;
      }

      proxy_pass $scheme://$backend;

      proxy_ignore_headers Set-Cookie Cache-Control Expires X-Accel-Expires;
      proxy_cache_methods GET;
      proxy_cache_key "$uri";
      proxy_cache_valid 200 5m;
      proxy_cache $rest_cache;
      proxy_cache_lock on;
      proxy_cache_use_stale updating;
      # peform backgroud update of cache
      proxy_cache_background_update on;
      add_header X-ReverseProxy-Cache-Status $upstream_cache_status;
}

location ~ ^/finesse/api/User/\w+/CompressedClientLog {
    limit_except POST OPTIONS { 
        deny all;
    }
    if ($request_method = OPTIONS ) {
        rewrite ^ /internaloptions$uri last;
    }
    # Check if the Content-Type is multipart/form-data
    if ($http_content_type !~ "^multipart/form-data") {
        return 415;  # Unsupported Media Type
    }
    # rate limit set for finesse apis
    limit_req zone=finesseratelimit burst=${NGX_FIN_DESKTOP_REQUEST_BURST_LIMIT} nodelay;

    set $authorization_url ${NGX_AUTH_URL};
    set $custom_authorization_header 'authorization';
    # logic to block unauthorized user, checks if the user requesting the finesse api is present in the system.
    # if user is present, rewrites the url to internal/finesse/api which does the authorization through 
    # UserAuth API, else 401 unauthorized is returned.
    rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
    
    
    proxy_pass $scheme://$backend;
    proxy_no_cache 1;
    proxy_cache_bypass 1;
}


# This location block will capture all the finesse API's
location ~ ^/finesse/api/(Users|User|Team|TeamResource|Queues|Queue|Dialog|TeamMessage|TeamMessages|CloudConnectTokenService|CloudConnectMgmtService|Devices)(.*)?$ {
     limit_except GET POST PUT DELETE OPTIONS { 
        deny all;
     }
	 if ($request_method = OPTIONS ) {
           rewrite ^ /internaloptions$uri last;
      }
      # rate limit set for finesse apis
      limit_req zone=finesseratelimit burst=${NGX_FIN_DESKTOP_REQUEST_BURST_LIMIT} nodelay;

	  set $authorization_url ${NGX_AUTH_URL};
	  set $custom_authorization_header 'authorization';
      # logic to block unauthorized user, checks if the user requesting the finesse api is present in the system.
      # if user is present, rewrites the url to internal/finesse/api which does the authorization through 
      # UserAuth API, else 401 unauthorized is returned.
      
      rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
      
      proxy_pass $scheme://$backend;
      proxy_no_cache 1;
      proxy_cache_bypass 1;
}

# This location block will capture all the internal finesse API calls. This is called from 
# client_log which enforces a separate rate limit for those endpoints
location ~ ^/internal/finesse/api/ {
      internal;
      rewrite ^/internal(?<realurl>/.*)$ $realurl last;
}

location = /finesse/api/UserAuth {
      # Allow access to UserAuth api from localhost only
      # Usually called from lua scripts
      if ($is_accessed_locally = "false") { return 403; }
      
      if ($request_method = OPTIONS ) {
           rewrite ^ /internaloptions$uri last;
      }
      proxy_pass $scheme://$backend;
      proxy_no_cache 1;
      proxy_cache_bypass 1;
}
