后端 - 新增 service/mail_quota.js:每个邮箱每天最多 config.email.dailyLimit(默认 10,EMAIL_DAILY_LIMIT)封, 注册验证码与找回密码**共用**额度;按北京时间切日,key TTL 到次日 0 点; 发信失败 / 被 60 秒节流拦下会还回额度;超限返回 429 daily_limit「… 请明天再试」 - service.user.findByEmail() / emailExists():LOWER(email) 查询(大小写不敏感)+ paranoid:false (软删除账号仍占用邮箱),单测环境无 sequelize 时退化为等值查询 - register/code:先判邮箱已占用 → 409 email_taken(含「忘记密码可找回」提示),一封邮件都不发; 发送失败/超限统一返回 429 + status(daily_limit / send_failed) - register:提交时再判一次邮箱占用(防发码后被抢注) - forgot:改用 findByEmail(大小写/软删除一致),日额度与注册共用,超限 429 - 单测:新增「邮箱已使用不发信」「每日 10 封上限(注册/找回)」4 个用例;fake-redis 补 decr 前端 - 登录页获取验证码:先做邮箱格式校验,并展示后端 409/429 的具体文案 - 忘记密码页:邮箱格式校验 + 小写归一,429 文案直接显示 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
293 lines
13 KiB
JavaScript
293 lines
13 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
const bcrypt = require('bcryptjs');
|
||
const jwt = require('jsonwebtoken');
|
||
const createFakeRedis = require('../../utils/fake-redis');
|
||
|
||
const instance = (data) => Object.assign(
|
||
{
|
||
toJSON: () => data,
|
||
update: async (fields) => Object.assign(data, fields),
|
||
},
|
||
data,
|
||
);
|
||
|
||
describe('test/app/controller/web.test.js', () => {
|
||
const passwordHash = bcrypt.hashSync('secret-pass', 4);
|
||
const userRow = {
|
||
id: 1,
|
||
username: 'admin',
|
||
nickname: '管理员',
|
||
email: 'admin@example.com',
|
||
phone: '13800000001',
|
||
status: 1,
|
||
passwordHash,
|
||
};
|
||
|
||
/** 用户模型:按账号查 / 按主键查 */
|
||
function mockUser(user = userRow) {
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findOne() {
|
||
return instance(Object.assign({}, user, { update: async fields => Object.assign(user, fields) }));
|
||
},
|
||
async findByPk(id) {
|
||
return instance(Object.assign({}, user, { id }));
|
||
},
|
||
},
|
||
});
|
||
}
|
||
|
||
it('POST /api/web/auth/login:账号密码换取 user JWT(不依赖 cookie/CSRF)', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/auth/login')
|
||
.send({ account: 'admin', password: 'secret-pass' })
|
||
.expect(200);
|
||
|
||
assert(res.body.ok === true, JSON.stringify(res.body));
|
||
const { token, tokenType, expiresIn, user } = res.body.data;
|
||
assert(tokenType === 'Bearer' && expiresIn === app.config.jwt.userExpiresIn, JSON.stringify(res.body.data));
|
||
assert(user.id === 1 && user.username === 'admin' && user.passwordHash === undefined, JSON.stringify(user));
|
||
|
||
const payload = jwt.decode(token);
|
||
assert(payload.typ === 'user' && Number(payload.sub) === 1, JSON.stringify(payload));
|
||
assert(!(res.headers['set-cookie'] || []).some(item => item.startsWith('packs_sess')), '不应下发登录态 cookie');
|
||
});
|
||
|
||
it('POST /api/web/auth/login:密码错 / 缺参', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
|
||
let res = await app.httpRequest().post('/api/web/auth/login').send({ account: 'admin', password: 'wrong' }).expect(401);
|
||
assert(res.body.status === 'unauthorized' && res.body.message.includes('账号或密码错误'), JSON.stringify(res.body));
|
||
|
||
res = await app.httpRequest().post('/api/web/auth/login').send({ account: 'admin' }).expect(422);
|
||
assert(res.body.ok === false, JSON.stringify(res.body));
|
||
});
|
||
|
||
const requiredAgreement = {
|
||
id: 9,
|
||
code: 'user_agreement',
|
||
name: '用户协议',
|
||
required: true,
|
||
version: { id: 11, version: '1.0.0', title: '用户协议', content: '正文' },
|
||
};
|
||
|
||
it('POST /api/web/auth/login:小程序未同意协议 → 428 agreement_required', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
app.mockService('agreement', 'requiredVersions', async () => [ requiredAgreement ]);
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/auth/login')
|
||
.send({ account: 'admin', password: 'secret-pass', client: 'mini_program' })
|
||
.expect(428);
|
||
|
||
assert(res.body.status === 'agreement_required', JSON.stringify(res.body));
|
||
assert(res.body.data.agreements[0].code === 'user_agreement', JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/auth/login:小程序同意当前版本 → 记录版本并登录成功', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
|
||
let recorded = null;
|
||
app.mockService('agreement', 'requiredVersions', async () => [ requiredAgreement ]);
|
||
app.mockService('agreement', 'record', async (userId, accepted) => {
|
||
recorded = { userId, accepted };
|
||
return accepted.map(item => ({
|
||
code: item.code,
|
||
versionId: item.versionId,
|
||
version: item.version,
|
||
agreedAt: new Date().toISOString(),
|
||
}));
|
||
});
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/auth/login')
|
||
.send({
|
||
account: 'admin',
|
||
password: 'secret-pass',
|
||
client: 'mini_program',
|
||
agreements: [{ code: 'user_agreement', versionId: 11 }],
|
||
})
|
||
.expect(200);
|
||
|
||
assert(res.body.ok === true, JSON.stringify(res.body));
|
||
assert(recorded && recorded.userId === 1, JSON.stringify(recorded));
|
||
assert(recorded.accepted[0].versionId === 11 && recorded.accepted[0].version === '1.0.0', JSON.stringify(recorded));
|
||
assert(res.body.data.agreements[0].version === '1.0.0', JSON.stringify(res.body.data));
|
||
});
|
||
|
||
it('GET /api/web/me / PUT /api/web/me / PUT /api/web/me/password:都按令牌里的用户操作', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
let updated = null;
|
||
/** ⚠️ mock 会忽略 attributes.exclude,这里手动模拟 service 的 SAFE_ATTRIBUTES(不吐密码哈希) */
|
||
const safeRow = () => {
|
||
const { passwordHash: _omit, ...safe } = userRow;
|
||
return safe;
|
||
};
|
||
mock(app, 'model', {
|
||
User: {
|
||
// 真 service 的行为:默认不返回密码哈希,只有显式 include('passwordHash') 时才带
|
||
async findByPk(id, options) {
|
||
assert(String(id) === '1');
|
||
const wantHash = Boolean(options?.attributes?.include?.includes('passwordHash'));
|
||
const data = wantHash ? Object.assign({}, userRow) : safeRow();
|
||
const row = instance(data);
|
||
// update 要同时写进实例的 toJSON 数据,否则控制器回显还是旧值
|
||
row.update = async fields => {
|
||
updated = Object.assign(updated || {}, fields);
|
||
Object.assign(data, fields);
|
||
Object.assign(userRow, fields);
|
||
};
|
||
return row;
|
||
},
|
||
},
|
||
});
|
||
|
||
const token = app.createAnonymousContext().service.jwt.signUser(userRow);
|
||
const auth = { Authorization: `Bearer ${token}` };
|
||
|
||
let res = await app.httpRequest().get('/api/web/me').set(auth).expect(200);
|
||
assert(res.body.data.username === 'admin' && res.body.data.passwordHash === undefined, JSON.stringify(res.body.data));
|
||
await app.httpRequest().get('/api/web/me').expect(401);
|
||
|
||
res = await app.httpRequest().put('/api/web/me').set(auth).send({ nickname: '新昵称' }).expect(200);
|
||
assert(res.body.data.nickname === '新昵称' && updated.nickname === '新昵称', JSON.stringify(updated));
|
||
|
||
// 改密码:原密码错 → 422;正确 → 200
|
||
await app.httpRequest().put('/api/web/me/password').set(auth).send({ oldPassword: 'nope', newPassword: 'new-pass' }).expect(422);
|
||
await app.httpRequest().put('/api/web/me/password').set(auth).send({ oldPassword: 'secret-pass', newPassword: 'new-pass' }).expect(200);
|
||
assert(await bcrypt.compare('new-pass', userRow.passwordHash), '应写入新密码哈希');
|
||
});
|
||
|
||
it('POST /api/web/auth/forgot:邮箱未注册也返回成功(防账号枚举)', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mock(app, 'model', {
|
||
User: { async findOne() { return null; } },
|
||
});
|
||
|
||
const res = await app.httpRequest().post('/api/web/auth/forgot').send({ email: 'nobody@example.com' }).expect(200);
|
||
assert(res.body.data.sent === true && res.body.data.url === undefined, JSON.stringify(res.body));
|
||
|
||
await app.httpRequest().post('/api/web/auth/forgot').send({ email: 'bad' }).expect(422);
|
||
});
|
||
|
||
it('POST /api/web/auth/forgot:重发节流返回 429 + 友好文案(不是 500)', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockUser();
|
||
|
||
// 第一次:正常发出(devMode 会把链接带回来)
|
||
const first = await app.httpRequest().post('/api/web/auth/forgot').send({ email: userRow.email }).expect(200);
|
||
assert(first.body.data.sent === true, JSON.stringify(first.body));
|
||
assert((first.body.data.url || '').includes('/reset?token='), 'devMode 应回带令牌的链接');
|
||
|
||
// 立刻再发:命中 resendInterval 节流 → 429(之前是 500「服务器内部错误」,用户看不懂)
|
||
const again = await app.httpRequest().post('/api/web/auth/forgot').send({ email: userRow.email }).expect(429);
|
||
assert(again.body.status === 'throttled', JSON.stringify(again.body));
|
||
assert(/秒后再试/.test(again.body.message), JSON.stringify(again.body));
|
||
});
|
||
|
||
it('POST /api/web/auth/forgot:同一邮箱当天超过 10 封 → 429,提示明天再试', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockUser();
|
||
|
||
// 直接把当日额度打到上限(模拟已经发过 10 封)
|
||
const limit = app.config.email.dailyLimit;
|
||
const day = app.createAnonymousContext().service.mailQuota.today();
|
||
await fake.client.set(`${app.config.cache.prefix}mailquota:${userRow.email}:${day}`, String(limit));
|
||
|
||
const res = await app.httpRequest().post('/api/web/auth/forgot').send({ email: userRow.email }).expect(429);
|
||
assert(res.body.status === 'daily_limit', JSON.stringify(res.body));
|
||
assert(/明天再试/.test(res.body.message), JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/auth/register/code:邮箱已使用 → 409,且不再发验证码', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockUser();
|
||
|
||
const res = await app.httpRequest().post('/api/web/auth/register/code').send({ email: userRow.email }).expect(409);
|
||
assert(res.body.status === 'email_taken', JSON.stringify(res.body));
|
||
assert(/已被使用/.test(res.body.message), JSON.stringify(res.body));
|
||
|
||
// 没有占用任何发信额度(说明压根没发)
|
||
const day = app.createAnonymousContext().service.mailQuota.today();
|
||
const used = await fake.client.get(`${app.config.cache.prefix}mailquota:${userRow.email}:${day}`);
|
||
assert(!used, `邮箱已占用时不应发信,实际额度记录=${used}`);
|
||
});
|
||
|
||
it('POST /api/web/auth/register/code:新邮箱当天超过 10 封 → 429,提示明天再试', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mock(app, 'model', { User: { async findOne() { return null; } } });
|
||
|
||
const email = 'newbie@example.com';
|
||
const limit = app.config.email.dailyLimit;
|
||
const day = app.createAnonymousContext().service.mailQuota.today();
|
||
await fake.client.set(`${app.config.cache.prefix}mailquota:${email}:${day}`, String(limit));
|
||
|
||
const res = await app.httpRequest().post('/api/web/auth/register/code').send({ email }).expect(429);
|
||
assert(res.body.status === 'daily_limit', JSON.stringify(res.body));
|
||
assert(/明天再试/.test(res.body.message), JSON.stringify(res.body));
|
||
});
|
||
|
||
it('改密 / 重置密码后,旧 user JWT 立即失效(password_changed_at)', async () => {
|
||
const user = Object.assign({}, userRow, { passwordChangedAt: null });
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findOne() { return instance(user); },
|
||
async findByPk(id) { return instance(Object.assign(user, { id })); },
|
||
},
|
||
});
|
||
|
||
const cfgJwt = app.config.jwt;
|
||
const iat = Math.floor(Date.now() / 1000) - 600; // 10 分钟前签发
|
||
const oldToken = jwt.sign(
|
||
{ sub: String(userRow.id), username: 'admin', typ: 'user', iat },
|
||
cfgJwt.secret,
|
||
{ issuer: cfgJwt.issuer, audience: cfgJwt.audience, expiresIn: '1h' },
|
||
);
|
||
const oldAuth = { Authorization: `Bearer ${oldToken}` };
|
||
|
||
// 没改过密码:旧令牌正常可用
|
||
await app.httpRequest().get('/api/web/me').set(oldAuth).expect(200);
|
||
|
||
// 刚改过密码(改密时间晚于旧令牌的 iat)→ 旧令牌 401,且带明确原因
|
||
user.passwordChangedAt = new Date((iat + 300) * 1000);
|
||
const stale = await app.httpRequest().get('/api/web/me').set(oldAuth).expect(401);
|
||
assert(stale.body.status === 'password_changed', JSON.stringify(stale.body));
|
||
assert(/重新登录/.test(stale.body.message), JSON.stringify(stale.body));
|
||
|
||
// 改密之后重新签发的令牌(iat 更晚)照常可用
|
||
const fresh = app.createAnonymousContext().service.jwt.signUser(Object.assign({}, userRow));
|
||
await app.httpRequest().get('/api/web/me').set({ Authorization: `Bearer ${fresh}` }).expect(200);
|
||
|
||
// 且 passwordChangedAt 不会漏给前端
|
||
const me = await app.httpRequest().get('/api/web/me').set({ Authorization: `Bearer ${fresh}` }).expect(200);
|
||
assert(me.body.data.passwordChangedAt === undefined, JSON.stringify(me.body.data));
|
||
|
||
// 运维接口(internal_auth)同样拦旧令牌
|
||
await app.httpRequest().get('/api/users').set(oldAuth).expect(401);
|
||
});
|
||
|
||
it('GET /api/wechat/qrcode.svg:本地生成二维码(可直接给前端 img 用)', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
|
||
const res = await app.httpRequest().get('/api/wechat/qrcode.svg?code=AB12CD').expect(200);
|
||
assert(String(res.headers['content-type']).includes('image/svg+xml'), res.headers['content-type']);
|
||
// SVG 是二进制类响应,supertest 可能只给 res.body(Buffer)
|
||
const svg = res.text || String(res.body);
|
||
assert(svg.includes('<svg'), '应返回 SVG 源码');
|
||
assert(!/<image|xlink:href/i.test(svg), '不能引用外部资源');
|
||
});
|
||
});
|