1056 lines
29 KiB
Lua
1056 lines
29 KiB
Lua
---
|
||
--- Generated by EmmyLua(https://github.com/EmmyLua)
|
||
--- Created by admin.
|
||
--- DateTime: 2025/10/15 09:12
|
||
---
|
||
--local snowflake = require("util.snowflake")
|
||
local helpers = require("share.helpers")
|
||
local jsonschema = require("jsonschema")
|
||
local cjson = require("cjson.safe")
|
||
local redis = require("share.redis")
|
||
local jwt = require("resty.jwt")
|
||
|
||
--[[
|
||
local workerId = 0 -- 假设当前机器的ID是1,范围在[0, 31]之间
|
||
local datacenterId = 0 -- 数据中心ID,范围在[0, 31]之间
|
||
local snow = snowflake.new(workerId, datacenterId)
|
||
local id = snow:generateUniqueId()-- 生成ID
|
||
--ngx.say("Generated ID:"..snow.int64_to_string(id))
|
||
--]]
|
||
|
||
--max =a and b or c--a?b:c
|
||
|
||
local STATUS_CODE = {
|
||
-- 成功状态码
|
||
SUCCESS = { code = 200, message = "操作成功" },
|
||
UNKNOWN_ERROR = { code = 9999, message = "未知错误" }
|
||
}
|
||
|
||
local val = STATUS_CODE.SUCCESS
|
||
local status = val or STATUS_CODE.UNKNOWN_ERROR
|
||
local msg = status.message
|
||
ngx.say("message:"..msg)
|
||
|
||
|
||
--local openssl = require("openssl")
|
||
--
|
||
---- 生成RSA密钥对
|
||
--local key = openssl.pkey.new {
|
||
-- algorithm = "RSA",
|
||
-- rsa = {
|
||
-- bits = 2048 -- 密钥长度
|
||
-- }
|
||
--}
|
||
--
|
||
---- 导出私钥和公钥
|
||
--local private_key_pem = key:pem() -- 获取私钥的PEM格式
|
||
--local public_key_pem = key:public_key():pem() -- 获取公钥的PEM格式
|
||
--
|
||
---- 打印密钥
|
||
--ngx.say("Private Key:"..private_key_pem)
|
||
--ngx.say("\nPublic Key:"..public_key_pem)
|
||
--
|
||
local openssl = require "resty.openssl"
|
||
local digest = require "resty.openssl.digest"
|
||
local pkey = require "resty.openssl.pkey"
|
||
local str = require "resty.string"
|
||
|
||
--获取共享字段中的键值
|
||
local key = "11-code"
|
||
local shared_dict = ngx.shared.codeDict
|
||
local codeV = shared_dict:get(key)
|
||
if codeV ~= nil then
|
||
ngx.say("code valus:".. codeV)
|
||
end
|
||
|
||
--删除共享字段中的键值
|
||
--shared_dict:delete(key)
|
||
|
||
local user_id = "11"
|
||
local client_id = "aaaasddd"
|
||
local current_time = ngx.time()
|
||
local code = ngx.md5(user_id .. client_id .. current_time .. math.random())
|
||
ngx.say("code:"..code)
|
||
|
||
ngx.say("-----")
|
||
|
||
-- 正确的schema定义
|
||
local schema = {
|
||
type = "object",
|
||
properties = {
|
||
username = { type = "string" },
|
||
password = { type = "string" },
|
||
captcha = {
|
||
type = { "string", "null" }, -- 允许string或null
|
||
minLength = 0, -- 允许空字符串
|
||
default = "" -- 默认值
|
||
},
|
||
checkKey = {
|
||
type = { "string", "null" },
|
||
minLength = 0,
|
||
default = ""
|
||
}
|
||
},
|
||
required = { "username", "password" } -- 必填字段
|
||
}
|
||
|
||
local schemaToken = {
|
||
type = "object",
|
||
properties = {
|
||
grant_type = { type = "string" },
|
||
code = { type = "string" },
|
||
redirect_uri = { type = "string" },
|
||
},
|
||
required = { "grant_type", "code", "redirect_uri" }
|
||
}
|
||
|
||
-- 原始JSON字符串
|
||
--local jsonStr = [[
|
||
--{
|
||
-- "username": "admin",
|
||
-- "password": "123456",
|
||
-- "captcha": "",
|
||
-- "checkKey": ""
|
||
--}
|
||
--]]
|
||
|
||
--[[
|
||
ngx.req.read_body()
|
||
--获取请求数据
|
||
local jsonStr = ngx.req.get_body_data()
|
||
print("read data:",jsonStr)
|
||
|
||
-- JSON解析函数
|
||
local function parse_json(json_str)
|
||
local ok, data = pcall(cjson.decode, json_str)
|
||
if not ok then
|
||
return nil, "JSON解析失败: "..data
|
||
end
|
||
return data
|
||
end
|
||
|
||
-- 验证函数
|
||
local function validateJson(data)
|
||
local validator = jsonschema.generate_validator(schemaToken)
|
||
local valid, errors = validator(data) -- 注意返回两个值
|
||
|
||
if not valid then
|
||
return false, errors
|
||
end
|
||
return true
|
||
end
|
||
|
||
-- 完整测试流程
|
||
local testData, err = parse_json(jsonStr)
|
||
if testData then
|
||
local isValid, validationErr = validateJson(testData)
|
||
ngx.say(isValid and "验证通过" or "验证失败: "..(validationErr or "未知错误"))
|
||
else
|
||
ngx.say("验证失败: ".."未知错误")
|
||
end
|
||
|
||
do return end
|
||
--]]
|
||
|
||
-- 生成RSA密钥对
|
||
local function generate_rsa_keys(length)
|
||
local key, err = pkey.new({
|
||
type = "RSA",
|
||
bits = length or 2048
|
||
})
|
||
if not key then
|
||
return nil, nil, "生成密钥对失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
-- 提取公钥(PEM格式)
|
||
local pub_pem, err = key:to_PEM("public")
|
||
if not pub_pem then
|
||
return nil, nil, "提取公钥失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
-- 提取私钥(PEM格式)
|
||
local priv_pem, err = key:to_PEM("private")
|
||
if not priv_pem then
|
||
return nil, nil, "提取私钥失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
return pub_pem, priv_pem, nil
|
||
end
|
||
|
||
-- 生成签名(使用私钥)
|
||
local function sign(priv_key_pem, data, algorithm)
|
||
-- 加载私钥
|
||
local priv_key, err = pkey.new(priv_key_pem)
|
||
if not priv_key then
|
||
return nil, "加载私钥失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
-- 处理原始数据(字符串或文件路径)
|
||
local data_str
|
||
if type(data) == "string" then
|
||
if string.find(data, "^/") or string.find(data, "^%.%/") then
|
||
-- 从文件读取
|
||
local file, err = io.open(data, "rb")
|
||
if not file then
|
||
return nil, "读取数据文件失败: " .. (err or "未知错误")
|
||
end
|
||
data_str = file:read("*a")
|
||
file:close()
|
||
else
|
||
-- 直接使用字符串
|
||
data_str = data
|
||
end
|
||
else
|
||
return nil, "原始数据格式错误(需字符串或文件路径)"
|
||
end
|
||
|
||
-- 计算数据摘要
|
||
local md, err = digest.new(algorithm)
|
||
if not md then
|
||
return nil, "初始化摘要算法失败: " .. (err or "未知错误")
|
||
end
|
||
md:update(data_str)
|
||
|
||
-- 使用私钥对摘要签名(RSA-PKCS#1填充)
|
||
local signature, err = priv_key:sign(md)
|
||
if not signature then
|
||
return nil, "签名生成失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
-- 签名转为Base64编码(便于传输)
|
||
return ngx.encode_base64(signature), nil
|
||
end
|
||
|
||
-- 验签函数(使用公钥)
|
||
local function verify(pub_key_pem, data, signature_b64, algorithm)
|
||
-- 加载公钥
|
||
local pub_key, err = pkey.new(pub_key_pem)
|
||
if not pub_key then
|
||
return false, "加载公钥失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
-- 处理原始数据
|
||
local data_str
|
||
if type(data) == "string" then
|
||
if string.find(data, "^/") or string.find(data, "^%.%/") then
|
||
local file, err = io.open(data, "rb")
|
||
if not file then
|
||
return false, "读取数据文件失败: " .. (err or "未知错误")
|
||
end
|
||
data_str = file:read("*a")
|
||
file:close()
|
||
else
|
||
data_str = data
|
||
end
|
||
else
|
||
return false, "原始数据格式错误(需字符串或文件路径)"
|
||
end
|
||
|
||
-- 解码Base64签名为二进制
|
||
local signature, err = ngx.decode_base64(signature_b64)
|
||
if not signature then
|
||
return false, "签名Base64解码失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
-- 计算数据摘要(与签名时一致)
|
||
local md, err = digest.new(algorithm)
|
||
if not md then
|
||
return false, "初始化摘要算法失败: " .. (err or "未知错误")
|
||
end
|
||
md:update(data_str)
|
||
|
||
-- 公钥验签
|
||
local ok, err = pub_key:verify(signature, md)
|
||
if not ok then
|
||
return false, "验签失败: " .. (err or "未知原因")
|
||
end
|
||
return true, nil
|
||
end
|
||
|
||
-- 示例:完整流程(生成密钥对 → 签名 → 验签)
|
||
local function example()
|
||
local original_data = "hello, world" -- 原始数据
|
||
local algorithm = "sha256" -- 签名算法
|
||
|
||
-- 1. 生成RSA密钥对
|
||
local pub_key, priv_key, err = generate_rsa_keys(2048)
|
||
if err then
|
||
ngx.say("密钥对生成失败: ", err)
|
||
return
|
||
end
|
||
ngx.say("公钥:\n", pub_key)
|
||
ngx.say("\n私钥:\n", priv_key)
|
||
ngx.say("\n------------------------")
|
||
|
||
-- 2. 使用私钥生成签名
|
||
local signature_b64, err = sign(priv_key, original_data, algorithm)
|
||
if err then
|
||
ngx.say("签名失败: ", err)
|
||
return
|
||
end
|
||
ngx.say("生成的签名(Base64):\n", signature_b64)
|
||
ngx.say("\n------------------------")
|
||
|
||
-- 3. 使用公钥验签
|
||
local ok, err = verify(pub_key, original_data, signature_b64, algorithm)
|
||
if ok then
|
||
ngx.say("验签成功:数据完整且签名有效")
|
||
else
|
||
ngx.say("验签失败:", err)
|
||
end
|
||
end
|
||
|
||
-- 执行示例
|
||
example()
|
||
|
||
--do
|
||
-- return
|
||
--end
|
||
|
||
-- 公钥加密(用于生成测试数据)
|
||
local function rsa_encrypt(pub_key, plaintext)
|
||
--
|
||
local pkey, err = pkey.new(pub_key)
|
||
if not pkey or not plaintext then
|
||
return nil, "参数错误"
|
||
end
|
||
|
||
local oaep_params = {
|
||
oaep_md = "sha256", -- 对应pkey.lua中的opts.oaep_md
|
||
mgf1_md = "sha256", -- 对应pkey.lua中的opts.mgf1_md
|
||
label = nil
|
||
}
|
||
|
||
local RSA_PKCS1_OAEP_PADDING = "4"
|
||
local ciphertext, err = pkey:encrypt(plaintext, RSA_PKCS1_OAEP_PADDING, oaep_params)
|
||
if not ciphertext then
|
||
return nil, "加密失败: " .. (err or "未知错误")
|
||
end
|
||
-- 返回Base64编码的密文(便于传输存储)
|
||
return ngx.encode_base64(ciphertext), nil
|
||
end
|
||
|
||
-- 私钥解密(核心实现)
|
||
local function rsa_decrypt(priv_key, encrypted_data)
|
||
local pkey, err = pkey.new(priv_key)
|
||
if not pkey or not encrypted_data then
|
||
return nil, "参数错误(私钥或密文为空)"
|
||
end
|
||
|
||
-- 1. 先解码Base64密文
|
||
local ciphertext, err = ngx.decode_base64(encrypted_data)
|
||
if not ciphertext then
|
||
return nil, "Base64解码失败: " .. (err or "无效密文")
|
||
end
|
||
-- 2. 设置解密填充方式(必须与加密时一致)
|
||
local oaep_params = {
|
||
oaep_md = "sha256", -- 对应pkey.lua中的opts.oaep_md
|
||
mgf1_md = "sha256", -- 对应pkey.lua中的opts.mgf1_md
|
||
label = nil
|
||
}
|
||
|
||
local RSA_PKCS1_OAEP_PADDING = "4"
|
||
-- 3. 执行解密
|
||
local result, err = pkey:decrypt(ciphertext, RSA_PKCS1_OAEP_PADDING, oaep_params)
|
||
|
||
if not result then
|
||
return nil, "解密返回空结果"
|
||
end
|
||
|
||
return result, nil -- 返回解密后的原始数据
|
||
end
|
||
|
||
-- 完整测试流程
|
||
local function test_rsa_crypto()
|
||
-- 1. 生成密钥对
|
||
local pub_key, priv_key, err = generate_rsa_keys(2048)
|
||
if err then
|
||
return nil, "密钥生成失败: " .. err
|
||
end
|
||
|
||
ngx.say(pub_key)
|
||
ngx.say("-----")
|
||
ngx.say(priv_key)
|
||
ngx.say("-----")
|
||
-- 2. 原始数据
|
||
local original_text = "这是一段需要加密的敏感数据:123456"
|
||
ngx.say("原始数据: ", original_text)
|
||
|
||
-- 3. 公钥加密
|
||
local encrypted_data, err = rsa_encrypt(pub_key, original_text)
|
||
if err then
|
||
return nil, "加密失败: " .. err
|
||
end
|
||
ngx.say("公钥加密后(Base64): ", encrypted_data)
|
||
|
||
-- 4. 私钥解密
|
||
local decrypted_text, err = rsa_decrypt(priv_key, encrypted_data)
|
||
if err then
|
||
return nil, "私钥解密失败: " .. err
|
||
end
|
||
ngx.say("私钥解密后: ", decrypted_text)
|
||
ngx.say("私钥解密后hex: ", str.to_hex(decrypted_text))
|
||
|
||
-- 5. 验证结果
|
||
if decrypted_text ~= original_text then
|
||
return nil, "解密结果不匹配原始数据"
|
||
end
|
||
|
||
-------------------------------
|
||
-- 要签名的数据
|
||
local md5val = original_text --ngx.md5(original_text) -- 使用MD5作为摘要算法,你也可以使用其他如sha256等
|
||
---- 生成签名------------------
|
||
-- 使用SHA256算法
|
||
local md = digest.new("sha256")
|
||
-- 更新签名上下文,提供数据以供签名
|
||
md:update(md5val)
|
||
-- 完成签名
|
||
local privK, err = pkey.new(priv_key)
|
||
if not privK then
|
||
return nil, "参数错误(私钥或密文为空)"
|
||
end
|
||
local signature, err = privK:sign(md)
|
||
if not signature then
|
||
ngx.log(ngx.ERR, "Failed to generate signature: ", err)
|
||
return
|
||
end
|
||
ngx.say("签名数据1: ", signature)
|
||
local encode_date = ngx.encode_base64(signature)
|
||
ngx.say("签名数据加密后(Base64):", encode_date)
|
||
|
||
---- 验证签名------------------
|
||
local pubK, err = pkey.new(pub_key)
|
||
if not pubK then
|
||
return nil, "参数错误(私钥或密文为空)"
|
||
end
|
||
local digestP = digest.new("sha256")
|
||
-- 更新签名上下文,提供数据以供签名
|
||
digestP:update(md5val)
|
||
local signature1 = ngx.decode_base64(encode_date)
|
||
ngx.say("签名数据2: ", signature1)
|
||
local is_valid = pubK:verify(signature1, digestP) -- 使用与签名相同的摘要算法进行验证
|
||
if is_valid then
|
||
ngx.say("Signature is valid.")
|
||
else
|
||
ngx.say("Signature is invalid.")
|
||
end
|
||
-----------------------------------
|
||
return true, "加密解密验证成功"
|
||
end
|
||
|
||
-- 1. 生成密钥对
|
||
local pub_key, priv_key, err = generate_rsa_keys(2048)
|
||
if err then
|
||
return nil, "密钥生成失败: " .. err
|
||
end
|
||
|
||
-- 私钥和公钥
|
||
local private_key = priv_key
|
||
local public_key = pub_key
|
||
|
||
-- 创建JWT的payload
|
||
local payload = {
|
||
iss = "https://example.com",
|
||
sub = "1234567890",
|
||
name = "John Doe",
|
||
iat = os.time(),
|
||
exp = os.time() + 3600
|
||
}
|
||
|
||
-- 使用私钥生成JWT
|
||
local jwt_obj = jwt:sign(private_key, {
|
||
header = {
|
||
type = "JWT",
|
||
alg = "RS256"
|
||
},
|
||
payload = payload
|
||
})
|
||
if not jwt_obj then
|
||
ngx.say("Failed to generate JWT")
|
||
return
|
||
end
|
||
|
||
ngx.say("Generated JWT: ", jwt_obj)
|
||
|
||
-- 使用公钥校验JWT
|
||
local decoded, res = jwt:verify(public_key, jwt_obj)
|
||
if not decoded then
|
||
ngx.say("Failed to verify JWT: ", cjson.encode(res))
|
||
return
|
||
end
|
||
|
||
ngx.say("JWT is valid: ", cjson.encode(decoded))
|
||
|
||
--local original_text = "这是一段需要加密的敏感数据:123456"
|
||
--local key = x509.PKey()
|
||
--key:generate_key("rsa", 2048) -- 生成 RSA 密钥,2048 位长度
|
||
--
|
||
--local cert = x509.X509()
|
||
--cert:set_version(2) -- 设置证书版本为 2 (RFC 5280)
|
||
--cert:set_serial_number({0x01, 0x02, 0x03}) -- 设置序列号
|
||
--cert:set_issuer_name([[
|
||
-- C=US, ST=Texas, L=Houston, O=Example Inc, OU=IT, CN=example.com
|
||
-- ]]) -- 设置颁发者名称
|
||
--cert:set_subject_name([[
|
||
-- C=US PARTICULARITY, ST=Texas, L=Houston, O=Example Inc, OU=IT, CN=example.com
|
||
-- ]]) -- 设置主题名称(与颁发者相同或不同)
|
||
--cert:set_pubkey(key) -- 设置公钥
|
||
--
|
||
--cert:set_not_before(os.time()) -- 设置生效时间(当前时间)
|
||
--cert:set_not_after(os.time() + 60*60*24*365) -- 设置过期时间(一年后)
|
||
--
|
||
--cert:sign(key, "sha256") -- 使用私钥和 SHA256 签名证书
|
||
--
|
||
--local key_pem = pem.to_pem(key) -- 将密钥转换为 PEM 格式
|
||
--local cert_pem = pem.to_pem(cert) -- 将证书转换为 PEM 格式
|
||
|
||
-- 输出或保存到文件
|
||
--ngx.say(key_pem)
|
||
--ngx.say(cert_pem)
|
||
|
||
-- 执行测试
|
||
local success, msg = test_rsa_crypto()
|
||
if success then
|
||
ngx.say("测试成功: \n", msg)
|
||
else
|
||
ngx.status = 500
|
||
ngx.say("测试失败: \n", msg)
|
||
end
|
||
ngx.say("-----")
|
||
|
||
--[[
|
||
local radix = require("resty.radixtree")
|
||
|
||
-- 路由处理函数注册表
|
||
local function user_handler(m)
|
||
print(m.name)
|
||
print(ngx.ctx.perms)
|
||
end
|
||
|
||
-- 创建路由规则
|
||
local routes = {
|
||
{
|
||
paths = {"/user/:name"},
|
||
methods = {"GET"},
|
||
filter_fun = function(vars)
|
||
ngx.ctx.perms = "system::users::view"
|
||
return true
|
||
end,
|
||
handler = user_handler,
|
||
}
|
||
}
|
||
|
||
-- 初始化radixtree实例
|
||
local rx = radix.new(routes)
|
||
|
||
-- 路由分发主函数
|
||
-- 构建dispatch参数
|
||
local opts = {
|
||
--host = ngx.var.host,
|
||
method = ngx.var.request_method,
|
||
--remote_addr = ngx.var.remote_addr,
|
||
matched = {}
|
||
}
|
||
|
||
-- 使用dispatch方法进行路由匹配
|
||
local ok = rx:dispatch("/user/123", opts, opts.matched)
|
||
--]]
|
||
|
||
--[[
|
||
--获取用户相关的角色数据的数据
|
||
local function init_task()
|
||
local redis = require("share.redis")
|
||
--引用使用的库文件
|
||
local Model = require("share.model")
|
||
--创建一个数据表相关的模型
|
||
local userModel = Model:new('sys_user')
|
||
|
||
--获取数据表中的记录数
|
||
local code, res = userModel:count()
|
||
--redis:set("admin-system:user:add", "1")
|
||
--redis:set("admin-system:user:edit", "1")
|
||
--redis:set("admin-system:user:delete", "1")
|
||
--redis:set("admin-system:user:view", "1")
|
||
--local ok, err = redis:set("admin-system:user:list", "1")
|
||
|
||
--if not ok then
|
||
-- ngx.log(ngx.ERR, "failed to set key in Redis: ", err)
|
||
--else
|
||
-- ngx.log(ngx.INFO, "updated key: ", key, " with value: ", value)
|
||
--end
|
||
|
||
--dict:set("RBAC", "1")
|
||
|
||
ngx.thread.kill(t)
|
||
end
|
||
|
||
--启动线程进行处理
|
||
t = ngx.thread.spawn(init_task)
|
||
--]]
|
||
|
||
--[[
|
||
--调用c库相关例子
|
||
local mylib = require "addlib"
|
||
ngx.say(addlib.add(5,7))
|
||
--]]
|
||
|
||
--local dict = ngx.shared.dictRBAC
|
||
--local value, err = dict:get("zhangsan-system:user:list")
|
||
--if value then
|
||
-- ngx.say("zhangsan-system:user:list is exist")
|
||
--else
|
||
-- ngx.say("zhangsan-system:user:list is not exist")
|
||
--end
|
||
|
||
--[[
|
||
-- 方法1:直接使用EXISTS命令
|
||
local value = redis.call("EXISTS", "admin-system:user:add")
|
||
ngx.say("key value exist:"..value)
|
||
|
||
local val1, err = redis:get("admin-system:user:add")
|
||
local val2, err = redis:get("admin-system:user:edit")
|
||
local val3, err = redis:get("admin-system:user:delete")
|
||
local val4, err = redis:get("admin-system:user:view")
|
||
local val5, err = redis:get("admin-system:user:list")
|
||
ngx.say("add:"..val1)
|
||
ngx.say("edit:"..val2)
|
||
ngx.say("delete:"..val3)
|
||
ngx.say("view:"..val4)
|
||
ngx.say("list:"..val5)
|
||
|
||
local val6, err = redis:get("admin-system:user:test")
|
||
if val6 ~= nil then
|
||
ngx.say("test:"..val6)
|
||
end
|
||
--]]
|
||
|
||
local uuid = require("util.uuid")
|
||
--app_id 应用程序id
|
||
local uid = uuid.generateUuid()
|
||
ngx.say("uuid:"..uid)
|
||
--app_secret 应用程序密钥
|
||
math.randomseed(os.time() + (os.clock() * 1000000)) -- 增强随机性
|
||
local charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||
local result = {}
|
||
for i = 1, #uid do
|
||
local rand = math.random(1, #charset)
|
||
table.insert(result, string.sub(charset, rand, rand))
|
||
end
|
||
|
||
--print(generate_12char_uuid()) -- 示例输出:aB3eF7hJ9kL2
|
||
|
||
--[[
|
||
local args = ngx.req.get_uri_args()
|
||
local pageNum = args["pagenum"] or 1
|
||
local pageSize = args["pagesize"] or 10
|
||
ngx.say("pageNum:", pageNum, " pageSize:", pageSize)
|
||
--]]
|
||
|
||
--[[
|
||
local schema = {
|
||
type = 'object',
|
||
properties = {
|
||
Authorization = {type = 'string', minLength = 10, pattern = 'Bearer\\s+(.+)$'},
|
||
}, required = {"Authorization"}
|
||
}
|
||
|
||
--获取用户认证数据信息
|
||
local data = {}
|
||
local auth_header = ngx.var.http_Authorization
|
||
data.Authorization = auth_header
|
||
local validator = jsonschema.generate_validator(schema)
|
||
local result = validator(data)
|
||
if not result then
|
||
ngx.log(ngx.WARN, "令牌格式不正确")
|
||
ngx.status = ngx.HTTP_UNAUTHORIZED
|
||
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
||
end
|
||
local token = string.sub(auth_header,8)
|
||
ngx.say(token)
|
||
--]]
|
||
|
||
--local sampleJson = [[{"raw_header":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9","signature":"zkKAmXifqWDrMaLpXe8hrA1JpDRbdlgwS-yxNnQUOBw","raw_payload":"eyJpYXQiOjE3NjE4OTIwNDMsImV4cCI6MTc2MTg5NTY0MywidXNlcmlkIjoiYWRtaW4iLCJyb2xlIjoiIn0","valid":true,"verified":true,"reason":"everything is awesome~ :p","header":{"alg":"HS256","typ":"JWT"},"payload":{"iat":1761892043,"userid":"admin","exp":1761895643,"role":""}}]]
|
||
----解析json字符串
|
||
--local data = cjson.decode(sampleJson);
|
||
----打印json字符串中的age字段
|
||
--ngx.say(data["raw_header"]);
|
||
----打印数组中的第一个值(lua默认是从0开始计数)
|
||
--ngx.say(data["payload"]["userid"]);
|
||
|
||
--[[
|
||
local jwttoken = require("util.token")
|
||
--获取请求头中的令牌数据
|
||
local auth_header = ngx.var.http_Authorization
|
||
--调用令牌校验
|
||
local result = jwttoken.authorizationToken((auth_header))
|
||
-- 输出结果
|
||
ngx.say(cjson.encode(result))
|
||
ngx.exit(result.code)
|
||
--]]
|
||
|
||
--[[
|
||
local jsonschema = require("jsonschema")
|
||
|
||
-- 定义一个JSON Schema
|
||
-- 定义一个JSON Schema
|
||
local schema = {
|
||
{type = "object", properties = {
|
||
{name = "username", type = "string"},
|
||
{name = "phone", type = "string"},
|
||
{name = "email", type = "string"},
|
||
{name = "idcard", type = "string"},
|
||
{name = "name", type = "string"},
|
||
{name = "office_phone", type = "string"},
|
||
{name = "telephone", type = "string"},
|
||
{name = "display_name", type = "string"},
|
||
}, required = {"username", "phone", "email", "idcard"}}
|
||
}
|
||
|
||
-- 待验证的JSON数据
|
||
--local json_data = '{"name": "Alice", "age": 30}'
|
||
--local data, pos, err = cjson.decode(json_data)
|
||
--if err then
|
||
-- error("JSON decoding error: " .. err)
|
||
--end
|
||
--读取请求体的数据
|
||
ngx.req.read_body()
|
||
--获取请求数据
|
||
local body_data = ngx.req.get_body_data()
|
||
|
||
-- 验证数据是否符合schema
|
||
local ok, err = jsonschema:generate_validator(body_data, schema)
|
||
if not ok then
|
||
error("Validation failed: " .. err)
|
||
else
|
||
print("Validation succeeded!")
|
||
end
|
||
--]]
|
||
|
||
--[[
|
||
--用于接收前端数据的对象
|
||
local args=nil
|
||
--获取前端的请求方式 并获取传递的参数
|
||
local request_method = ngx.var.request_method
|
||
--判断是get请求还是post请求并分别拿出相应的数据
|
||
if"GET" == request_method then
|
||
args = ngx.req.get_uri_args()
|
||
elseif "POST" == request_method then
|
||
ngx.req.read_body()
|
||
args = ngx.req.get_post_args()
|
||
--兼容请求使用post请求,但是传参以get方式传造成的无法获取到数据的bug
|
||
if (args == nil or args.data == null) then
|
||
args = ngx.req.get_uri_args()
|
||
end
|
||
end
|
||
|
||
--获取前端传递的name值
|
||
local name =
|
||
--响应前端
|
||
ngx.say("linux hello:"..name)
|
||
--]]
|
||
|
||
--[[
|
||
local M = {}
|
||
local charset = {} do -- [0-9a-zA-Z]
|
||
for c = 48, 57 do table.insert(charset, string.char(c)) end
|
||
for c = 65, 90 do table.insert(charset, string.char(c)) end
|
||
for c = 97, 122 do table.insert(charset, string.char(c)) end
|
||
end
|
||
function M.uuid(length)
|
||
local res = ""
|
||
for i = 1, length do
|
||
res = res .. charset[math.random(1, #charset)]
|
||
end
|
||
return res
|
||
end
|
||
return M
|
||
--]]
|
||
|
||
--[[
|
||
local jwt = require("resty.jwt")
|
||
|
||
local secret_key = "!@#$5412$#@!" -- 确保这个密钥足够安全并保密
|
||
|
||
--设置JWT的有效载荷
|
||
local obj = {
|
||
header = {typ="JWT", alg="HS256"},
|
||
payload = { -- 自定义数据
|
||
username = "admin",
|
||
role = "admin",
|
||
iss = "your_issuer", -- 签发者
|
||
sub = "1234567890", -- 主题
|
||
exp = os.time() + 3600, -- 过期时间(例如:当前时间+1小时)
|
||
iat = os.time() -- 签发时间
|
||
}
|
||
}
|
||
local jwt_token = jwt:sign(secret_key, obj)
|
||
ngx.say(jwt_token)
|
||
|
||
local jwt_obj = jwt:verify(secret_key, jwt_token)
|
||
local param = cjson.encode(jwt_obj)
|
||
ngx.say(param)
|
||
|
||
local ok, claims = jwt:verify(jwt_token) -- 使用之前生成的token
|
||
if ok then
|
||
print("Token is valid")
|
||
for k, v in pairs(claims) do
|
||
print(k, v)
|
||
end
|
||
else
|
||
print("Token is invalid:", claims) -- claims将包含错误信息
|
||
end
|
||
--]]
|
||
|
||
--[[
|
||
--创建新的JWT对象
|
||
--local jwt_obj = jwt:new()
|
||
--设置密钥
|
||
local secret_key = "!@#$5412$#@!" -- 确保这个密钥足够安全并保密
|
||
--jwt_obj:set_secret(secret_key)
|
||
|
||
--设置JWT的有效载荷
|
||
local payload = {
|
||
iss = "your_issuer", -- 签发者
|
||
exp = os.time() + 3600, -- 过期时间(例如:当前时间+1小时)
|
||
iat = os.time(), -- 签发时间
|
||
sub = "1234567890", -- 主题
|
||
data = { -- 自定义数据
|
||
username = "admin",
|
||
role = "admin"
|
||
}
|
||
}
|
||
-- 生成JWT token
|
||
local jwt_token, err = jwt:sign(secret_key, payload)
|
||
if err then
|
||
error("Failed to generate JWT token: " .. err)
|
||
end
|
||
|
||
print("Generated JWT Token:", jwt_token)
|
||
|
||
|
||
local ok, claims = jwt:verify(jwt_token) -- 使用之前生成的token
|
||
if ok then
|
||
print("Token is valid")
|
||
for k, v in pairs(claims) do
|
||
print(k, v)
|
||
end
|
||
else
|
||
print("Token is invalid:", claims) -- claims将包含错误信息
|
||
end
|
||
--]]
|
||
|
||
--[[
|
||
local perm = require("util.permissionfilter")
|
||
local perms = {}
|
||
--获取角色的所所有全新信息
|
||
local rest = perm:getRolePermissions("admin")
|
||
for _, key in ipairs(rest) do
|
||
table.insert(perms, key)
|
||
end
|
||
local val = table.concat(perms, ",")
|
||
ngx.say(val)
|
||
|
||
local exist = perm:hasPermission("admin", "system::users::add")
|
||
if exist then
|
||
ngx.say("权限可以使用")
|
||
else
|
||
ngx.say("权限不能使用")
|
||
end
|
||
|
||
--清除角色的权限数据
|
||
--perm:clearRolePermissions("admin")
|
||
--]]
|
||
|
||
--[[
|
||
local generateCert = require("util.generatorssl")
|
||
-- 使用示例
|
||
local success, files = generateCert:generate_self_signed_cert(
|
||
"example.com",
|
||
365,
|
||
2048,
|
||
"./ssl_certs"
|
||
)
|
||
|
||
if success then
|
||
print("SSL证书生成成功:")
|
||
print("私钥文件: "..files.key)
|
||
print("证书文件: "..files.cert)
|
||
else
|
||
print("证书生成失败")
|
||
end
|
||
--]]
|
||
|
||
--[[
|
||
--读取用户表、角色表和权限表中配置的权限数据
|
||
local roleDao = require("dao.role")
|
||
--获取数据表中的记录数
|
||
local code, res = roleDao:getAllSystemRoles()
|
||
if res == nil then return end
|
||
--读取角色id和角色名称
|
||
for _, row in pairs(res) do
|
||
--row.id:1
|
||
--row.create_by:admin
|
||
--row.create_time:
|
||
--row.role_name:admin
|
||
--row.status:0,
|
||
--row.remark:超级管理员
|
||
--row.role_key:超级管理员
|
||
print(row.id..row.create_by..row.role_name)
|
||
end
|
||
--]]
|
||
|
||
--[[
|
||
--获取数据表中的记录数
|
||
local code, res = userModel:count()
|
||
ngx.say(res)
|
||
|
||
--查询表中id为1的数据记录
|
||
code, res = userModel:find("1")
|
||
if res ~= nil then
|
||
ngx.say(table.getn(res))
|
||
end
|
||
--查询表中的所有记录
|
||
code, res = userModel:all()
|
||
--显示查询到的数据记录
|
||
if code == 0 then
|
||
for _, row in ipairs(res) do
|
||
for key, value in pairs(row) do
|
||
ngx.say(key .. ":" .. tostring(value))
|
||
end
|
||
end
|
||
end
|
||
|
||
--分页 获取数据表中的记录
|
||
local data = nil
|
||
code, data = userModel:paginate(1, 10)
|
||
local count = data.total
|
||
ngx.say("data total:", count)
|
||
for _, row in ipairs(data.data) do
|
||
ngx.say("begin show data:")
|
||
for key, value in pairs(row) do
|
||
ngx.say(key .. ":" .. tostring(value))
|
||
end
|
||
end
|
||
|
||
ngx.say("----begin where and query---")
|
||
-- 返回 users 表中 username 字段的值是 `cgreen` 的,`password` 字段的值是 `xxxxxx` 的多条数据,注意此处返回是 table 数组,`first()` 方法返回的是单条数据
|
||
code, res = userModel:where('name','=','zhangsan'):where('password','=','111111'):get()
|
||
--ngx.say(code)
|
||
--if res ~= nil then
|
||
-- for _, row in ipairs(res) do
|
||
-- for key, value in pairs(row) do
|
||
-- ngx.say(key .. ":" .. tostring(value))
|
||
-- end
|
||
-- end
|
||
--end
|
||
--]]
|
||
|
||
--[[
|
||
--ngx.say("----begin where or query---")
|
||
-- 返回 `name` 为 `xxx` 或者 `yyy` 的所有用户 table 数组
|
||
code, res = userModel:where('name','=','zhangsan'):orwhere('name','=','admin'):get()
|
||
--for _, row in ipairs(res) do
|
||
-- for key, value in pairs(row) do
|
||
-- ngx.say(key .. ":" .. tostring(value))
|
||
-- end
|
||
--end
|
||
|
||
--orderby(column, option)方法,第一个参数传入排序的列名,第二个参数默认为ASC 也可以传入 ASC 正序 或 DESC 倒序(不区分大小写),
|
||
code, res = userModel:orderby('created_time'):get()
|
||
--for _, row in ipairs(res) do
|
||
-- for key, value in pairs(row) do
|
||
-- ngx.say(key .. ":" .. tostring(value))
|
||
-- end
|
||
--end
|
||
|
||
-- 创建一个用户
|
||
code, res = userModel:create({
|
||
id='3',
|
||
password='22222',
|
||
name='lisi',
|
||
email='lisi@gmail.com',
|
||
})
|
||
|
||
-- 更新 id = 1 的 user 的 name 为 test, avatar 为 NULL
|
||
code, res = userModel:where('id', '=', '3'):update({
|
||
phone='666666',
|
||
email='zhangsan@qq.com'
|
||
})
|
||
--输出更新后影响的行总数
|
||
ngx.say("update affected_rows: ", res.affected_rows)
|
||
|
||
-- 删除 id = 1 的用户
|
||
code, res = userModel:where('id','=','3'):delete()
|
||
ngx.say("delete affected_rows: ", res.affected_rows)
|
||
--]]
|
||
|
||
--[[
|
||
--读取请求体的数据
|
||
ngx.req.read_body()
|
||
--获取请求数据
|
||
local body_data = ngx.req.get_body_data()
|
||
ngx.say(body_data)
|
||
|
||
local data = cjson.decode(body_data)
|
||
--键值为id产生uuid数据值,增加到json中
|
||
data.id = helpers.getUuid()
|
||
local ret = helpers.convert_json(data)
|
||
ngx.say(ret)
|
||
--]]
|
||
|
||
--local header = ngx.req.get_headers()
|
||
--for k,v in pairs(header) do
|
||
-- ngx.say("[header] name:", k, "value:", v)
|
||
--end
|
||
|
||
--local payloads = ngx.req.get_uri_args()
|
||
--for k,v in pairs(payloads) do
|
||
-- ngx.say("[params] name:", k, " value:", v)
|
||
--end
|
||
|
||
--去掉组装最后一位逗号(,)
|
||
--local newKeys = keys:sub(1, #keys -1)
|
||
--local newValues = values:sub(1, #values -1)
|
||
|
||
--[[
|
||
--读取请求体的数据
|
||
--ngx.req.read_body()
|
||
|
||
--获取请求数据
|
||
local body_data = ngx.req.get_body_data()
|
||
|
||
if not body_data then
|
||
ngx.say("read file error:", err)
|
||
return ngx.exit(400)
|
||
end
|
||
local len = #body_data
|
||
|
||
local file_name = ngx.req.get_body_file()
|
||
ngx.say("file length:", len)
|
||
|
||
ngx.req.read_body_in_buffer(ngx.var.request_body_file)
|
||
|
||
ngx.say(body_data)
|
||
--]]
|
||
|
||
--[[
|
||
local cjson = require("cjson.safe")
|
||
local file_path = "/home/frankly/work/test.dat"
|
||
local file_length = 1024 * 1024 * 400
|
||
local f, err = io.input(file_path, "r")
|
||
if not f then
|
||
ngx.say("read file error:"..err)
|
||
return
|
||
end
|
||
local content = f:read(file_length) --读取文件内容
|
||
f:close() --关闭文件
|
||
--ngx.say(content)
|
||
local res = {
|
||
key = "data",
|
||
value = content
|
||
}
|
||
--ngx.header["Length"] = #content
|
||
ngx.header["Content-Type"] = 'application/json; charset=UTF-8'
|
||
ngx.say(cjson.encode(res))
|
||
ngx.log(ngx.INFO, "send data success")
|
||
--]] |