This commit is contained in:
2026-01-17 14:48:49 +08:00
parent b9b4c993f4
commit 0b5a0557ee
14 changed files with 613 additions and 233 deletions

View File

@@ -40,24 +40,32 @@ export const checkAuth = async (ctx: any, isAdmin = false) => {
const token = ctx.query.token;
console.log('checkAuth', ctx.query, { token });
if (!token) {
return ctx.throw(401, 'not login');
return {
code: 401,
message: '未登录',
}
}
// 鉴权代理
let tokenUser = await authCache.get(token);
if (!tokenUser) {
const tokenUserRes = await getTokenUser(token);
if (tokenUserRes.code !== 200) {
return ctx.throw(tokenUserRes.code, 'not login');
return {
code: tokenUserRes.code,
message: '验证失败' + tokenUserRes.message,
}
} else {
tokenUser = tokenUserRes.data;
}
authCache.set(token, tokenUser);
}
ctx.state = {
...ctx.state,
token,
tokenUser,
};
if (ctx.state) {
ctx.state = {
...ctx.state,
token,
tokenUser,
};
}
const { username } = tokenUser;
if (!auth.username) {
// 初始管理员账号
@@ -75,9 +83,16 @@ export const checkAuth = async (ctx: any, isAdmin = false) => {
isCheckAdmin = true;
}
if (!isCheckAdmin) {
return ctx.throw(403, 'not admin user');
return {
code: 403,
message: '非管理员用户',
}
}
}
return {
code: 200,
data: { tokenUser, token }
}
};
app
.route({
@@ -86,7 +101,10 @@ app
description: '获取当前登录用户信息, 第一个登录的用户为管理员用户',
})
.define(async (ctx) => {
await checkAuth(ctx);
const authResult = await checkAuth(ctx);
if (authResult.code !== 200) {
ctx.throw(authResult.code, authResult.message);
}
})
.addTo(app);
app
@@ -97,7 +115,10 @@ app
})
.define(async (ctx) => {
console.log('query', ctx.query);
await checkAuth(ctx, true);
const authResult = await checkAuth(ctx, true);
if (authResult.code !== 200) {
ctx.throw(authResult.code, authResult.message);
}
})
.addTo(app);