AuthPlatform/src/util/authcode.lua

64 lines
1.7 KiB
Lua
Raw Normal View History

---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/11/13 22:08
--- 授权码生成和认证
local str = require "resty.string"
local random = require "resty.random"
local cjson = require("cjson.safe")
local _M = {}
-- 生成随机授权码16字节
local function generate_code()
local random_bytes = random.bytes(16)
return str.to_hex(random_bytes)
end
-- 存储授权码有效期5分钟
function _M.create(user_id, client_id, redirect_uri, scope)
local code = generate_code()
print("authorize code:", code)
local code_key = "auth_code-"..code
local code_data = cjson.encode({
user_id = user_id,
client_id = client_id,
redirect_uri = redirect_uri,
scope = scope,
expires_at = ngx.time() + 300 -- 5分钟过期
})
local shared_dict = ngx.shared.codeDict
shared_dict:set(code_key, code_data)
shared_dict:expire(code_key, 300) --时效性为5分钟
return code
end
-- 验证并消费授权码(一次性有效)
function _M.consume(code, client_id)
if code == nil then
return nil, "无效的授权码"
end
local code_key = "auth_code-"..code
local shared_dict = ngx.shared.codeDict
local data = shared_dict:get(code_key)
if data == nil then
return nil, "无效的授权码"
end
-- 消费后立即删除(一次性)
shared_dict:delete(code_key)
local code_data = cjson.decode(data)
--[[
if code_data.client_id ~= client_id then
return nil, "客户端不匹配"
end
--]]
if code_data.expires_at < ngx.time() then
return nil, "授权码已过期"
end
return code_data
end
return _M