feat: 更新开发脚本,添加新的环境变量支持,优化管理员登录流程

This commit is contained in:
2025-12-18 03:47:07 +08:00
parent 5b610fd600
commit 6e1ffe173a
6 changed files with 91 additions and 34 deletions

View File

@@ -6,29 +6,64 @@ app.route({
description: '管理员用户登录',
}).define(async (ctx) => {
const { username, password } = ctx.query;
const query = assistantConfig.query;
const auth = assistantConfig.getConfig().auth || {};
const res = await query.post({
path: 'user',
key: 'login',
data: {
username,
password,
},
})
if (res.code !== 200) {
return ctx.throw(401, 'login failed');
}
const loginUser = res.data.username;
if (auth.username && loginUser !== auth.username) {
if (auth && auth.username && auth.username !== username) {
return ctx.throw(403, 'login user is not admin user');
}
if (!auth.username) {
// 初始管理员账号
auth.username = loginUser;
assistantConfig.setConfig({ auth });
}
// 保存配置
// 发起请求,转发客户端 cookie
const res = await fetch(`${assistantConfig.baseURL}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
path: 'user',
key: 'login',
username,
password,
}),
});
ctx.body = res.data;
// 转发上游服务器返回的所有 set-cookie支持多个 cookie
const setCookieHeaders = res.headers.getSetCookie?.() || [];
if (setCookieHeaders.length > 0) {
// 设置多个 cookie 到原生 http.ServerResponse
ctx.res.setHeader('Set-Cookie', setCookieHeaders);
} else {
// 兼容旧版本,使用 get 方法
const setCookieHeader = res.headers.get('set-cookie');
if (setCookieHeader) {
ctx.res.setHeader('Set-Cookie', setCookieHeader);
}
}
const responseData = await res.json();
console.debug('admin login response', { res: responseData });
if (responseData.code !== 200) {
console.debug('admin login failed', { res: responseData });
return ctx.throw(401, 'login failed');
}
const me = await assistantConfig.query.post({
path: 'user',
key: 'me',
token: responseData.data.token,
})
if (me.code === 200) {
const loginUser = me.data.username;
if (auth.username && loginUser !== auth.username) {
return ctx.throw(403, 'login user is not admin user');
}
if (!auth.username) {
// 初始管理员账号
auth.username = loginUser;
if (!auth.type) {
auth.type = 'public';
}
assistantConfig.setConfig({ auth });
console.log('set first admin user', { username: loginUser });
}
// 保存配置
}
ctx.body = responseData.data;
}).addTo(app);