Compare commits

...

4 Commits

34 changed files with 525 additions and 104 deletions

View File

@ -52,6 +52,16 @@ http {
## 应用路径 todo 路径问题 ## 应用路径 todo 路径问题
set $APP_PATH '/home/frankly/work/AuthPlatform'; set $APP_PATH '/home/frankly/work/AuthPlatform';
#访问时允许跨域处理
access_by_lua_block {
ngx.header["Access-Control-Allow-Origin"] = "*"
ngx.header["Access-Control-Allow-Methods"] = "GET, POST, DELETE, PUT"
ngx.header["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
if ngx.var.request_method == "OPTIONS" then
ngx.exit(ngx.HTTP_NOT_ALLOWED)
end
}
#数据列表配置 #数据列表配置
include 'system/system.conf'; include 'system/system.conf';
@ -81,10 +91,10 @@ http {
} }
} }
server { #server {
listen 9081 ssl http2; # listen 9081 ssl http2;
server_name *.*; # server_name *.*;
ssl_certificate ssl/metroid.crt; # ssl_certificate ssl/metroid.crt;
ssl_certificate_key ssl/metroid.key; # ssl_certificate_key ssl/metroid.key;
} #}
} }

View File

@ -2,8 +2,8 @@
### 接口相关控制接口文件需要使用jwt进行token验证 ### ### 接口相关控制接口文件需要使用jwt进行token验证 ###
###################################################### ######################################################
#用户认证登陆相关 #用户认证登陆相关
location /api/auth { location /api/user {
content_by_lua_file '${APP_PATH}/src/api/auth/auth.lua'; content_by_lua_file '${APP_PATH}/src/api/system/login.lua';
} }
#账号信息数据接口 #账号信息数据接口

73
src/api/oauth/oauth.lua Normal file
View File

@ -0,0 +1,73 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/10/28 11:09
---
--解析url路由过滤库
local radix = require("resty.radixtree")
--数据表业务处理
local oauthService = require("service.oauth.oauth")
--定义相关路由前端接口url地址
local routes = {
--------------------------------------------
-------------OAuth2.0认证相关路由配置--------------
--------------------------------------------
--获取授权码
{
paths = { "/api/oauth/v2/authorize" },
methods = { "POST" },
handler = oauthService.authorize,
},
--根据授权码获取Access-Token
{
paths = { "/api/oauth/v2/token" },
methods = { "POST" },
handler = oauthService.token,
},
--根据Access-Token获取相应用户的账户信息
{
paths = { "/api/oauth/v2/userinfo" },
methods = { "POST" },
handler = oauthService.userinfo,
},
--回收Access-Token
{
paths = { "/api/oauth/v2/logout" },
methods = { "POST" },
handler = oauthService.logout,
},
--根据Refresh-Token刷新Access-Token
{
paths = { "/api/oauth/v2/refresh" },
methods = { "POST" },
handler = oauthService.refresh,
},
--验证token是否有效
{
paths = { "/api/oauth/v2/checklogin" },
methods = { "POST" },
handler = oauthService.checklogin,
},
}
-- 初始化路由
local rx, err = radix.new(routes)
if not rx then
ngx.say("Not Found")
ngx.exit(ngx.HTTP_NOT_FOUND)
end
--获取访问的uri地址
local uri = ngx.var.uri
local opts = {
method = ngx.var.request_method,
matched = {}
}
-- 进行路由匹配和相关函数调用
local ok = rx:dispatch(uri, opts, opts.matched)
if not ok then
ngx.say("Not Found")
ngx.exit(ngx.HTTP_NOT_FOUND)
end

View File

