删除不需要的库文件,修改数据库中验证问题,增加初始化文件,修改配置实现简单的内存共享测试功能

This commit is contained in:
wanglei 2025-11-04 09:33:40 +08:00
parent 42b62500e4
commit 3323d1d82c
15 changed files with 102 additions and 20 deletions

View File

@ -13,8 +13,10 @@ http {
client_max_body_size 1024M; #允许最大100k的请求体 client_max_body_size 1024M; #允许最大100k的请求体
client_body_buffer_size 1024M; #设置缓冲区大小 client_body_buffer_size 1024M; #设置缓冲区大小
#lua_code_cache off; #关闭代码缓存修改lua脚本不需要重启
lua_package_path '$prefix/src/?/?.lua;$prefix/src/?.lua;/home/frankly/work/AuthPlatform/src/?/?.lua;/home/frankly/work/AuthPlatform/src/?.lua;;'; lua_package_path '$prefix/src/?/?.lua;$prefix/src/?.lua;/home/frankly/work/AuthPlatform/src/?/?.lua;/home/frankly/work/AuthPlatform/src/?.lua;;';
lua_package_cpath '$prefix/src/share/lib/?.so;;'; lua_package_cpath '$prefix/src/share/lib/?.so;/home/frankly/work/AuthPlatform/src/share/lib/?.so;;';
# Path of the file with trusted CA certificates. # Path of the file with trusted CA certificates.
#lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; #lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
@ -22,6 +24,21 @@ http {
# The verification depth in the server certificates chain. # The verification depth in the server certificates chain.
#lua_ssl_verify_depth 3; #lua_ssl_verify_depth 3;
# Nginx 启动时执行的 Lua 代码块
lua_shared_dict dict_a 1m;
init_by_lua_block {
-- 定义一个全局变量
ngx.log(ngx.INFO, "Initializing global variable")
global_var = "Hello, Nginx with Lua!"
-- 初始化一个共享字典(需要 lua-shared-dict 模块)
local shared_dict = ngx.shared.dict_a
shared_dict:set("key", "value")
}
#下面代码不能与上面的代码进行共用否则报错nginx: [emerg] "init_by_lua_file" directive is duplicate
#init_by_lua_file '/home/frankly/work/AuthPlatform/src/init.lua';
server { server {
listen 9080; listen 9080;
server_name 127.0.0.1; server_name 127.0.0.1;
@ -33,7 +50,6 @@ http {
## 应用路径 todo 路径问题 ## 应用路径 todo 路径问题
set $APP_PATH '/home/frankly/work/AuthPlatform'; set $APP_PATH '/home/frankly/work/AuthPlatform';
#access_by_lua_file '${APP_PATH}/src/auth/jwt-auth.lua';
#数据列表配置 #数据列表配置
include 'system/system.conf'; include 'system/system.conf';
@ -41,6 +57,9 @@ http {
location /testSQL { location /testSQL {
content_by_lua_file '${APP_PATH}/src/test/testPostgres.lua'; content_by_lua_file '${APP_PATH}/src/test/testPostgres.lua';
} }
location /testRBAC {
content_by_lua_file '${APP_PATH}/src/test/testRBAC.lua';
}
location /cjson { location /cjson {
content_by_lua_file '${APP_PATH}/src/test/test.lua'; content_by_lua_file '${APP_PATH}/src/test/test.lua';
} }
@ -49,5 +68,19 @@ http {
access_by_lua_file '${APP_PATH}/src/auth/jwt-auth.lua'; access_by_lua_file '${APP_PATH}/src/auth/jwt-auth.lua';
proxy_pass http://192.168.147.1:3000; proxy_pass http://192.168.147.1:3000;
} }
location = /testSM {
content_by_lua_block {
cjson = require "cjson.safe"
ngx.say(cjson.encode({a = 1, b = 2}))
local dict_a = ngx.shared.dict_a;
ngx.say("abc=",dict_a:get("abc"))
-- 访问全局变量
ngx.say("Global variable: ", global_var)
-- 访问共享字典
ngx.say("Shared dict value: ", dict_a:get("key"))
}
}
} }
} }

View File

@ -43,7 +43,7 @@ if jwt_obj.verified == false then
end end
--判断token是否超时 --令牌已过期 --判断token是否超时 --令牌已过期
if jwt_obj.payload.exp and os.time() > jwt_obj.payload.exp then if jwt_obj.payload.exp and ngx.time() > jwt_obj.payload.exp then
ngx.log(ngx.WARN, "token timeout ".. jwt_obj.reason) ngx.log(ngx.WARN, "token timeout ".. jwt_obj.reason)
ngx.status = ngx.HTTP_UNAUTHORIZED ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.exit(ngx.HTTP_UNAUTHORIZED) ngx.exit(ngx.HTTP_UNAUTHORIZED)

View File

@ -84,6 +84,7 @@ function _M:updateSystemAccount(id, jsonData)
if ok == false then if ok == false then
return 0x000001,nil return 0x000001,nil
end end
jsonData.update_time = ngx.time()
--对数据内容进行更新 --对数据内容进行更新
return accountModel:where('id', '=', id):update(jsonData) return accountModel:where('id', '=', id):update(jsonData)
end end

View File

@ -99,7 +99,8 @@ function _M.updateApplication(id, jsonData)
if ok == false then if ok == false then
return 0x000001,nil return 0x000001,nil
end end
--对数据内容进行更新 --对数据内容进行更
jsonData.update_time = ngx.time()
return applicationModel:where('id', '=', id):update(jsonData) return applicationModel:where('id', '=', id):update(jsonData)
end end

View File

@ -83,6 +83,7 @@ function _M.updateSystemDepartment(id, jsonData)
if ok == false then if ok == false then
return 0x000001,nil return 0x000001,nil
end end
jsonData.update_time = ngx.time()
--对数据内容进行更新 --对数据内容进行更新
return departmentModel:where('id', '=', id):update(jsonData) return departmentModel:where('id', '=', id):update(jsonData)
end end

View File

@ -91,6 +91,7 @@ function _M.updateSystemPermission(id, jsonData)
if ok == false then if ok == false then
return 0x000001,nil return 0x000001,nil
end end
jsonData.update_time = ngx.time()
--对数据内容进行更新 --对数据内容进行更新
return permissionModel:where('id', '=', id):update(jsonData) return permissionModel:where('id', '=', id):update(jsonData)
end end

View File

@ -84,6 +84,7 @@ function _M:updateSystemRole(id, jsonData)
if ok == false then if ok == false then
return 0x000001,nil return 0x000001,nil
end end
jsonData.update_time = ngx.time()
--对数据内容进行更新 --对数据内容进行更新
return roleModel:where('id', '=', id):update(jsonData) return roleModel:where('id', '=', id):update(jsonData)
end end

14
src/init.lua Normal file
View File

@ -0,0 +1,14 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by frankly.
--- DateTime: 2025/11/3 18:44
---
print("init application...")
cjson = require "cjson"
local dict_a = ngx.shared.dict_a
local v = dict_a:get("abc")
if not v then
dict_a:set("abc", 9)
end

View File

@ -7,9 +7,22 @@ local resp = require("util.response")
local userDao = require("dao.user") local userDao = require("dao.user")
local validatorJson = require("validator.system.user") local validatorJson = require("validator.system.user")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local token = require("util.token")
local _M = {} local _M = {}
--验证用户id与token中的用户id是否一致
local function getUserId()
--获取请求头中的令牌数据
local auth_header = ngx.var.http_Authorization
--验证数据的正确性
local retToken = token.authorizationToken(auth_header)
--token前面已经进行验证不需要进行判断
--验证成功获取用户id信息
local userid = retToken["body"]["payload"]["userid"]
return userid
end
--获取所有用户信息 --获取所有用户信息
function _M.getSystemUsers() function _M.getSystemUsers()
--获取页码和请求的数据量 --获取页码和请求的数据量
@ -23,6 +36,12 @@ end
--根据用户id获取用户信息 --根据用户id获取用户信息
function _M.getSystemUser(m) function _M.getSystemUser(m)
local userid = getUserId()
if userid ~= m.id then
ngx.log(ngx.WARN, "用户与使用token中的用户id不一致")
ngx.status = ngx.HTTP_NOT_ALLOWED
ngx.exit(ngx.HTTP_NOT_ALLOWED)
end
local code,ret = userDao.getSystemUser(m.id) local code,ret = userDao.getSystemUser(m.id)
local result = resp:json(code, ret) local result = resp:json(code, ret)
resp:send(result) resp:send(result)
@ -59,6 +78,12 @@ end
--根据用户id删除用户信息 --根据用户id删除用户信息
function _M.updateSystemUser(m) function _M.updateSystemUser(m)
local userid = getUserId()
if userid ~= m.id then
ngx.log(ngx.WARN, "用户与使用token中的用户id不一致")
ngx.status = ngx.HTTP_NOT_ALLOWED
ngx.exit(ngx.HTTP_NOT_ALLOWED)
end
--读取请求体的数据 --读取请求体的数据
ngx.req.read_body() ngx.req.read_body()
--获取请求数据 --获取请求数据

Binary file not shown.

View File

@ -127,23 +127,23 @@ end
--获取当前时间戳(毫秒) --获取当前时间戳(毫秒)
function snowflake:getCurrentTimestamp() function snowflake:getCurrentTimestamp()
local timestamp = os.time() local timestamp = ngx.time()
return timestamp return timestamp
end end
--获取新的时间戳 --获取新的时间戳
function snowflake:getNextTimestamp(lastTimestamp) function snowflake:getNextTimestamp(lastTimestamp)
local timestamp = math.floor(os.time()); local timestamp = math.floor(ngx.time());
while (timestamp <= lastTimestamp) while (timestamp <= lastTimestamp)
do do
timestamp = math.floor(os.time()); timestamp = math.floor(ngx.time());
end end
return timestamp; return timestamp;
end end
-- 雪花算法的实现 -- 雪花算法的实现
function snowflake:generateUniqueId() function snowflake:generateUniqueId()
--local curtime = os.time() --local curtime = ngx.time()
--print("current time: ", curtime) --print("current time: ", curtime)
local timestamp = self.getCurrentTimestamp() -- 当前时间戳(毫秒) local timestamp = self.getCurrentTimestamp() -- 当前时间戳(毫秒)
-- 如果是同一时间生成的,则进行毫秒内序列 -- 如果是同一时间生成的,则进行毫秒内序列

View File

@ -7,7 +7,7 @@
local helpers = require("share.helpers") local helpers = require("share.helpers")
local jsonschema = require("jsonschema") local jsonschema = require("jsonschema")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
--
--local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间 --local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间
--local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间 --local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间
--local snow = snowflake.new(workerId, datacenterId) --local snow = snowflake.new(workerId, datacenterId)
@ -16,6 +16,9 @@ local cjson = require("cjson.safe")
--max =a and b or c--a?b:c --max =a and b or c--a?b:c
local mylib = require "addlib"
ngx.say(addlib.add(5,7))
--[[ --[[
local uuid = require("resty.jit-uuid") local uuid = require("resty.jit-uuid")
uuid.seed() uuid.seed()
@ -33,6 +36,7 @@ local pageSize = args["pagesize"] or 10
ngx.say("pageNum:", pageNum, " pageSize:", pageSize) ngx.say("pageNum:", pageNum, " pageSize:", pageSize)
--]] --]]
--[[
local schema = { local schema = {
type = 'object', type = 'object',
properties = { properties = {
@ -53,6 +57,7 @@ if not result then
end end
local token = string.sub(auth_header,8) local token = string.sub(auth_header,8)
ngx.say(token) 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":""}}]] --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字符串 ----解析json字符串

View File

@ -26,7 +26,7 @@ permission_system:assign_role("user002", "user_manager")
permission_system:assign_role("admin001", "super_admin") permission_system:assign_role("admin001", "super_admin")
-- 测试权限验证 -- 测试权限验证
print("=== RBAC权限验证测试 ===") ngx.say("=== RBAC权限验证测试 ===")
-- 测试用户001guest角色 -- 测试用户001guest角色
local test_cases = { local test_cases = {
@ -46,17 +46,17 @@ local test_cases = {
for _, test in ipairs(test_cases) do for _, test in ipairs(test_cases) do
local result = permission_system:check_permission(test.user_id, test.resource, test.action) local result = permission_system:check_permission(test.user_id, test.resource, test.action)
local status = result == test.expected and "✓ 通过" or "✗ 失败" local status = result == test.expected and "✓ 通过" or "✗ 失败"
print(string.format("%s 用户:%s 资源:%s 方法:%s 结果:%s", ngx.say(string.format("%s 用户:%s 资源:%s 方法:%s 结果:%s",
status, test.user_id, test.resource, test.action, tostring(result))) status, test.user_id, test.resource, test.action, tostring(result)))
end end
-- 显示用户权限列表 -- 显示用户权限列表
print("\n=== 用户权限列表 ===") ngx.say("\n=== 用户权限列表 ===")
local users = {"user001", "user002", "admin001"} local users = {"user001", "user002", "admin001"}
for _, user_id in ipairs(users) do for _, user_id in ipairs(users) do
local permissions = permission_system:get_user_permissions(user_id) local permissions = permission_system:get_user_permissions(user_id)
print(string.format("用户 %s 的权限:", user_id)) ngx.say(string.format("用户 %s 的权限:", user_id))
for _, perm in ipairs(permissions) do for _, perm in ipairs(permissions) do
print(string.format(" - %s %s", perm.action, perm.resource)) ngx.say(string.format(" - %s %s", perm.action, perm.resource))
end end
end end

View File

@ -16,7 +16,7 @@ function _M:json(status, message, data, http_status)
--end --end
msg = error_code[status] msg = error_code[status]
end end
local response = {code=status, msg=msg, result=data,timestamp=os.time()} local response = {code=status, msg=msg, result=data,timestamp=ngx.time()}
if not response.code then if not response.code then
response.code = -1 response.code = -1
response.message = 'not find status code' response.message = 'not find status code'
@ -34,7 +34,7 @@ function _M:json(status, data, http_status)
local response_status = http_status or ngx.OK local response_status = http_status or ngx.OK
msg = error_code[status] msg = error_code[status]
local response = {code=status, msg=msg, result=data,timestamp=os.time()} local response = {code=status, msg=msg, result=data,timestamp=ngx.time()}
if not response.code then if not response.code then
response.code = -1 response.code = -1
response.message = 'not find status code' response.message = 'not find status code'
@ -51,7 +51,7 @@ function _M:raw(http_status, http_body)
code = http_status, code = http_status,
headers = {}, headers = {},
body = http_body, body = http_body,
timestamp = os.time() timestamp = ngx.time()
} }
end end

View File

@ -26,8 +26,8 @@ local obj = {
role = "", -- 角色 role = "", -- 角色
--iss = "your_issuer", -- 签发者 --iss = "your_issuer", -- 签发者
--sub = "1234567890", -- 主题 --sub = "1234567890", -- 主题
exp = os.time() + 3600, -- 过期时间(例如:当前时间+1小时 exp = ngx.time() + 3600, -- 过期时间(例如:当前时间+1小时
iat = os.time() -- 签发时间 iat = ngx.time() -- 签发时间
} }
} }
@ -76,7 +76,7 @@ function _M.authorizationToken(auth_header)
return response return response
end end
--判断token是否超时 --判断token是否超时
if jwt_obj.payload.exp and os.time() > jwt_obj.payload.exp then if jwt_obj.payload.exp and ngx.time() > jwt_obj.payload.exp then
response["code"] = 401 response["code"] = 401
response["message"] = "令牌已过期" response["message"] = "令牌已过期"
return response return response