AuthPlatform/src/init.lua

92 lines
2.7 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
--- 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
local conf = 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(conf.REDIS.TIMEOUT) -- 1秒
-- 连接到 Redis
local ok, err = red:connect(conf.REDIS.HOST, conf.REDIS.PORT)
if not ok then
ngx.log(ngx.ERR, "redis failed to connect: "..err)
return
end
--需要密码时对密码进行处理
if conf.REDIS.PASSWORD ~= nil then
local res, err = red:auth(conf.REDIS.PASSWORD)
if not res then
ngx.log(ngx.ERR, "redis failed to connect, password error: "..err)
return
end
end
-- 从连接池中获取连接
--red:set_keepalive(conf.REDIS.POOL_MAX_IDLE_TIME, conf.REDIS.POOL_SIZE)
--读取用户表、角色表和权限表中配置的权限数据
local roleDao = require("dao.system.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