|
| 1 | +const authorize = require('../middlewares/authorize'); |
| 2 | + |
| 3 | +describe('Authorize Middleware', () => { |
| 4 | + let req; |
| 5 | + let res; |
| 6 | + let next; |
| 7 | + |
| 8 | + beforeEach(() => { |
| 9 | + req = { |
| 10 | + user: null, |
| 11 | + }; |
| 12 | + res = { |
| 13 | + status: jest.fn().mockReturnThis(), |
| 14 | + json: jest.fn().mockReturnThis(), |
| 15 | + }; |
| 16 | + next = jest.fn(); |
| 17 | + }); |
| 18 | + |
| 19 | + it('should call next if user has an allowed role', () => { |
| 20 | + req.user = { role: 'admin' }; |
| 21 | + const middleware = authorize('admin', 'superadmin'); |
| 22 | + |
| 23 | + middleware(req, res, next); |
| 24 | + |
| 25 | + expect(next).toHaveBeenCalledWith(); |
| 26 | + expect(next).not.toHaveBeenCalledWith(expect.any(Error)); |
| 27 | + }); |
| 28 | + |
| 29 | + it('should return 401 if user is not authenticated', () => { |
| 30 | + req.user = null; |
| 31 | + const middleware = authorize('admin'); |
| 32 | + |
| 33 | + middleware(req, res, next); |
| 34 | + |
| 35 | + expect(next).toHaveBeenCalledWith(expect.objectContaining({ |
| 36 | + statusCode: 401, |
| 37 | + message: 'Authentication required' |
| 38 | + })); |
| 39 | + }); |
| 40 | + |
| 41 | + it('should return 403 if user role is not allowed', () => { |
| 42 | + req.user = { role: 'user' }; |
| 43 | + const middleware = authorize('admin'); |
| 44 | + |
| 45 | + middleware(req, res, next); |
| 46 | + |
| 47 | + expect(next).toHaveBeenCalledWith(expect.objectContaining({ |
| 48 | + statusCode: 403, |
| 49 | + message: 'Access forbidden: insufficient permissions' |
| 50 | + })); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should work with multiple allowed roles', () => { |
| 54 | + req.user = { role: 'editor' }; |
| 55 | + const middleware = authorize('admin', 'editor'); |
| 56 | + |
| 57 | + middleware(req, res, next); |
| 58 | + |
| 59 | + expect(next).toHaveBeenCalledWith(); |
| 60 | + }); |
| 61 | +}); |
0 commit comments