feat: token 改为多端会话,各端登录互不覆盖
This commit is contained in:
+29
-2
@@ -21,10 +21,16 @@ function extractToken(ctx) {
|
||||
/**
|
||||
* 按 token 查找用户
|
||||
* DB 中存储的是 token 的 sha256 哈希;兼容旧明文 token,命中后自动迁移为哈希
|
||||
* 多端会话:命中 security.tokens 中任意一条即可,同时兼容旧的单 token 字段
|
||||
*/
|
||||
async function findUserByToken(rawToken) {
|
||||
const hashed = await hashToken(rawToken);
|
||||
let user = await DBModel.User.findOne({ 'security.token': hashed });
|
||||
let user = await DBModel.User.findOne({
|
||||
$or: [
|
||||
{ 'security.tokens.hash': hashed },
|
||||
{ 'security.token': hashed },
|
||||
],
|
||||
});
|
||||
if (!user) {
|
||||
// 兼容旧明文 token
|
||||
user = await DBModel.User.findOne({ 'security.token': rawToken });
|
||||
@@ -36,6 +42,23 @@ async function findUserByToken(rawToken) {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取 token 命中会话的过期时间
|
||||
* @returns {Date|null|undefined} null=不过期;undefined=未命中任何会话
|
||||
*/
|
||||
function resolveTokenExpiry(user, hashedToken) {
|
||||
if (!user?.security) return undefined;
|
||||
const sessions = Array.isArray(user.security.tokens) ? user.security.tokens : [];
|
||||
const session = sessions.find((item) => item?.hash === hashedToken);
|
||||
if (session) {
|
||||
return session.expiry ? new Date(session.expiry) : null;
|
||||
}
|
||||
if (user.security.token === hashedToken) {
|
||||
return user.security.tokenExpiry ? new Date(user.security.tokenExpiry) : null;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 认证中间件 - 验证 token 并挂载用户信息到 ctx
|
||||
* 可选参数:
|
||||
@@ -70,7 +93,10 @@ function auth(options = {}) {
|
||||
return ResponseUtil.unauthorized(ctx, '用户未登录或 token 无效');
|
||||
}
|
||||
|
||||
if (user.security.tokenExpiry && new Date() > user.security.tokenExpiry) {
|
||||
// 按本次 token 命中的会话判断过期,不能只看 legacy tokenExpiry:
|
||||
// 多端会话下其它端新登录不会影响本端
|
||||
const expiry = resolveTokenExpiry(user, await hashToken(token));
|
||||
if (expiry && new Date() > expiry) {
|
||||
return ResponseUtil.unauthorized(ctx, '登录已过期,请重新登录');
|
||||
}
|
||||
|
||||
@@ -120,6 +146,7 @@ function sanitizeUser(user) {
|
||||
delete obj.security?.passwd;
|
||||
delete obj.security?.passwdSalt;
|
||||
delete obj.security?.token;
|
||||
delete obj.security?.tokens;
|
||||
delete obj.security?.tokenExpiry;
|
||||
delete obj.security?.passwordResetToken;
|
||||
delete obj.security?.passwordResetExpiry;
|
||||
|
||||
Reference in New Issue
Block a user