@mamoorali295/rbac
Version:
Complete RBAC (Role-Based Access Control) system for Node.js with Express middleware, NestJS integration, GraphQL support, MongoDB & PostgreSQL support, modern admin dashboard, TypeScript support, and dynamic permission management
385 lines (384 loc) • 14.5 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RbacAdminService = void 0;
const common_1 = require("@nestjs/common");
const DatabaseAdapter_1 = require("../adapters/DatabaseAdapter");
/**
* NestJS Admin Service for RBAC Dashboard
* Provides business logic for the admin dashboard operations.
* Handles all database operations through the DatabaseAdapter.
*
* Features:
* - User management (CRUD operations)
* - Role management with feature assignments
* - Feature and permission management
* - Dashboard statistics
* - Admin authentication validation
*
* @example
* ```typescript
* @Injectable()
* export class MyAdminService {
* constructor(private adminService: RbacAdminService) {}
*
* async getAdminStats() {
* return await this.adminService.getDashboardStats();
* }
*
* async manageUsers() {
* const users = await this.adminService.getAllUsers(10, 0, '');
* return users;
* }
* }
* ```
*/
let RbacAdminService = class RbacAdminService {
constructor(config, dbAdapter, adminConfig) {
this.config = config;
this.dbAdapter = dbAdapter;
this.adminCredentials = adminConfig.adminCredentials;
}
// =====================================
// AUTHENTICATION METHODS
// =====================================
/**
* Validate admin credentials for authentication
* @param username - Admin username
* @param password - Admin password
* @returns Promise<boolean> - True if credentials are valid
*/
validateAdmin(username, password) {
return __awaiter(this, void 0, void 0, function* () {
return (username === this.adminCredentials.username &&
password === this.adminCredentials.password);
});
}
// =====================================
// DASHBOARD STATISTICS
// =====================================
/**
* Get dashboard statistics including counts of users, roles, features, and permissions
* @returns Promise<DashboardStats> - Dashboard statistics object
*/
getDashboardStats() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.getDashboardStats();
});
}
// =====================================
// USER MANAGEMENT METHODS
// =====================================
/**
* Get all users with pagination and search functionality
* @param limit - Number of users per page
* @param skip - Number of users to skip (for pagination)
* @param search - Search query for filtering users
* @returns Promise with users array and total count
*/
getAllUsers(limit_1, skip_1) {
return __awaiter(this, arguments, void 0, function* (limit, skip, search = '') {
return yield this.dbAdapter.getAllUsers(limit, skip, search);
});
}
/**
* Find user by user ID
* @param userId - Unique user identifier
* @returns Promise<any | null> - User object or null if not found
*/
findUserByUserId(userId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findUserByUserId(userId);
});
}
/**
* Find user by user ID with role information
* @param userId - Unique user identifier
* @returns Promise<any | null> - User object with role or null if not found
*/
findUserByUserIdWithRole(userId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findUserByUserIdWithRole(userId);
});
}
/**
* Create a new user in the RBAC system
* @param userData - User data object
* @returns Promise<any> - Created user object
*/
createUser(userData) {
return __awaiter(this, void 0, void 0, function* () {
const dbUserData = Object.assign(Object.assign({}, userData), { name: userData.name || '', email: userData.email || '' });
return yield this.dbAdapter.createUser(dbUserData);
});
}
/**
* Update user information
* @param userId - Unique user identifier
* @param updateData - Data to update
* @returns Promise<any> - Updated user object
*/
updateUser(userId, updateData) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.updateUser(userId, updateData);
});
}
/**
* Delete user from the RBAC system
* @param userId - Unique user identifier
* @returns Promise<void>
*/
deleteUser(userId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.deleteUser(userId);
});
}
// =====================================
// ROLE MANAGEMENT METHODS
// =====================================
/**
* Get all roles in the system
* @returns Promise with roles array and total count
*/
getAllRoles() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.getAllRoles();
});
}
/**
* Find role by name
* @param roleName - Role name
* @returns Promise<any | null> - Role object or null if not found
*/
findRoleByName(roleName) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findRoleByName(roleName);
});
}
/**
* Find role by ID with associated features
* @param roleId - Role identifier
* @returns Promise<any | null> - Role object with features or null if not found
*/
findRoleByIdWithFeatures(roleId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findRoleByIdWithFeatures(roleId);
});
}
/**
* Create a new role
* @param roleData - Role data object
* @returns Promise<any> - Created role object
*/
createRole(roleData) {
return __awaiter(this, void 0, void 0, function* () {
const dbRoleData = Object.assign(Object.assign({}, roleData), { description: roleData.description || '' });
return yield this.dbAdapter.createRole(dbRoleData);
});
}
/**
* Update role information
* @param roleId - Role identifier
* @param updateData - Data to update
* @returns Promise<any> - Updated role object
*/
updateRole(roleId, updateData) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.updateRole(roleId, updateData);
});
}
/**
* Delete role from the system
* @param roleId - Role identifier
* @returns Promise<void>
*/
deleteRole(roleId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.deleteRole(roleId);
});
}
/**
* Assign features and permissions to a role
* @param roleId - Role identifier
* @param featurePermissions - Array of feature-permission mappings
* @returns Promise<void>
*/
assignRoleFeaturePermissions(roleId, featurePermissions) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.assignRoleFeaturePermissions(roleId, featurePermissions);
});
}
// =====================================
// FEATURE MANAGEMENT METHODS
// =====================================
/**
* Get all features in the system
* @returns Promise with features array and total count
*/
getAllFeatures() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.getAllFeatures();
});
}
/**
* Find feature by name
* @param featureName - Feature name
* @returns Promise<any | null> - Feature object or null if not found
*/
findFeatureByName(featureName) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findFeatureByName(featureName);
});
}
/**
* Find feature by ID
* @param featureId - Feature identifier
* @returns Promise<any | null> - Feature object or null if not found
*/
findFeatureById(featureId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findFeatureById(featureId);
});
}
/**
* Create a new feature
* @param featureData - Feature data object
* @returns Promise<any> - Created feature object
*/
createFeature(featureData) {
return __awaiter(this, void 0, void 0, function* () {
const dbFeatureData = Object.assign(Object.assign({}, featureData), { description: featureData.description || '' });
return yield this.dbAdapter.createFeature(dbFeatureData);
});
}
/**
* Update feature information
* @param featureId - Feature identifier
* @param updateData - Data to update
* @returns Promise<any> - Updated feature object
*/
updateFeature(featureId, updateData) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.updateFeature(featureId, updateData);
});
}
/**
* Delete feature from the system
* @param featureId - Feature identifier
* @returns Promise<void>
*/
deleteFeature(featureId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.deleteFeature(featureId);
});
}
// =====================================
// PERMISSION MANAGEMENT METHODS
// =====================================
/**
* Get all permissions in the system
* @returns Promise with permissions array and total count
*/
getAllPermissions() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.getAllPermissions();
});
}
/**
* Find permission by name
* @param permissionName - Permission name
* @returns Promise<any | null> - Permission object or null if not found
*/
findPermissionByName(permissionName) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findPermissionByName(permissionName);
});
}
/**
* Find permission by ID
* @param permissionId - Permission identifier
* @returns Promise<any | null> - Permission object or null if not found
*/
findPermissionById(permissionId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.findPermissionById(permissionId);
});
}
/**
* Create a new permission
* @param permissionData - Permission data object
* @returns Promise<any> - Created permission object
*/
createPermission(permissionData) {
return __awaiter(this, void 0, void 0, function* () {
const dbPermissionData = Object.assign(Object.assign({}, permissionData), { description: permissionData.description || '' });
return yield this.dbAdapter.createPermission(dbPermissionData);
});
}
/**
* Update permission information
* @param permissionId - Permission identifier
* @param updateData - Data to update
* @returns Promise<any> - Updated permission object
*/
updatePermission(permissionId, updateData) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.updatePermission(permissionId, updateData);
});
}
/**
* Delete permission from the system
* @param permissionId - Permission identifier
* @returns Promise<void>
*/
deletePermission(permissionId) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.dbAdapter.deletePermission(permissionId);
});
}
// =====================================
// UTILITY METHODS
// =====================================
/**
* Get the underlying database adapter for advanced operations
* @returns DatabaseAdapter - The database adapter instance
*/
getDbAdapter() {
return this.dbAdapter;
}
/**
* Check if the admin service is properly configured and initialized
* @returns boolean - True if service is ready
*/
isReady() {
return !!(this.dbAdapter && this.adminCredentials);
}
};
exports.RbacAdminService = RbacAdminService;
exports.RbacAdminService = RbacAdminService = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)('RBAC_CONFIG')),
__param(1, (0, common_1.Inject)('RBAC_DB_ADAPTER')),
__param(2, (0, common_1.Inject)('RBAC_ADMIN_CONFIG')),
__metadata("design:paramtypes", [Object, DatabaseAdapter_1.DatabaseAdapter, Object])
], RbacAdminService);