zhangqian
2024-01-12 fea217048591823280a888b6c26f68558e51dded
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
local jwt = require "resty.jwt"
local secret = "327a9457-899a-481e-8b30-58cc97e5b808"
 
local M = {}
 
function logPrint(msg)
    ngx.log(ngx.ERR, msg)
end
 
function M.proxy(key_prefix)
    local aps_nodes = ngx.shared.aps_nodes_map
 
    -- 读取header
    local auth_header = ngx.var.http_Authorization
    if auth_header == nil then
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
 
    if auth_header .. "" == "" then
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
 
    -- 获取jwt token
    local _, _, token = string.find(auth_header, "Bearer%s+(.+)")
    if token .. "" == "" then
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
 
    -- 验证token
    local jwt_obj = jwt:verify(secret, token)
    if jwt_obj.verified == false then
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
 
    local parent_id = jwt_obj["payload"]["ParentId"]
    if parent_id == nil then
        logPrint("ParentId in token is nil")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
 
    
    --search real ip and port to redirect to by parent_id
    local node_addr = aps_nodes:get(key_prefix .. parent_id)
    if not node_addr then
        ngx.exit(ngx.HTTP_BAD_GATEWAY)
    end
 
    logPrint("aps current parentid is "..parent_id.." key_prefix:"..key_prefix.. " node_addr:"..node_addr)
    ngx.var.proxy_aps_server = "http://" .. node_addr
end
 
return M