完善了安全功能
This commit is contained in:
85
test/auth.test.js
Normal file
85
test/auth.test.js
Normal file
@@ -0,0 +1,85 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractToken, sanitizeUser } from '../middleware/auth.js';
|
||||
|
||||
// 模拟 ctx 对象
|
||||
function mockCtx(overrides = {}) {
|
||||
return {
|
||||
header: {},
|
||||
request: { body: {}, query: {} },
|
||||
ip: '127.0.0.1',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('extractToken', () => {
|
||||
it('优先从 Authorization Bearer header 提取', () => {
|
||||
const ctx = mockCtx({
|
||||
header: { authorization: 'Bearer abc123' },
|
||||
request: { body: { token: 'body_token' } },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'abc123');
|
||||
});
|
||||
|
||||
it('无 Bearer header 时从 body 提取', () => {
|
||||
const ctx = mockCtx({
|
||||
request: { body: { token: 'body_token' } },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'body_token');
|
||||
});
|
||||
|
||||
it('无 Bearer header 时从 query 提取', () => {
|
||||
const ctx = mockCtx({
|
||||
request: { query: { token: 'query_token' } },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'query_token');
|
||||
});
|
||||
|
||||
it('无 Bearer header 时从 header token 字段提取', () => {
|
||||
const ctx = mockCtx({
|
||||
header: { token: 'header_token' },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'header_token');
|
||||
});
|
||||
|
||||
it('无任何 token 时返回 undefined', () => {
|
||||
const ctx = mockCtx();
|
||||
assert.equal(extractToken(ctx), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeUser', () => {
|
||||
it('应删除密码和重置令牌相关字段', () => {
|
||||
const user = {
|
||||
toObject: () => ({
|
||||
profile: { mobile: '13800138000' },
|
||||
security: {
|
||||
passwd: 'hashed',
|
||||
passwdSalt: 'salt',
|
||||
token: 'valid_token',
|
||||
passwordResetToken: 'reset_token',
|
||||
passwordResetExpiry: new Date(),
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const safe = sanitizeUser(user);
|
||||
assert.equal(safe.security.passwd, undefined);
|
||||
assert.equal(safe.security.passwdSalt, undefined);
|
||||
assert.equal(safe.security.passwordResetToken, undefined);
|
||||
assert.equal(safe.security.passwordResetExpiry, undefined);
|
||||
assert.equal(safe.security.token, 'valid_token');
|
||||
assert.equal(safe.profile.mobile, '13800138000');
|
||||
});
|
||||
|
||||
it('处理普通对象(无 toObject 方法)', () => {
|
||||
const user = {
|
||||
profile: { mobile: '13800138000' },
|
||||
security: { passwd: 'x', passwdSalt: 'y' },
|
||||
};
|
||||
|
||||
const safe = sanitizeUser(user);
|
||||
assert.equal(safe.security.passwd, undefined);
|
||||
assert.equal(safe.security.passwdSalt, undefined);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user