ai review
This commit is contained in:
+25
-3
@@ -1,5 +1,6 @@
|
||||
import { DBModel } from '../models/index.js';
|
||||
import ResponseUtil from '../utils/api_response.js';
|
||||
import { hashToken } from '../utils/crypto.js';
|
||||
|
||||
/**
|
||||
* 从请求中提取 token(优先 Authorization header)
|
||||
@@ -17,6 +18,24 @@ function extractToken(ctx) {
|
||||
|| ctx.header?.token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 token 查找用户
|
||||
* DB 中存储的是 token 的 sha256 哈希;兼容旧明文 token,命中后自动迁移为哈希
|
||||
*/
|
||||
async function findUserByToken(rawToken) {
|
||||
const hashed = await hashToken(rawToken);
|
||||
let user = await DBModel.User.findOne({ 'security.token': hashed });
|
||||
if (!user) {
|
||||
// 兼容旧明文 token
|
||||
user = await DBModel.User.findOne({ 'security.token': rawToken });
|
||||
if (user) {
|
||||
user.security.token = hashed;
|
||||
await user.save();
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 认证中间件 - 验证 token 并挂载用户信息到 ctx
|
||||
* 可选参数:
|
||||
@@ -37,7 +56,7 @@ function auth(options = {}) {
|
||||
return ResponseUtil.unauthorized(ctx, '缺少认证 token');
|
||||
}
|
||||
|
||||
const user = await DBModel.User.findOne({ 'security.token': token });
|
||||
const user = await findUserByToken(token);
|
||||
if (!user) {
|
||||
return ResponseUtil.unauthorized(ctx, '用户未登录或 token 无效');
|
||||
}
|
||||
@@ -69,15 +88,18 @@ function auth(options = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回用户安全对象(去除密码等敏感字段)
|
||||
* 返回用户安全对象(去除密码、token 等敏感字段)
|
||||
* 注意:登录/注册响应中的 token 由 handler 单独附加
|
||||
*/
|
||||
function sanitizeUser(user) {
|
||||
const obj = user.toObject ? user.toObject() : { ...user };
|
||||
delete obj.security?.passwd;
|
||||
delete obj.security?.passwdSalt;
|
||||
delete obj.security?.token;
|
||||
delete obj.security?.tokenExpiry;
|
||||
delete obj.security?.passwordResetToken;
|
||||
delete obj.security?.passwordResetExpiry;
|
||||
return obj;
|
||||
}
|
||||
|
||||
export { auth, extractToken, sanitizeUser };
|
||||
export { auth, extractToken, sanitizeUser, findUserByToken };
|
||||
|
||||
Reference in New Issue
Block a user