diff --git a/conf/nginx.conf b/conf/nginx.conf index 61a1e81..288b411 100644 --- a/conf/nginx.conf +++ b/conf/nginx.conf @@ -13,8 +13,10 @@ http { client_max_body_size 1024M; #允许最大100k的请求体 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_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. #lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; @@ -22,6 +24,21 @@ http { # The verification depth in the server certificates chain. #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 { listen 9080; server_name 127.0.0.1; @@ -33,7 +50,6 @@ http { ## 应用路径 todo 路径问题 set $APP_PATH '/home/frankly/work/AuthPlatform'; - #access_by_lua_file '${APP_PATH}/src/auth/jwt-auth.lua'; #数据列表配置 include 'system/system.conf'; @@ -41,6 +57,9 @@ http { location /testSQL { content_by_lua_file '${APP_PATH}/src/test/testPostgres.lua'; } + location /testRBAC { + content_by_lua_file '${APP_PATH}/src/test/testRBAC.lua'; + } location /cjson { 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'; 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")) + } + } } } \ No newline at end of file diff --git a/src/auth/jwt-auth.lua b/src/auth/jwt-auth.lua index 702f9c6..f508cd3 100644 --- a/src/auth/jwt-auth.lua +++ b/src/auth/jwt-auth.lua @@ -43,7 +43,7 @@ if jwt_obj.verified == false then end --判断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.status = ngx.HTTP_UNAUTHORIZED ngx.exit(ngx.HTTP_UNAUTHORIZED) diff --git a/src/dao/account.lua b/src/dao/account.lua index 55fa76e..30b3111 100644 --- a/src/dao/account.lua +++ b/src/dao/account.lua @@ -84,6 +84,7 @@ function _M:updateSystemAccount(id, jsonData) if ok == false then return 0x000001,nil end + jsonData.update_time = ngx.time() --对数据内容进行更新 return accountModel:where('id', '=', id):update(jsonData) end diff --git a/src/dao/application.lua b/src/dao/application.lua index 99733b2..ca66b5b 100644 --- a/src/dao/application.lua +++ b/src/dao/application.lua @@ -99,7 +99,8 @@ function _M.updateApplication(id, jsonData) if ok == false then return 0x000001,nil end - --对数据内容进行更新 + --对数据内容进行更 + jsonData.update_time = ngx.time() return applicationModel:where('id', '=', id):update(jsonData) end diff --git a/src/dao/department.lua b/src/dao/department.lua index 0f0cf2d..027f7ba 100644 --- a/src/dao/department.lua +++ b/src/dao/department.lua @@ -83,6 +83,7 @@ function _M.updateSystemDepartment(id, jsonData) if ok == false then return 0x000001,nil end + jsonData.update_time = ngx.time() --对数据内容进行更新 return departmentModel:where('id', '=', id):update(jsonData) end diff --git a/src/dao/permission.lua b/src/dao/permission.lua index 36200b7..1d15224 100644 --- a/src/dao/permission.lua +++ b/src/dao/permission.lua @@ -91,6 +91,7 @@ function _M.updateSystemPermission(id, jsonData) if ok == false then return 0x000001,nil end + jsonData.update_time = ngx.time() --对数据内容进行更新 return permissionModel:where('id', '=', id):update(jsonData) end diff --git a/src/dao/role.lua b/src/dao/role.lua index 0a3d7e5..42e7210 100644 --- a/src/dao/role.lua +++ b/src/dao/role.lua @@ -84,6 +84,7 @@ function _M:updateSystemRole(id, jsonData) if ok == false then return 0x000001,nil end + jsonData.update_time = ngx.time() --对数据内容进行更新 return roleModel:where('id', '=', id):update(jsonData) end diff --git a/src/init.lua b/src/init.lua new file mode 100644 index 0000000..556aeb4 --- /dev/null +++ b/src/init.lua @@ -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 \ No newline at end of file diff --git a/src/service/system/user.lua b/src/service/system/user.lua index 0e953c4..a3e1434 100644 --- a/src/service/system/user.lua +++ b/src/service/system/user.lua @@ -7,9 +7,22 @@ local resp = require("util.response") local userDao = require("dao.user") local validatorJson = require("validator.system.user") local cjson = require("cjson.safe") +local token = require("util.token") 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() --获取页码和请求的数据量 @@ -23,6 +36,12 @@ end --根据用户id获取用户信息 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 result = resp:json(code, ret) resp:send(result) @@ -59,6 +78,12 @@ end --根据用户id删除用户信息 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() --获取请求数据 diff --git a/src/share/lib/cjson.so b/src/share/lib/cjson.so deleted file mode 100644 index af89ca2..0000000 Binary files a/src/share/lib/cjson.so and /dev/null differ diff --git a/src/share/snowflake.lua b/src/share/snowflake.lua index e0287a8..534c1c7 100644 --- a/src/share/snowflake.lua +++ b/src/share/snowflake.lua @@ -127,23 +127,23 @@ end --获取当前时间戳(毫秒) function snowflake:getCurrentTimestamp() - local timestamp = os.time() + local timestamp = ngx.time() return timestamp end --获取新的时间戳 function snowflake:getNextTimestamp(lastTimestamp) - local timestamp = math.floor(os.time()); + local timestamp = math.floor(ngx.time()); while (timestamp <= lastTimestamp) do - timestamp = math.floor(os.time()); + timestamp = math.floor(ngx.time()); end return timestamp; end -- 雪花算法的实现 function snowflake:generateUniqueId() - --local curtime = os.time() + --local curtime = ngx.time() --print("current time: ", curtime) local timestamp = self.getCurrentTimestamp() -- 当前时间戳(毫秒) -- 如果是同一时间生成的,则进行毫秒内序列 diff --git a/src/test/test.lua b/src/test/test.lua index 1eb350f..1b4ff8a 100644 --- a/src/test/test.lua +++ b/src/test/test.lua @@ -7,7 +7,7 @@ local helpers = require("share.helpers") local jsonschema = require("jsonschema") local cjson = require("cjson.safe") --- + --local workerId = 0 -- 假设当前机器的ID是1,范围在[0, 31]之间 --local datacenterId = 0 -- 数据中心ID,范围在[0, 31]之间 --local snow = snowflake.new(workerId, datacenterId) @@ -16,6 +16,9 @@ local cjson = require("cjson.safe") --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") uuid.seed() @@ -33,6 +36,7 @@ local pageSize = args["pagesize"] or 10 ngx.say("pageNum:", pageNum, " pageSize:", pageSize) --]] +--[[ local schema = { type = 'object', properties = { @@ -53,6 +57,7 @@ if not result then 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字符串 diff --git a/src/test/testRBAC.lua b/src/test/testRBAC.lua index a6ab697..418e8ff 100644 --- a/src/test/testRBAC.lua +++ b/src/test/testRBAC.lua @@ -26,7 +26,7 @@ permission_system:assign_role("user002", "user_manager") permission_system:assign_role("admin001", "super_admin") -- 测试权限验证 -print("=== RBAC权限验证测试 ===") +ngx.say("=== RBAC权限验证测试 ===") -- 测试用户001(guest角色) local test_cases = { @@ -46,17 +46,17 @@ local test_cases = { for _, test in ipairs(test_cases) do local result = permission_system:check_permission(test.user_id, test.resource, test.action) 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))) end -- 显示用户权限列表 -print("\n=== 用户权限列表 ===") +ngx.say("\n=== 用户权限列表 ===") local users = {"user001", "user002", "admin001"} for _, user_id in ipairs(users) do 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 - print(string.format(" - %s %s", perm.action, perm.resource)) + ngx.say(string.format(" - %s %s", perm.action, perm.resource)) end end \ No newline at end of file diff --git a/src/util/response.lua b/src/util/response.lua index deefcb3..d99c002 100644 --- a/src/util/response.lua +++ b/src/util/response.lua @@ -16,7 +16,7 @@ function _M:json(status, message, data, http_status) --end msg = error_code[status] 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 response.code = -1 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 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 response.code = -1 response.message = 'not find status code' @@ -51,7 +51,7 @@ function _M:raw(http_status, http_body) code = http_status, headers = {}, body = http_body, - timestamp = os.time() + timestamp = ngx.time() } end diff --git a/src/util/token.lua b/src/util/token.lua index f9e5b25..1f08019 100644 --- a/src/util/token.lua +++ b/src/util/token.lua @@ -26,8 +26,8 @@ local obj = { role = "", -- 角色 --iss = "your_issuer", -- 签发者 --sub = "1234567890", -- 主题 - exp = os.time() + 3600, -- 过期时间(例如:当前时间+1小时) - iat = os.time() -- 签发时间 + exp = ngx.time() + 3600, -- 过期时间(例如:当前时间+1小时) + iat = ngx.time() -- 签发时间 } } @@ -76,7 +76,7 @@ function _M.authorizationToken(auth_header) return response end --判断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["message"] = "令牌已过期" return response