tinfo-web-server / test /authMiddleware.test.js
Faridaqurr
initial backend
e8c33fa
Raw
History Blame Contribute Delete
1.48 kB
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');
});