# Rate limit authcode and token request
location ~ ^/desktop/sso/authcode {
	limit_req zone=ssovalveratelimit burst=${NGX_FIN_SSOVALVE_REQUEST_BURST_LIMIT} nodelay;
	proxy_pass $scheme://$backend;
	proxy_no_cache 1;
	proxy_cache_bypass 1;
	# Cache access token from response cookie
	header_filter_by_lua_block {
		-- HTTP 302 will have token in response cookies. This flow is triggered from desktop
		if (ngx.status == ngx.HTTP_MOVED_TEMPORARILY)
		then
			local _ssoutils = require("ssoutils")
			_ssoutils.cacheTokenFromResponseCookies();
		end
	}
	# Cache access token from response body
	body_filter_by_lua_block {
		-- HTTP 200 will have token in response body. This is usually sent for token/tokenpair
		-- requests by thirdparty clients i.e direct call to /sso/token endpoint initially
		if (ngx.status == ngx.HTTP_OK)
		then
			local _ssoutils = require("ssoutils")
			_ssoutils.cacheTokenFromResponseBody();
		end
	}
}

location ~ ^/desktop/sso/token {
	limit_except POST GET OPTIONS { deny all; }
	limit_req zone=ssovalveratelimit burst=${NGX_FIN_SSOVALVE_REQUEST_BURST_LIMIT} nodelay;
	proxy_pass $scheme://$backend;
	proxy_no_cache 1;
	proxy_cache_bypass 1;
	# Cache refreshed access token
	body_filter_by_lua_block {
		if (ngx.status == ngx.HTTP_OK)
		then
			local _ssoutils = require("ssoutils")
			_ssoutils.cacheTokenFromResponseBody();
		end
	}
}

# SSO test need not be exposed as admin interfaces are not exposed.
# Only admin interfaces uses test endpoints.
# Blocking the same
location ~ ^/desktop/sso/test(/)?$ {
	return 403;
}
