Older/Server/lua/login.lua

79 lines
2.0 KiB
Lua
Raw Normal View History

2023-11-05 19:01:15 +08:00
local cjson = require "cjson"
2024-06-16 14:50:10 +08:00
local password_path = "password.txt"
2024-06-16 21:37:26 +08:00
local function add_domain(cookies, key, domain)
if type(cookies) == "string" then -- 确保 set_cookies 是一个表
cookies = { cookies }
end
local new_cookies = {} -- 查找并修改名为 'remember' 的 Cookie
for _, cookie in ipairs(cookies) do
local cookie_key, value = string.match(cookie, "^%s*(.-)%s*=%s*(.-)%s*;")
if cookie_key == key then
local new_cookie = value .. "; Domain=" .. domain .. "; Path=/; HttpOnly"
table.insert(new_cookies, key.."=" .. new_cookie)
else
table.insert(new_cookies, cookie)
end
end
return new_cookies;
end
2023-11-05 19:01:15 +08:00
ngx.req.read_body()
local body = ngx.req.get_body_data()
2024-06-16 14:50:10 +08:00
if not body then
ngx.status = ngx.HTTP_BAD_REQUEST
ngx.say("No body found")
return
end
local ok, json_data = pcall(cjson.decode, body)
if not ok then
ngx.status = ngx.HTTP_BAD_REQUEST
ngx.say("Invalid JSON")
return
end
local user_account = json_data.account
local user_password = json_data.password
local reply = {}
local file = io.open(password_path, "r")
if not file then
ngx.log(ngx.INFO, "无法打开文件: ", password_path)
reply.status = -1000
reply.message = "服务器错误,找不到 " .. password_path;
ngx.say(cjson.encode(reply))
return
end
local credentials = {}
for line in file:lines() do
local account, password = line:match("([^=]+)=([^=]+)")
if account and password then
credentials[account] = password
end
end
file:close()
local session = require "resty.session".start()
if credentials[user_account] == user_password then
reply.status = 0
reply.message = "登录成功"
session:set("account", user_account)
session:set("authenticated", true)
2023-11-05 19:01:15 +08:00
session:save()
2024-06-16 21:37:26 +08:00
ngx.header["Set-Cookie"] = add_domain(ngx.header["Set-Cookie"], "remember", ".amass.fun");
2023-11-05 19:01:15 +08:00
else
2024-06-16 14:50:10 +08:00
reply.status = -100
reply.message = "登录失败"
2023-11-05 19:01:15 +08:00
end
2024-06-16 14:50:10 +08:00
ngx.say(cjson.encode(reply))