diff --git a/backend/tests/rbac.integration.test.js b/backend/tests/rbac.integration.test.js new file mode 100644 index 0000000..cf495d7 --- /dev/null +++ b/backend/tests/rbac.integration.test.js @@ -0,0 +1,94 @@ +const request = require('supertest'); +const app = require('../app'); +const { createUser, createAdminUser } = require('./test-utils'); + +describe('RBAC Integration Tests', () => { + let userToken; + let adminToken; + let testUser; + + beforeAll(async () => { + // Create a regular user + testUser = await createUser({ + name: 'Test User', + email: 'testuser@example.com', + password: 'password123', + role: 'user' + }); + + // Create an admin user + const adminUser = await createAdminUser({ + name: 'Admin User', + email: 'admin@example.com', + password: 'password123', + role: 'admin' + }); + + // Login to get tokens + const userResponse = await request(app) + .post('/api/auth/login') + .send({ + email: testUser.email, + password: 'password123' + }); + + const adminResponse = await request(app) + .post('/api/auth/login') + .send({ + email: adminUser.email, + password: 'password123' + }); + + userToken = userResponse.body.token; + adminToken = adminResponse.body.token; + }); + + describe('Protected Routes', () => { + // Test that regular users cannot access admin-only routes + it('should deny access to admin-only routes for regular users', async () => { + const response = await request(app) + .get('/api/roles') + .set('Authorization', `Bearer ${userToken}`) + .expect(403); + + expect(response.body.error).toBe('Insufficient permissions'); + }); + + // Test that admin users can access admin-only routes + it('should allow access to admin-only routes for admins', async () => { + const response = await request(app) + .get('/api/roles') + .set('Authorization', `Bearer ${adminToken}`) + .expect(200); + + expect(response.body).toBeDefined(); + }); + + // Test that unauthenticated users cannot access protected routes + it('should deny access to protected routes for unauthenticated users', async () => { + const response = await request(app) + .get('/api/roles') + .expect(401); + + expect(response.body.error).toBe('Authentication required'); + }); + }); + + describe('Role-based Access Control Middleware', () => { + // Test that requireRole middleware works correctly + it('should validate role requirements properly', async () => { + // This test verifies the middleware logic by testing protected routes + const response = await request(app) + .get('/api/roles') + .set('Authorization', `Bearer ${adminToken}`) + .expect(200); + + expect(response.body).toBeDefined(); + }); + }); + + afterAll(async () => { + // Cleanup test users if needed + // This would depend on your database setup + }); +}); \ No newline at end of file