feat: token 改为多端会话,各端登录互不覆盖
This commit is contained in:
+63
-15
@@ -3,7 +3,7 @@ import mongoose from 'mongoose';
|
||||
import { DBModel } from "../models/index.js";
|
||||
import ResponseUtil from "../utils/api_response.js";
|
||||
import { hashPassword, verifyPassword, hashToken } from "../utils/crypto.js";
|
||||
import { sanitizeUser } from "../middleware/auth.js";
|
||||
import { sanitizeUser, extractToken } from "../middleware/auth.js";
|
||||
import { APP_REGISTRY, GRANTABLE_ROLES } from "../models/app_registry.js";
|
||||
import {
|
||||
hasConfigSchema,
|
||||
@@ -127,6 +127,8 @@ const signinSchema = Joi.object({
|
||||
'any.required': '缺少密码',
|
||||
'string.empty': '密码不能为空'
|
||||
}),
|
||||
// 可选:登录来源应用,仅用于多端会话分组,不参与鉴权
|
||||
appId: Joi.string().max(64).allow('', null),
|
||||
});
|
||||
|
||||
const wxSigninSchema = Joi.object({
|
||||
@@ -167,6 +169,10 @@ const grantSchema = Joi.object({
|
||||
|
||||
const LOCK_AFTER_FAILED_ATTEMPTS = 10;
|
||||
|
||||
// 登录 token 有效期与多端会话上限:每端登录各自一条,互不覆盖
|
||||
const TOKEN_TTL_MS = 15 * 24 * 60 * 60 * 1000;
|
||||
const MAX_TOKEN_SESSIONS = 10;
|
||||
|
||||
function groupByUserId(list) {
|
||||
const map = new Map();
|
||||
for (const item of list) {
|
||||
@@ -251,14 +257,43 @@ class HandlerUser {
|
||||
return crypto.randomBytes(32).toString("hex");
|
||||
}
|
||||
|
||||
// 签发 token:哈希入库,返回原始值供响应
|
||||
async issueToken(user) {
|
||||
// 签发 token:每端一条会话(DB 只存哈希),其它端登录不会覆盖本端
|
||||
// appId 用于多端会话分组(同一应用重复登录替换旧会话),不参与鉴权
|
||||
async issueToken(user, appId = "") {
|
||||
const raw = await this.genToken();
|
||||
user.security.token = await hashToken(raw);
|
||||
user.security.tokenExpiry = new Date(Date.now() + 15 * 24 * 60 * 60 * 1000);
|
||||
user.security.lastLoginAt = new Date();
|
||||
const hash = await hashToken(raw);
|
||||
const now = Date.now();
|
||||
const expiry = new Date(now + TOKEN_TTL_MS);
|
||||
|
||||
// 兼容迁移:首次签发时把存量单 token 会话带入多端列表,避免部署后其它端被踢
|
||||
const existing = Array.isArray(user.security.tokens) && user.security.tokens.length
|
||||
? user.security.tokens
|
||||
: (user.security.token
|
||||
? [{ hash: user.security.token, expiry: user.security.tokenExpiry, appId: "", createdAt: null }]
|
||||
: []);
|
||||
|
||||
// 清理已过期会话并限制条数;同一应用的重复登录替换旧会话,
|
||||
// 不同应用各保留一条,登录互不覆盖(未标注 appId 的登录按独立会话累加)
|
||||
const appKey = String(appId || "");
|
||||
const sessions = existing
|
||||
.map((item) => ({
|
||||
hash: item.hash,
|
||||
expiry: item.expiry,
|
||||
appId: item.appId || "",
|
||||
createdAt: item.createdAt || null,
|
||||
}))
|
||||
.filter((item) => item.hash && (!item.expiry || new Date(item.expiry).getTime() > now))
|
||||
.filter((item) => !appKey || item.appId !== appKey)
|
||||
.slice(-(MAX_TOKEN_SESSIONS - 1));
|
||||
sessions.push({ hash, expiry, appId: appKey, createdAt: new Date(now) });
|
||||
|
||||
user.security.tokens = sessions;
|
||||
// 旧字段镜像最新会话,兼容仍读取 security.token 的存量客户端
|
||||
user.security.token = hash;
|
||||
user.security.tokenExpiry = expiry;
|
||||
user.security.lastLoginAt = new Date(now);
|
||||
await user.save();
|
||||
return { raw, tokenExpiry: user.security.tokenExpiry };
|
||||
return { raw, tokenExpiry: expiry };
|
||||
}
|
||||
|
||||
// 登录/注册响应:脱敏后单独附加本次签发的原始 token
|
||||
@@ -335,7 +370,7 @@ class HandlerUser {
|
||||
}
|
||||
|
||||
try {
|
||||
const { mobile, passwd } = value;
|
||||
const { mobile, passwd, appId } = value;
|
||||
|
||||
// 查找用户
|
||||
let user = await DBModel.User.findOne({ "profile.mobile": mobile });
|
||||
@@ -378,7 +413,7 @@ class HandlerUser {
|
||||
|
||||
// 生成/更新 token(哈希入库)
|
||||
user.security.lastLoginIp = ctx.ip || ctx.request.ip;
|
||||
const { raw } = await this.issueToken(user);
|
||||
const { raw } = await this.issueToken(user, appId);
|
||||
|
||||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功");
|
||||
} catch (err) {
|
||||
@@ -583,20 +618,32 @@ class HandlerUser {
|
||||
});
|
||||
if (!membership) return ResponseUtil.forbidden(ctx, "无后台管理权限");
|
||||
|
||||
const { raw } = await this.issueToken(user);
|
||||
const { raw } = await this.issueToken(user, WEB_ADMIN_APP);
|
||||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 退出登录
|
||||
// 退出登录:只失效当前端的会话,其它端保持在线
|
||||
async signout(ctx) {
|
||||
// auth({required:false}) 中间件已验证登录态
|
||||
const user = ctx.state.user;
|
||||
if (user) {
|
||||
user.security.token = null;
|
||||
user.security.tokenExpiry = null;
|
||||
const raw = extractToken(ctx);
|
||||
if (raw) {
|
||||
const hashed = await hashToken(raw);
|
||||
const sessions = (Array.isArray(user.security.tokens) ? user.security.tokens : [])
|
||||
.filter((item) => item.hash && item.hash !== hashed);
|
||||
user.security.tokens = sessions;
|
||||
|
||||
// 旧字段指向被登出的会话时,回退到剩余会话中最新的那条
|
||||
if (user.security.token === hashed) {
|
||||
const latest = sessions[sessions.length - 1];
|
||||
user.security.token = latest?.hash || null;
|
||||
user.security.tokenExpiry = latest?.expiry || null;
|
||||
}
|
||||
}
|
||||
await user.save();
|
||||
}
|
||||
|
||||
@@ -816,9 +863,10 @@ class HandlerUser {
|
||||
"meta.updatetime": Date.now(),
|
||||
};
|
||||
if (locked) {
|
||||
// 作废已有会话,避免锁定了却还能继续用旧 token
|
||||
// 作废全部会话,避免锁定了却还能继续用旧 token
|
||||
set["security.token"] = null;
|
||||
set["security.tokenExpiry"] = null;
|
||||
set["security.tokens"] = [];
|
||||
} else {
|
||||
set["security.failedLoginAttempts"] = 0;
|
||||
}
|
||||
@@ -1220,7 +1268,7 @@ class HandlerUser {
|
||||
|
||||
// 8. 更新Token(哈希入库)
|
||||
user.security.lastLoginIp = ctx.ip || ctx.request.ip;
|
||||
const { raw } = await this.issueToken(user);
|
||||
const { raw } = await this.issueToken(user, appId);
|
||||
|
||||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功");
|
||||
} catch (err) {
|
||||
|
||||
+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;
|
||||
|
||||
@@ -31,6 +31,17 @@ const UserSchema = mongoose.Schema(
|
||||
passwdSalt: { type: String, comment: '密码盐值' },
|
||||
token: { type: String, index: true, sparse: true, comment: '认证令牌' },
|
||||
tokenExpiry: { type: Date, comment: '令牌过期时间' },
|
||||
// 多端会话:每次登录追加一条(只存哈希),各端互不覆盖;
|
||||
// token/tokenExpiry 保留为最新会话的镜像,兼容仍读旧字段的客户端
|
||||
tokens: [
|
||||
{
|
||||
_id: false,
|
||||
hash: { type: String, index: true, sparse: true, comment: '令牌哈希' },
|
||||
expiry: { type: Date, comment: '过期时间' },
|
||||
appId: { type: String, default: '', comment: '登录来源应用' },
|
||||
createdAt: { type: Date, default: Date.now, comment: '签发时间' },
|
||||
},
|
||||
],
|
||||
failedLoginAttempts: { type: Number, default: 0, comment: '失败登录尝试次数' },
|
||||
lastLoginAt: { type: Date, comment: '最后登录时间' },
|
||||
lastLoginIp: { type: String, comment: '最后登录IP' },
|
||||
|
||||
@@ -129,6 +129,84 @@ describe('用户接口集成测试', () => {
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
|
||||
it('多端登录互不踢下线,登出只失效当前端', async () => {
|
||||
// 模拟另一端登录:新 token 不应让已有 token 失效
|
||||
const second = await agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile: testMobile, passwd: testPasswd });
|
||||
|
||||
assert.equal(second.body.code, 0, second.body.msg);
|
||||
const secondToken = second.body.data.user.security.token;
|
||||
assert.notEqual(secondToken, token);
|
||||
|
||||
const firstInfo = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
assert.equal(firstInfo.body.code, 0, '另一端登录后,原 token 不应失效');
|
||||
|
||||
const secondInfo = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${secondToken}`)
|
||||
.send({});
|
||||
assert.equal(secondInfo.body.code, 0, secondInfo.body.msg);
|
||||
|
||||
// 登出第二端,第一端保持在线
|
||||
const out = await agent
|
||||
.post('/user/signout')
|
||||
.set('Authorization', `Bearer ${secondToken}`)
|
||||
.send({});
|
||||
assert.equal(out.body.code, 0, out.body.msg);
|
||||
|
||||
const stillOnline = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
assert.equal(stillOnline.body.code, 0, '登出另一端不应影响本端');
|
||||
|
||||
const revoked = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${secondToken}`)
|
||||
.send({});
|
||||
assert.equal(revoked.body.code, 401);
|
||||
});
|
||||
|
||||
it('同一应用重复登录替换旧会话,不同应用各自保留', async () => {
|
||||
const login = (appId) => agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile: testMobile, passwd: testPasswd, appId });
|
||||
|
||||
const admin1 = await login('web-escort-admin');
|
||||
const wx = await login('wxapp-escort-admin');
|
||||
assert.equal(admin1.body.code, 0, admin1.body.msg);
|
||||
assert.equal(wx.body.code, 0, wx.body.msg);
|
||||
const admin1Token = admin1.body.data.user.security.token;
|
||||
const wxToken = wx.body.data.user.security.token;
|
||||
|
||||
// 管理端再次登录:只替换管理端自己的会话
|
||||
const admin2 = await login('web-escort-admin');
|
||||
assert.equal(admin2.body.code, 0, admin2.body.msg);
|
||||
const admin2Token = admin2.body.data.user.security.token;
|
||||
|
||||
const oldAdmin = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${admin1Token}`)
|
||||
.send({});
|
||||
assert.equal(oldAdmin.body.code, 401, '同一应用旧会话应被替换');
|
||||
|
||||
const newAdmin = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${admin2Token}`)
|
||||
.send({});
|
||||
assert.equal(newAdmin.body.code, 0, newAdmin.body.msg);
|
||||
|
||||
const wxStill = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${wxToken}`)
|
||||
.send({});
|
||||
assert.equal(wxStill.body.code, 0, '管理端重新登录不应踢掉小程序端');
|
||||
});
|
||||
|
||||
it('不存在的用户应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/signin')
|
||||
|
||||
Reference in New Issue
Block a user