@ -6,7 +6,7 @@
--解析url路由过滤库 --解析url路由过滤库
local radix = require("resty.radixtree") local radix = require("resty.radixtree")
--数据表业务处理 --数据表业务处理
local authService = require("service.auth.auth") local loginService = require("service.system.login")
--定义相关路由前端接口url地址 --定义相关路由前端接口url地址
local routes = { local routes = {
@ -15,33 +15,33 @@ local routes = {
-------------------------------------------- --------------------------------------------
--用户登录路由接口 --用户登录路由接口
{ {
paths = { "/api/auth/login" }, paths = { "/api/user/login" },
methods = { "POST" }, methods = { "POST" },
handler = authService.login, handler = loginService.login,
}, },
--用户注册路由接口 --用户注册路由接口
{ {
paths = { "/api/auth/signup" }, paths = { "/api/user/signup" },
methods = { "POST" }, methods = { "POST" },
handler = authService.signup, handler = loginService.signup,
}, },
--用户退出路由接口 --用户退出路由接口
{ {
paths = { "/api/auth/logout" }, paths = { "/api/user/logout" },
methods = { "POST" }, methods = { "POST" },
handler = authService.logout, handler = loginService.logout,
}, },
--根据token信息获取用户信息数据 --根据token信息获取用户信息数据
{ {
paths = { "/api/auth/user" }, paths = { "/api/user/user" },
methods = { "GET" }, methods = { "GET" },
handler = authService.user, handler = loginService.user,
}, },
--根据token信息获取用户权限数据 --根据token信息获取用户权限数据
{ {
paths = { "/api/auth/permission" }, paths = { "/api/user/permission" },
methods = { "GET" }, methods = { "GET" },
handler = authService.permission, handler = loginService.permission,
}, },
} }

View File

@ -11,6 +11,7 @@ local systemUser = require("service.system.user")
--定义相关路由前端接口url地址 --定义相关路由前端接口url地址
local routes = { local routes = {
--用户相关路由接口 --用户相关路由接口
--获取所有用户信息数据
{ {
paths = { "/api/system/users" }, paths = { "/api/system/users" },
methods = { "GET" }, methods = { "GET" },
@ -20,6 +21,7 @@ local routes = {
end, end,
handler = systemUser.getSystemUsers, handler = systemUser.getSystemUsers,
}, },
--根据用户id获取用户详情信息
{ {
paths = { "/api/system/users/:id" }, paths = { "/api/system/users/:id" },
methods = { "GET" }, methods = { "GET" },
@ -29,6 +31,7 @@ local routes = {
end, end,
handler = systemUser.getSystemUser, handler = systemUser.getSystemUser,
}, },
--根据增加新的用户信息
{ {
paths = { "/api/system/users" }, paths = { "/api/system/users" },
methods = { "POST" }, methods = { "POST" },
@ -38,6 +41,7 @@ local routes = {
end, end,
handler = systemUser.addSystemUser, handler = systemUser.addSystemUser,
}, },
--根据用户id删除用户信息
{ {
paths = { "/api/system/users/:id" }, paths = { "/api/system/users/:id" },
methods = { "DELETE" }, methods = { "DELETE" },
@ -47,6 +51,7 @@ local routes = {
end, end,
handler = systemUser.deleteSystemUser, handler = systemUser.deleteSystemUser,
}, },
--根据用户id编辑用户信息
{ {
paths = { "/api/system/users/:id" }, paths = { "/api/system/users/:id" },
methods = { "PUT" }, methods = { "PUT" },
@ -66,7 +71,6 @@ if not rx then
end end
--获取访问的uri地址 --获取访问的uri地址
--local uri = ngx.var.request_uri
local uri = ngx.var.uri local uri = ngx.var.uri
local opts = { local opts = {
host = ngx.var.host, host = ngx.var.host,

View File

@ -1,7 +1,7 @@
local jwt = require "resty.jwt" local jwt = require "resty.jwt"
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local jsonschema = require("jsonschema") local jsonschema = require("jsonschema")
require("config") local conf = require("config")
-- 定义一个JSON Schema -- 定义一个JSON Schema
local schema = { local schema = {
@ -34,7 +34,7 @@ end
--获取token的数据值 --获取token的数据值
local token = string.sub(auth_header,8) local token = string.sub(auth_header,8)
--校验令牌 --校验令牌
local jwt_obj = jwt:verify(SYSTEM_CONFIG.secret_key, token) local jwt_obj = jwt:verify(conf.secret_key, token)
--如果校验结果中的verified==false则表示令牌无效 --如果校验结果中的verified==false则表示令牌无效
if jwt_obj.verified == false then if jwt_obj.verified == false then
ngx.log(ngx.WARN, "Invalid token: ".. jwt_obj.reason) ngx.log(ngx.WARN, "Invalid token: ".. jwt_obj.reason)

View File

@ -4,38 +4,38 @@
--- DateTime: 2025/9/24 16:31 --- DateTime: 2025/9/24 16:31
--- 配置文件配置信息 --- 配置文件配置信息
SYSTEM_CONFIG = { local _M = {
APP_ENV = "dev", -- dev/prod APP_ENV = "dev", -- dev/prod
locale = 'zh', locale = 'zh',
time_zone = "+8:00", -- UTC + 8
time_zone = "+8:00", -- UTC + 8 secret_key = "!@#$5412$#@!", -- 确保这个密钥足够安全并保密
secret_key = "!@#$5412$#@!", -- 确保这个密钥足够安全并保密
REDIS_PREFIX = 'Auth:', REDIS_PREFIX = 'Auth:',
-- 配置redis数据库连接 -- 配置redis数据库连接
REDIS = { REDIS = {
HOST = "127.0.0.1", -- redis host HOST = "127.0.0.1", -- redis host
PORT = 6379, -- redis port PORT = 6379, -- redis port
PASSWORD = nil, -- redis password PASSWORD = nil, -- redis password
POOL_MAX_IDLE_TIME = 10000, POOL_MAX_IDLE_TIME = 10000,
POOL_TIMEOUT = 1000, -- pool timeout POOL_TIMEOUT = 1000, -- pool timeout
POOL_SIZE = 20, -- pool size POOL_SIZE = 20, -- pool size
TIMEOUT = 1000, -- timeout TIMEOUT = 1000, -- timeout
}, },
-- 配置PostgresSQL数据库连接 -- 配置PostgresSQL数据库连接
POSTGRES = { POSTGRES = {
HOST = "127.0.0.1", -- postgres host HOST = "127.0.0.1", -- postgres host
PORT = 5432, -- postgres port PORT = 5432, -- postgres port
USERNAME = "postgres", USERNAME = "postgres", -- postgres user name
PASSWORD = "1qaz2wsx", -- postgres password PASSWORD = "1qaz2wsx", -- postgres password
DATABASE = "postgres", DATABASE = "postgres", -- postgres database name
CHARSET = 'utf8', CHARSET = 'utf8',
POOL_TIMEOUT = 1000, -- postgresql pool timeout POOL_TIMEOUT = 1000, -- postgresql pool timeout
POOL_SIZE = 100, -- postgresql pool size POOL_SIZE = 100, -- postgresql pool size
TIMEOUT = 1000, -- postgresql timeout TIMEOUT = 1000, -- postgresql timeout
} }
} }
return _M

View File

@ -3,7 +3,7 @@
--- Created by frankly. --- Created by frankly.
--- DateTime: 2025/10/29 23:36 --- DateTime: 2025/10/29 23:36
--- ---
local userDao = require("dao.user") local userDao = require("dao.system.user")
local _M = {} local _M = {}

70
src/dao/system/login.lua Normal file
View File

@ -0,0 +1,70 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by frankly.
--- DateTime: 2025/10/29 23:36
---
local userDao = require("dao.system.user")
local _M = {}
--认证用户返回用户数据信息
local function authenticate(name, passwd)
--验证用户名是否为空
if name == "" then
return 0x010003, nil
end
--验证密码是否为空
if passwd == "" then
return 0x010002, nil
end
return userDao:adjustUser(name, passwd)
end
--用户登录业务逻辑处理
function _M.login(jsonData)
--解析json中的键和数据值
local name = jsonData["username"]
local passwd = jsonData["password"]
local captcha = jsonData["captcha"]
local checkKey = jsonData["checkKey"]
--验证用户名是否为空
local code, res = authenticate(name, passwd)
if code ~= 0 then
return 0x000001,res
end
local num = 0
if res ~= nil then
num = table.getn(res)
end
--用户存在时返回用户已经存在
if num <= 0 then
return 0x01000C,nil
end
local userid = res[1].id
--获取用户id查询角色信息
local err, rest = userDao:userRole(userid)
if rest == nil then
return 0x01000C,nil
end
res[1].role_id = rest[1].role_id
res[1].role_name = rest[1].role_name
return 0, res
end
--用户登出业务逻辑处理
function _M.logout(jsonData)
local code = 0
local ret = "{}"
return code, ret
end
--用户注册业务逻辑处理
function _M.signup(jsonData)
return userDao:addSystemUser(jsonData)
end
function _M.getUser(userid)
return userDao:getSystemUser(userid)
end
return _M

View File

@ -10,7 +10,7 @@ local model = require("share.model")
--创建一个数据表相关的模型 --创建一个数据表相关的模型
local userModel = model:new('sys_user') local userModel = model:new('sys_user')
local roles = require("dao.role") local roles = require("dao.system.role")
local _M = {} local _M = {}

View File

@ -19,7 +19,7 @@ end
-- return -- return
--end --end
require("config") local conf = require("config")
print("init application woker id:", ngx.worker.id()) print("init application woker id:", ngx.worker.id())
--初始化获取系统默认的用户权限为实现RBAC框架做权限数据准备 --初始化获取系统默认的用户权限为实现RBAC框架做权限数据准备
@ -28,17 +28,17 @@ local function handler()
local redis = require("resty.redis") local redis = require("resty.redis")
local red = redis:new() local red = redis:new()
-- 设置超时时间 -- 设置超时时间
red:set_timeout(SYSTEM_CONFIG.REDIS.TIMEOUT) -- 1秒 red:set_timeout(conf.REDIS.TIMEOUT) -- 1秒
-- 连接到 Redis -- 连接到 Redis
local ok, err = red:connect(SYSTEM_CONFIG.REDIS.HOST, SYSTEM_CONFIG.REDIS.PORT) local ok, err = red:connect(conf.REDIS.HOST, conf.REDIS.PORT)
if not ok then if not ok then
ngx.log(ngx.ERR, "redis failed to connect: "..err) ngx.log(ngx.ERR, "redis failed to connect: "..err)
return return
end end
--需要密码时对密码进行处理 --需要密码时对密码进行处理
if SYSTEM_CONFIG.REDIS.PASSWORD ~= nil then if conf.REDIS.PASSWORD ~= nil then
local res, err = red:auth(SYSTEM_CONFIG.REDIS.PASSWORD) local res, err = red:auth(conf.REDIS.PASSWORD)
if not res then if not res then
ngx.log(ngx.ERR, "redis failed to connect, password error: "..err) ngx.log(ngx.ERR, "redis failed to connect, password error: "..err)
return return
@ -46,10 +46,10 @@ local function handler()
end end
-- 从连接池中获取连接 -- 从连接池中获取连接
--red:set_keepalive(SYSTEM_CONFIG.REDIS.POOL_MAX_IDLE_TIME, SYSTEM_CONFIG.REDIS.POOL_SIZE) --red:set_keepalive(conf.REDIS.POOL_MAX_IDLE_TIME, conf.REDIS.POOL_SIZE)
--读取用户表、角色表和权限表中配置的权限数据 --读取用户表、角色表和权限表中配置的权限数据
local roleDao = require("dao.role") local roleDao = require("dao.system.role")
--获取数据表中的记录数 --获取数据表中的记录数
local code, res = roleDao:getAllSystemRoles() local code, res = roleDao:getAllSystemRoles()
if res == nil then return end if res == nil then return end

110
src/service/oauth/oauth.lua Normal file
View File

@ -0,0 +1,110 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/10/28 11:09
--- 用于
local resp = require("util.response")
local authDao = require("dao.oauth.oauth")
local validator = require("validator.oauth.oauth")
local cjson = require("cjson.safe")
local token = require("util.uuid")
local _M = {}
--获取授权码
function _M:authorize()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorAuthorize(body_data)
--验证失败则返回
if not ok then
local result = resp:json(0x000001)
resp:send(result)
return
end
end
--根据授权码获取Access-Token
function _M:token()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorToken(body_data)
--验证失败则返回
if not ok then
local result = resp:json(0x000001)
resp:send(result)
return
end
end
--根据Access-Token获取相应用户的账户信息
function _M:userinfo()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorJson(body_data)
--验证失败则返回
if not ok then
local result = resp:json(0x000001)
resp:send(result)
return
end
end
--回收Access-Token
function _M:logout()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorJson(body_data)
--验证失败则返回
if not ok then
local result = resp:json(0x000001)
resp:send(result)
return
end
end
--根据Refresh-Token刷新Access-Token
function _M:refresh()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorJson(body_data)
--验证失败则返回
if not ok then
local result = resp:json(0x000001)
resp:send(result)
return
end
end
--验证token是否有效
function _M:checklogin()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorJson(body_data)
--验证失败则返回
if not ok then
local result = resp:json(0x000001)
resp:send(result)
return
end
end
return _M

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/9/25 08:25 --- DateTime: 2025/9/25 08:25
--- 业务逻辑 对账户数据表进行数据表业务处理 --- 业务逻辑 对账户数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local accountDao = require("dao.account") local accountDao = require("dao.system.account")
local validatorJson = require("validator.system.account") local validatorJson = require("validator.system.account")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/9/27 16:02 --- DateTime: 2025/9/27 16:02
--- 业务逻辑 对应用数据表进行数据表业务处理 --- 业务逻辑 对应用数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local applicationDao = require("dao.application") local applicationDao = require("dao.system.application")
local validatorJson = require("validator.system.application") local validatorJson = require("validator.system.application")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/9/28 10:22 --- DateTime: 2025/9/28 10:22
--- 业务逻辑 对组织架构数据表进行数据表业务处理 --- 业务逻辑 对组织架构数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local departmentDao = require("dao.department") local departmentDao = require("dao.system.department")
local validatorJson = require("validator.system.department") local validatorJson = require("validator.system.department")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")

View File

@ -4,8 +4,8 @@
--- DateTime: 2025/10/28 11:09 --- DateTime: 2025/10/28 11:09
--- 用于 --- 用于
local resp = require("util.response") local resp = require("util.response")
local authDao = require("dao.auth") local loginDao = require("dao.system.login")
local validator = require("validator.auth.auth") local validator = require("validator.system.login")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local token = require("util.token") local token = require("util.token")
@ -29,7 +29,7 @@ function _M.login()
return return
end end
--ngx.say(body_data) --ngx.say(body_data)
local code, ret = authDao.login(cjson.decode(body_data)) local code, ret = loginDao.login(cjson.decode(body_data))
--读取数据错误 --读取数据错误
if code ~= 0 or table.getn(ret) < 0 then if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001) local result = resp:json(0x000001)
@ -64,7 +64,7 @@ function _M.signup()
return return
end end
--ngx.say(body_data) --ngx.say(body_data)
local code, ret = authDao.signup(cjson.decode(body_data)) local code, ret = loginDao.signup(cjson.decode(body_data))
--读取数据错误 --读取数据错误
if code ~= 0 or table.getn(ret) < 0 then if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001) local result = resp:json(0x000001)
@ -114,7 +114,7 @@ function _M.user()
end end
--验证成功获取用户id信息 --验证成功获取用户id信息
local userid = retToken["body"]["payload"]["userid"] local userid = retToken["body"]["payload"]["userid"]
local code, ret = authDao.getUser(userid) local code, ret = loginDao.getUser(userid)
--读取数据错误 --读取数据错误
if code ~= 0 or table.getn(ret) < 0 then if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001) local result = resp:json(0x000001)
@ -145,7 +145,7 @@ function _M.permission()
local role_id = retToken["body"]["payload"]["role_id"] local role_id = retToken["body"]["payload"]["role_id"]
local role_name = retToken["body"]["payload"]["role_name"] local role_name = retToken["body"]["payload"]["role_name"]
--通过用户id查询到用户的权限信息 --通过用户id查询到用户的权限信息
local code, ret = authDao.getUser(userid) local code, ret = loginDao.getUser(userid)
--读取数据错误 --读取数据错误
if code ~= 0 or table.getn(ret) < 0 then if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001) local result = resp:json(0x000001)

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/9/27 17:06 --- DateTime: 2025/9/27 17:06
--- 业务逻辑 对权限数据表进行数据表业务处理 --- 业务逻辑 对权限数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local permissionDao = require("dao.permission") local permissionDao = require("dao.system.permission")
local validatorJson = require("validator.system.permission") local validatorJson = require("validator.system.permission")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/11/04 15:01 --- DateTime: 2025/11/04 15:01
--- 业务逻辑 对岗位数据表进行数据表业务处理 --- 业务逻辑 对岗位数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local positionDao = require("dao.position") local positionDao = require("dao.system.position")
local validatorJson = require("validator.system.position") local validatorJson = require("validator.system.position")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/9/27 15:19 --- DateTime: 2025/9/27 15:19
--- 业务逻辑 对用户角色数据表进行数据表业务处理 --- 业务逻辑 对用户角色数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local roleDao = require("dao.role") local roleDao = require("dao.system.role")
local validatorJson = require("validator.system.role") local validatorJson = require("validator.system.role")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")

View File

@ -4,7 +4,7 @@
--- DateTime: 2025/9/25 08:19 --- DateTime: 2025/9/25 08:19
--- 业务逻辑 对用户数据表进行数据表业务处理 --- 业务逻辑 对用户数据表进行数据表业务处理
local resp = require("util.response") local resp = require("util.response")
local userDao = require("dao.user") local userDao = require("dao.system.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 token = require("util.token")

View File

@ -5,7 +5,7 @@
--- ---
local snowflake = require("share.snowflake") local snowflake = require("share.snowflake")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
require("config") local conf = require("config")
local _M = {} local _M = {}
@ -128,7 +128,7 @@ local function get_cookie(key)
end end
local function get_local_time() local function get_local_time()
local time_zone = ngx.re.match(SYSTEM_CONFIG.time_zone, "[0-9]+") local time_zone = ngx.re.match(conf.time_zone, "[0-9]+")
if time_zone == nil then if time_zone == nil then
local err = "not set time zone or format error, time zone should look like `+8:00` current is: " .. config.time_zone local err = "not set time zone or format error, time zone should look like `+8:00` current is: " .. config.time_zone
ngx.log(ngx.ERR, err) ngx.log(ngx.ERR, err)

View File

@ -1,4 +1,4 @@
require("config") local conf = require("config")
local Database = require('share.database') local Database = require('share.database')
local helpers = require('share.helpers') local helpers = require('share.helpers')
local implode = helpers.implode local implode = helpers.implode
@ -11,28 +11,28 @@ local WRITE = 'WRITE'
local READ = 'READ' local READ = 'READ'
local database_write = Database:new({ local database_write = Database:new({
host = SYSTEM_CONFIG.POSTGRES.HOST, host = conf.POSTGRES.HOST,
port = SYSTEM_CONFIG.POSTGRES.PORT, port = conf.POSTGRES.PORT,
user = SYSTEM_CONFIG.POSTGRES.USERNAME, user = conf.POSTGRES.USERNAME,
password = SYSTEM_CONFIG.POSTGRES.PASSWORD, password = conf.POSTGRES.PASSWORD,
database = SYSTEM_CONFIG.POSTGRES.DATABASE, database = conf.POSTGRES.DATABASE,
charset = SYSTEM_CONFIG.POSTGRES.CHARSET, charset = conf.POSTGRES.CHARSET,
timeout = SYSTEM_CONFIG.POSTGRES.TIMEOUT, timeout = conf.POSTGRES.TIMEOUT,
db_pool_timeout = SYSTEM_CONFIG.POSTGRES.POOL_TIMEOUT, db_pool_timeout = conf.POSTGRES.POOL_TIMEOUT,
db_pool_size = SYSTEM_CONFIG.POSTGRES.POOL_SIZE, db_pool_size = conf.POSTGRES.POOL_SIZE,
db_type = WRITE db_type = WRITE
}) })
local database_read = Database:new({ local database_read = Database:new({
host = SYSTEM_CONFIG.POSTGRES.HOST, host = conf.POSTGRES.HOST,
port = SYSTEM_CONFIG.POSTGRES.PORT, port = conf.POSTGRES.PORT,
user = SYSTEM_CONFIG.POSTGRES.USERNAME, user = conf.POSTGRES.USERNAME,
password = SYSTEM_CONFIG.POSTGRES.PASSWORD, password = conf.POSTGRES.PASSWORD,
database = SYSTEM_CONFIG.POSTGRES.DATABASE, database = conf.POSTGRES.DATABASE,
charset = SYSTEM_CONFIG.POSTGRES.CHARSET, charset = conf.POSTGRES.CHARSET,
timeout = SYSTEM_CONFIG.POSTGRES.TIMEOUT, timeout = conf.POSTGRES.TIMEOUT,
db_pool_timeout = SYSTEM_CONFIG.POSTGRES.POOL_TIMEOUT, db_pool_timeout = conf.POSTGRES.POOL_TIMEOUT,
db_pool_size = SYSTEM_CONFIG.POSTGRES.POOL_SIZE, db_pool_size = conf.POSTGRES.POOL_SIZE,
db_type = READ db_type = READ
}) })

View File

@ -1,9 +1,9 @@
local redis = require("resty.redis") local redis = require("resty.redis")
require("config") local conf = require("config")
local _M = setmetatable({}, {__index = function(self, key) local _M = setmetatable({}, {__index = function(self, key)
local red = redis:new() local red = redis:new()
local ok, err = red:connect(SYSTEM_CONFIG.REDIS.HOST, SYSTEM_CONFIG.REDIS.PORT) local ok, err = red:connect(conf.REDIS.HOST, conf.REDIS.PORT)
if not ok then if not ok then
ngx.log(ngx.ERR, err) ngx.log(ngx.ERR, err)
end end

View File

@ -9,11 +9,13 @@ local jsonschema = require("jsonschema")
local cjson = require("cjson.safe") local cjson = require("cjson.safe")
local redis = require("share.redis") local redis = require("share.redis")
--local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间 --[[
--local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间 local workerId = 0 -- 假设当前机器的ID是1范围在[0, 31]之间
--local snow = snowflake.new(workerId, datacenterId) local datacenterId = 0 -- 数据中心ID范围在[0, 31]之间
--local id = snow:generateUniqueId()-- 生成ID local snow = snowflake.new(workerId, datacenterId)
local id = snow:generateUniqueId()-- 生成ID
--ngx.say("Generated ID:"..snow.int64_to_string(id)) --ngx.say("Generated ID:"..snow.int64_to_string(id))
--]]
--max =a and b or c--a?b:c --max =a and b or c--a?b:c
@ -123,17 +125,22 @@ if val6 ~= nil then
end 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 uuid = require("resty.jit-uuid")
uuid.seed()
local val = uuid()
local uid = uuid.generate_v4() ---> v4 UUID
local uid1 = uuid.generate_v3() ---> v3 UUID (name-based with MD5)
local uid2 = uuid.generate_v5() ---> v5 UUID (name-based with SHA-1)
uuid.is_valid() ---> true/false (automatic JIT PCRE or Lua patterns)
--ngx.say(val.." "..uid)
local args = ngx.req.get_uri_args() local args = ngx.req.get_uri_args()
local pageNum = args["pagenum"] or 1 local pageNum = args["pagenum"] or 1
local pageSize = args["pagesize"] or 10 local pageSize = args["pagesize"] or 10
@ -333,6 +340,7 @@ else
end end
--]] --]]
--[[
local perm = require("util.permissionfilter") local perm = require("util.permissionfilter")
local perms = {} local perms = {}
--获取角色的所所有全新信息 --获取角色的所所有全新信息
@ -352,8 +360,9 @@ end
--清除角色的权限数据 --清除角色的权限数据
--perm:clearRolePermissions("admin") --perm:clearRolePermissions("admin")
--]]
--[[
local generateCert = require("util.generatorssl") local generateCert = require("util.generatorssl")
-- 使用示例 -- 使用示例
local success, files = generateCert:generate_self_signed_cert( local success, files = generateCert:generate_self_signed_cert(
@ -370,6 +379,7 @@ if success then
else else
print("证书生成失败") print("证书生成失败")
end end
--]]
--[[ --[[
--读取用户表、角色表和权限表中配置的权限数据 --读取用户表、角色表和权限表中配置的权限数据

View File

@ -6,7 +6,7 @@
local jwt = require("resty.jwt") local jwt = require("resty.jwt")
local jsonschema = require("jsonschema") local jsonschema = require("jsonschema")
require("config") local conf = require("config")
local _M = {} local _M = {}
@ -32,6 +32,7 @@ local obj = {
} }
} }
--通过参数生存jwt相关的token值
function _M.generateToken(userid, username, role_id, role_name) function _M.generateToken(userid, username, role_id, role_name)
if userid == nil or username == nil or role_id == nil or role_name == nil then if userid == nil or username == nil or role_id == nil or role_name == nil then
return "" return ""
@ -42,7 +43,7 @@ function _M.generateToken(userid, username, role_id, role_name)
obj.payload.role_id = role_id obj.payload.role_id = role_id
obj.payload.role_name = role_name obj.payload.role_name = role_name
--获取的登陆的用户信息返回tocken --获取的登陆的用户信息返回tocken
local jwt_token = jwt:sign(SYSTEM_CONFIG.secret_key, obj) local jwt_token = jwt:sign(conf.secret_key, obj)
return "Bearer "..jwt_token return "Bearer "..jwt_token
end end
@ -57,6 +58,7 @@ function _M.authorizationToken(auth_header)
return response return response
end end
--验证令牌是否符合要求
local validator = jsonschema.generate_validator(schema) local validator = jsonschema.generate_validator(schema)
local data = {} local data = {}
data.Authorization = auth_header data.Authorization = auth_header
@ -71,7 +73,7 @@ function _M.authorizationToken(auth_header)
--查找令牌中的Bearer前缀字符并进行截取 --查找令牌中的Bearer前缀字符并进行截取
local token = string.sub(auth_header,8) local token = string.sub(auth_header,8)
--校验令牌 --校验令牌
local jwt_obj = jwt:verify(SYSTEM_CONFIG.secret_key, token) local jwt_obj = jwt:verify(conf.secret_key, token)
--如果校验结果中的verified==false则表示令牌无效 --如果校验结果中的verified==false则表示令牌无效
if jwt_obj.verified == false then if jwt_obj.verified == false then
response["code"] = 401 response["code"] = 401

29
src/util/uuid.lua Normal file
View File

@ -0,0 +1,29 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by frankly.
--- DateTime: 2025/11/10 15:25
---
local jitUuid = require("resty.jit-uuid")
--uuid.seed()
--local val = uuid()
--local uuid1 = string.gsub(val,"-", "")
--local uid = uuid.generate_v4() ---> v4 UUID
--local uuid2 = string.gsub(uid, "-", "")
--local uid1 = uuid.generate_v3() ---> v3 UUID (name-based with MD5) --nil
--local uid2 = uuid.generate_v5() ---> v5 UUID (name-based with SHA-1) --nil
----uuid.is_valid() ---> true/false (automatic JIT PCRE or Lua patterns)
--ngx.say("val:"..uuid1.." uid:"..uuid2)--.." uid1:"..uid1--.." uid2:"..uid2)
local _M = {}
--使用库生存uuid
function _M.generateUuid()
jitUuid.seed()
local Guid = jitUuid.generate_v4() ---> v4 UUID
local uuid = string.gsub(Guid, "-", "")
return uuid
end
return _M

View File

@ -0,0 +1,113 @@
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by admin.
--- DateTime: 2025/10/30 08:09
---业务逻辑 对账户登录的参数进行数据的验证
local jsonschema = require("jsonschema")
local _M = {}
-- 定义一个JSON Schema
local schemaAuth = {
{type = "object", properties = {
{name = "username", type = "string"},
{name = "password", type = "string"},
{name = "captcha", type = "string"},
{name = "checkKey", type = "string"},
}, required = {"username", "password"}}
}
--获取授权码
function _M:validatorAuthorize(jsonData)
-- 验证数据是否符合schema
local validator = jsonschema.generate_validator(schemaAuth)
local result = validator(jsonData)
return result
end
local schemaToken = {
{type = "object", properties = {
{name = "username", type = "string"},
{name = "password", type = "string"},
{name = "captcha", type = "string"},
{name = "checkKey", type = "string"},
}, required = {"username", "password"}}
}
--根据授权码获取Access-Token
function _M:validatorToken(jsonData)
-- 验证数据是否符合schema
local validator = jsonschema.generate_validator(schemaToken)
local result = validator(jsonData)
return result
end
local schemaUserInfo = {
{type = "object", properties = {
{name = "username", type = "string"},
{name = "password", type = "string"},
{name = "captcha", type = "string"},
{name = "checkKey", type = "string"},
}, required = {"username", "password"}}
}
--根据Access-Token获取相应用户的账户信息
function _M:validatorUserinfo(jsonData)
-- 验证数据是否符合schema
local validator = jsonschema.generate_validator(schemaUserInfo)
local result = validator(jsonData)
return result
end
local schemaLogout = {
{type = "object", properties = {
{name = "username", type = "string"},
{name = "password", type = "string"},
{name = "captcha", type = "string"},
{name = "checkKey", type = "string"},
}, required = {"username", "password"}}
}
--回收Access-Token
function _M:validatorLogout(jsonData)
-- 验证数据是否符合schema
local validator = jsonschema.generate_validator(schemaLogout)
local result = validator(jsonData)
return result
end
local schemaRefresh = {
{type = "object", properties = {
{name = "username", type = "string"},
{name = "password", type = "string"},
{name = "captcha", type = "string"},
{name = "checkKey", type = "string"},
}, required = {"username", "password"}}
}
--根据Refresh-Token刷新Access-Token
function _M:validatorRefresh(jsonData)
-- 验证数据是否符合schema
local validator = jsonschema.generate_validator(schemaRefresh)
local result = validator(jsonData)
return result
end
local schemaChecklogin = {
{type = "object", properties = {
{name = "username", type = "string"},
{name = "password", type = "string"},
{name = "captcha", type = "string"},
{name = "checkKey", type = "string"},
}, required = {"username", "password"}}
}
--验证token是否有效
function _M:validatorChecklogin(jsonData)
-- 验证数据是否符合schema
local validator = jsonschema.generate_validator(schemaChecklogin)
local result = validator(jsonData)
return result
end
return _M