2026-03-17 11:07:20 +00:00
|
|
|
const { requireRole } = require('../middleware/role.middleware');
|
2026-03-17 10:09:15 +00:00
|
|
|
|
2026-03-17 17:06:42 +00:00
|
|
|
describe('Role-based Access Control', () => {
|
|
|
|
|
// Test that the middleware exists and is a function
|
2026-03-17 11:07:20 +00:00
|
|
|
test('requireRole should be a function', () => {
|
|
|
|
|
expect(typeof requireRole).toBe('function');
|
2026-03-16 21:07:16 +00:00
|
|
|
});
|
|
|
|
|
|
2026-03-17 17:06:42 +00:00
|
|
|
// Test that middleware allows access for users with correct role
|
|
|
|
|
test('should allow access for user with correct role', () => {
|
|
|
|
|
// This would need to be implemented with actual JWT mocking
|
2026-03-17 18:07:07 +00:00
|
|
|
// For now, just testing the middleware structure
|
|
|
|
|
const mockReq = { user: { role: 'admin' } };
|
|
|
|
|
const mockRes = {
|
|
|
|
|
status: jest.fn().mockReturnThis(),
|
|
|
|
|
json: jest.fn()
|
|
|
|
|
};
|
|
|
|
|
const mockNext = jest.fn();
|
|
|
|
|
|
2026-03-17 17:06:42 +00:00
|
|
|
const middleware = requireRole(['admin']);
|
2026-03-17 18:07:07 +00:00
|
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
|
|
|
|
|
|
expect(mockNext).toHaveBeenCalled();
|
2026-03-17 17:06:42 +00:00
|
|
|
});
|
|
|
|
|
|
2026-03-17 18:07:07 +00:00
|
|
|
// Test that middleware denies access for users with incorrect role
|
|
|
|
|
test('should deny access for user with incorrect role', () => {
|
|
|
|
|
const mockReq = { user: { role: 'user' } };
|
|
|
|
|
const mockRes = {
|
|
|
|
|
status: jest.fn().mockReturnThis(),
|
|
|
|
|
json: jest.fn()
|
|
|
|
|
};
|
|
|
|
|
const mockNext = jest.fn();
|
|
|
|
|
|
|
|
|
|
const middleware = requireRole(['admin']);
|
|
|
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
|
|
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(403);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Test that middleware denies access for unauthenticated users
|
|
|
|
|
test('should deny access for unauthenticated user', () => {
|
|
|
|
|
const mockReq = { };
|
|
|
|
|
const mockRes = {
|
|
|
|
|
status: jest.fn().mockReturnThis(),
|
|
|
|
|
json: jest.fn()
|
|
|
|
|
};
|
|
|
|
|
const mockNext = jest.fn();
|
|
|
|
|
|
2026-03-17 17:06:42 +00:00
|
|
|
const middleware = requireRole(['admin']);
|
2026-03-17 18:07:07 +00:00
|
|
|
middleware(mockReq, mockRes, mockNext);
|
|
|
|
|
|
|
|
|
|
expect(mockRes.status).toHaveBeenCalledWith(401);
|
2026-03-16 21:07:16 +00:00
|
|
|
});
|
|
|
|
|
});
|