# nginx.vh.default.conf  --  docker-openresty
#
# This file is installed to:
#   `/etc/nginx/conf.d/`
#
# It tracks the `server` section of the upstream OpenResty's `nginx.conf`.
#
# This config (and any other configs in `etc/nginx/conf.d/`) is loaded by
# default by the `include` directive in `/usr/local/openresty/nginx/conf/nginx.conf`.
#
# See https://github.com/openresty/docker-openresty/blob/master/README.md#nginx-config-files
#

# cache for JWT verification results
lua_shared_dict introspection 10m;

server
{
	listen ${port};

	location /
	{
		proxy_pass ${gateway-url};
		proxy_set_header X-forwarded-host $host;
		proxy_buffering off;

		access_by_lua_block
		{
			local opts =
			{
				discovery = "${discovery-url}",
				client_id = "${client-id}",
				client_secret = "${client-secret}",
				redirect_uri_scheme = ngx.var.scheme,
				ssl_verify = "no",
				scope = "openid",
				redirect_uri_path = "/oauth2",
				post_logout_redirect_uri = ngx.var.scheme .. "://" .. ngx.var.host .. ":" .. ngx.var.server_port .. "/",
			}

			if
				ngx.req.get_headers().authorization == nil or
				string.find(ngx.req.get_headers().authorization,"Bearer") == nil
			then
				res, err = ngx.ctx.authorization_code_flow(opts)
				user = not(err) and res.user.${user-field} or nil
			else
				res, err = require("resty.openidc").bearer_jwt_verify(opts)
				user = not(err) and res.${user-field} or nil
			end

			if err then
				ngx.status = ngx.HTTP_UNAUTHORIZED
				ngx.say(err)
				ngx.exit(ngx.HTTP_UNAUTHORIZED)
			end

			ngx.req.set_header("${header-name}", user)
		}

		rewrite_by_lua_block
		{
			ngx.ctx.authorization_code_flow = 
			function(opts)

				if
					require("resty.openidc").access_token() == nil and
					not(ngx.req.get_headers().accept == nil) and
					string.find(ngx.req.get_headers().accept,"html") == nil
				then
					ngx.exit(ngx.HTTP_UNAUTHORIZED)
				end

				return require("resty.openidc").authenticate(opts)

			end
		}
	}

	#error_page 404 /404.html;

	# redirect server error pages to the static page /50x.html
	#
	error_page 500 502 503 504 /50x.html;
	location = /50x.html
	{
		root /usr/local/openresty/nginx/html;
	}
}
