Spaces:
Running
Running
File size: 1,477 Bytes
e8c33fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | const test = require('node:test');
const assert = require('node:assert/strict');
require('dotenv').config();
test('protect strips passwordHash from req.user', async () => {
const { protect } = require('../middleware/authMiddleware');
const AdminUser = require('../models/AdminUser');
const originalFindById = AdminUser.findById.bind(AdminUser);
let selectCalledWith = null;
AdminUser.findById = () => ({
select: (projection) => {
selectCalledWith = projection;
return {
lean: async () => ({
_id: '507f1f77bcf86cd799439011',
username: 'testadmin',
role: 'admin',
isActive: true,
passwordHash: '$2b$12$SHOULDNOTLEAKTHIS',
}),
};
},
});
const jwt = require('jsonwebtoken');
const { env } = require('../configs/env');
const token = jwt.sign(
{ id: '507f1f77bcf86cd799439011' },
env.jwtSecret || 'test-secret-32-characters-minimum!!',
{ expiresIn: '1h' }
);
const req = { cookies: { token } };
const res = {};
let nextCalled = false;
const next = () => { nextCalled = true; };
await protect(req, res, next);
AdminUser.findById = originalFindById;
assert.ok(nextCalled, 'next() should have been called');
assert.ok(selectCalledWith && selectCalledWith.includes('-passwordHash'), `select must exclude passwordHash, got: ${selectCalledWith}`);
assert.equal(req.user.passwordHash, undefined, 'passwordHash must not be on req.user');
});
|