AuthPlatform/src/init.lua

92 lines
2.7 KiB
Lua
Raw Normal View History

---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by frankly.
--- DateTime: 2025/11/3 18:44
---
--[[
"ngx_lua""init_by_lua_file";
nginx时初始化一次
--]]
--只在第一个worker进程中执行一次
if ngx.worker.id() ~= 0 then
return
end
--判断程序是否加载权限数据
--local dict = ngx.shared.dict
--local load = dict:get("RBAC")
--if load then
-- return
--end
require("config")
print("init application woker id:", ngx.worker.id())
--初始化获取系统默认的用户权限为实现RBAC框架做权限数据准备
local function handler()
--与redis进行连接
local redis = require("resty.redis")
local red = redis:new()
-- 设置超时时间
red:set_timeout(SYSTEM_CONFIG.REDIS.TIMEOUT) -- 1秒
-- 连接到 Redis
local ok, err = red:connect(SYSTEM_CONFIG.REDIS.HOST, SYSTEM_CONFIG.REDIS.PORT)
if not ok then
ngx.log(ngx.ERR, "redis failed to connect: "..err)
return
end
--需要密码时对密码进行处理
if SYSTEM_CONFIG.REDIS.PASSWORD ~= nil then
local res, err = red:auth(SYSTEM_CONFIG.REDIS.PASSWORD)
if not res then
ngx.log(ngx.ERR, "redis failed to connect, password error: "..err)
return
end
end
-- 从连接池中获取连接
--red:set_keepalive(SYSTEM_CONFIG.REDIS.POOL_MAX_IDLE_TIME, SYSTEM_CONFIG.REDIS.POOL_SIZE)
--读取用户表、角色表和权限表中配置的权限数据
local roleDao = require("dao.role")
--获取数据表中的记录数
local code, res = roleDao:getAllSystemRoles()
if res == nil then return end
--管道进行redis处理
red:init_pipeline()
--读取角色id和角色名称
for _, row in pairs(res) do
local id = row.id --:1
local name = row.role_name --:admin
--row.status:0,
local code, rest = roleDao:getPermission2roleId(id)
for _, ret in pairs(rest) do
--获取数据表中的数据
local permid = ret.permission_id
local perm = ret.permission_code
local key = name.."-"..perm
--role_name-permission_code 组成key进行验证 存储到redis中
red:set(key, "1")
end
end
local results, err = red:commit_pipeline()
if not results then
ngx.log(ngx.ERR, "init failed to commit the pipelined requests: ", err)
end
--关闭redis连接
red:close()
--共享数据字典进行数据存储
--dict:set("RBAC", "1")
print("init application success")
end
-- 设置定时器执行一次handler函数
local ok, err = ngx.timer.at(0, handler)
if not ok then
ngx.log(ngx.ERR, "failed to create timer")
return
end