# Authentication 示例 - NGINX 配置
#
# 演示如何在 Nginx 中集成 JWT 验证和 Basic Auth。

http {
    # 共享内存区域（用于限流等场景）
    lua_shared_dict auth_cache 10m;

    server {
        listen 8080;
        server_name localhost;

        # ==========================================
        # 场景 1：JWT 验证的受保护端点
        # ==========================================
        location /api/secure {
            access_by_lua_file /path/to/auth/jwt_validate.lua;

            # 验证通过后，可以使用 JWT payload 中的信息
            # ngx.ctx.jwt_payload 包含解码后的 payload
            content_by_lua_block {
                local payload = ngx.ctx.jwt_payload
                if payload and payload.sub then
                    ngx.header["Content-Type"] = "application/json"
                    ngx.say('{"status": "ok", "user": "' .. payload.sub .. '"}')
                else
                    ngx.say('{"status": "ok"}')
                end
            }
        }

        # ==========================================
        # 场景 2：Basic Auth 的受保护端点
        # ==========================================
        location /api/admin {
            access_by_lua_file /path/to/auth/basic_auth.lua;

            content_by_lua_block {
                local user = ngx.ctx.auth_user
                ngx.header["Content-Type"] = "application/json"
                ngx.say('{"status": "ok", "admin": "' .. user .. '"}')
            }
        }

        # ==========================================
        # 场景 3：公开端点（无需认证）
        # ==========================================
        location /api/public {
            content_by_lua_block {
                ngx.header["Content-Type"] = "application/json"
                ngx.say('{"status": "ok", "message": "public endpoint"}')
            }
        }

        # ==========================================
        # 场景 4：组合认证（Basic Auth + JWT）
        # 要求同时通过两种认证
        # ==========================================
        location /api/super-secure {
            access_by_lua_block {
                -- 先校验 Basic Auth（复用基本逻辑，不 exit）
                local cjson = require "cjson.safe"
                local hmac = require "resty.hmac"

                -- Basic Auth
                local auth = ngx.req.get_headers()["Authorization"]
                if not auth or not auth:match("^Basic ") then
                    ngx.status = 401
                    ngx.header["WWW-Authenticate"] = 'Basic realm="Super Secure API"'
                    ngx.header["Content-Type"] = "application/json"
                    ngx.say(cjson.encode({ error = "basic auth required" }))
                    return ngx.exit(401)
                end

                -- JWT
                if not auth:match("^Bearer ") then
                    -- 这里假设 Basic Auth 已通过，再检查 JWT
                    -- 实际场景中 Basic Auth 和 JWT 可能来自不同 header
                end

                -- 简化示例：仅校验 JWT Bearer
                local jwt_token = ngx.req.get_headers()["X-JWT-Token"]
                if not jwt_token then
                    ngx.status = 401
                    ngx.header["Content-Type"] = "application/json"
                    ngx.say(cjson.encode({ error = "JWT token required in X-JWT-Token header" }))
                    return ngx.exit(401)
                end
            }

            content_by_lua_block {
                ngx.header["Content-Type"] = "application/json"
                ngx.say('{"status": "ok", "message": "both auth passed"}')
            }
        }

        # ==========================================
        # 健康检查端点
        # ==========================================
        location /health {
            access_log off;
            return 200 '{"status": "healthy"}';
            add_header Content-Type application/json;
        }
    }
}
