diff --git a/server/middleware/rbac.js b/server/middleware/rbac.js index 98f98f3..38c59ea 100644 --- a/server/middleware/rbac.js +++ b/server/middleware/rbac.js @@ -155,6 +155,32 @@ const checkPermission = (userRole, resource, action) => { return hasPermission(userRole, permission); }; +/** + * Compatibility function for tests - creates middleware for specific resource.action + * @param {string} resource - The resource (e.g., 'devices', 'users') + * @param {string} action - The action (e.g., 'read', 'create', 'update', 'delete') + * @returns {Function} - Express middleware function + */ +const requirePermission = (resource, action) => { + return (req, res, next) => { + if (!req.user || !req.user.role) { + return res.status(403).json({ + success: false, + message: 'Access denied - no user role' + }); + } + + if (!checkPermission(req.user.role, resource, action)) { + return res.status(403).json({ + success: false, + message: 'Access denied - insufficient permissions' + }); + } + + next(); + }; +}; + /** * Check if a user has any of the specified permissions * @param {string} userRole - The user's role @@ -261,6 +287,7 @@ module.exports = { ROLES, hasPermission, checkPermission, + requirePermission, hasAnyPermission, hasAllPermissions, getPermissions, diff --git a/server/tests/middleware/rbac.test.js b/server/tests/middleware/rbac.test.js index 4d2d17a..c1346de 100644 --- a/server/tests/middleware/rbac.test.js +++ b/server/tests/middleware/rbac.test.js @@ -1,7 +1,7 @@ const { describe, it, beforeEach, afterEach, before, after } = require('mocha'); const { expect } = require('chai'); const sinon = require('sinon'); -const { hasPermission, checkPermission, requirePermissions } = require('../../middleware/rbac'); +const { hasPermission, checkPermission, requirePermission, requirePermissions } = require('../../middleware/rbac'); const { setupTestEnvironment, teardownTestEnvironment, cleanDatabase, mockRequest, mockResponse, mockNext, createTestUser, createTestTenant } = require('../setup'); describe('RBAC Middleware', () => { diff --git a/server/tests/setup.js b/server/tests/setup.js index 3430def..475fab6 100644 --- a/server/tests/setup.js +++ b/server/tests/setup.js @@ -215,7 +215,11 @@ async function createTestDetection(detectionData = {}) { async function createTestTenant(tenantData = {}) { const { Tenant } = models; + // Generate a simple test ID for tenant + const testId = 'tenant-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9); + const defaultTenantData = { + id: testId, // Use explicit test ID name: 'Test Tenant', slug: 'test-tenant-' + Date.now(), domain: 'test.example.com',