@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
207 lines (206 loc) • 7.81 kB
JavaScript
;
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.RbacService = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("../core");
/**
* NestJS service that provides RBAC functionality.
* Wraps the main RBAC system methods for use in NestJS applications.
*
* @example
* ```typescript
* @Injectable()
* export class UserService {
* constructor(private rbacService: RbacService) {}
*
* async createUser(userData: CreateUserDto) {
* // Create user in your main database
* const user = await this.userRepository.create(userData);
*
* // Register user in RBAC system
* await this.rbacService.registerUser(user.id, {
* name: user.name,
* email: user.email
* });
*
* return user;
* }
*
* async assignRole(userId: string, roleName: string) {
* await this.rbacService.assignRole(userId, roleName);
* }
*
* async checkUserPermissions(userId: string, feature: string) {
* return await this.rbacService.getFeaturePermissions(userId, feature);
* }
* }
* ```
*/
let RbacService = class RbacService {
constructor(config, initialized) {
this.config = config;
this.initialized = initialized;
}
/**
* Manually register a user in the RBAC system.
* Useful for programmatic user registration outside of HTTP requests.
*
* @param user_id - Unique identifier for the user
* @param userData - User data object
* @returns Promise that resolves when user is registered
* @throws Error if user already exists or registration fails
*
* @example
* ```typescript
* await this.rbacService.registerUser('user123', {
* name: 'John Doe',
* email: 'john@example.com'
* });
* ```
*/
registerUser(user_id, userData) {
return __awaiter(this, void 0, void 0, function* () {
return yield core_1.CoreRBAC.registerUserManual(user_id, userData);
});
}
/**
* Update user information in the RBAC system.
*
* @param user_id - Unique identifier for the user
* @param userData - User data to update
* @returns Promise that resolves when user is updated
* @throws Error if user is not found
*
* @example
* ```typescript
* await this.rbacService.updateUser('user123', {
* name: 'John Smith',
* email: 'johnsmith@example.com'
* });
* ```
*/
updateUser(user_id, userData) {
return __awaiter(this, void 0, void 0, function* () {
return yield core_1.CoreRBAC.updateUser(user_id, userData);
});
}
/**
* Assign a role to a user in the RBAC system.
*
* @param user_id - Unique identifier for the user
* @param roleName - Name of the role to assign
* @returns Promise that resolves when role is assigned
* @throws Error if user or role is not found
*
* @example
* ```typescript
* await this.rbacService.assignRole('user123', 'admin');
* ```
*/
assignRole(user_id, roleName) {
return __awaiter(this, void 0, void 0, function* () {
return yield core_1.CoreRBAC.assignRole(user_id, roleName);
});
}
/**
* Get the role name assigned to a user.
*
* @param user_id - Unique identifier for the user
* @returns Promise that resolves to the role name or null if no role assigned
*
* @example
* ```typescript
* const role = await this.rbacService.getUserRole('user123');
* console.log(role); // 'admin' or null
* ```
*/
getUserRole(user_id) {
return __awaiter(this, void 0, void 0, function* () {
return yield core_1.CoreRBAC.getUserRole(user_id);
});
}
/**
* Get all permissions a user has for a specific feature.
*
* @param user_id - Unique identifier for the user
* @param featureName - Name of the feature to check permissions for
* @returns Promise that resolves to an array of permission names
*
* @example
* ```typescript
* const permissions = await this.rbacService.getFeaturePermissions('user123', 'billing');
* console.log(permissions); // ['read', 'create', 'update']
* ```
*/
getFeaturePermissions(user_id, featureName) {
return __awaiter(this, void 0, void 0, function* () {
return yield core_1.CoreRBAC.getFeaturePermissions(user_id, featureName);
});
}
/**
* Check if a user has a specific permission for a feature.
*
* @param user_id - Unique identifier for the user
* @param feature - Feature name
* @param permission - Permission name
* @returns Promise that resolves to boolean indicating if user has permission
*
* @example
* ```typescript
* const canDelete = await this.rbacService.hasPermission('user123', 'billing', 'delete');
* if (canDelete) {
* // User can delete billing records
* }
* ```
*/
hasPermission(user_id, feature, permission) {
return __awaiter(this, void 0, void 0, function* () {
const permissions = yield this.getFeaturePermissions(user_id, feature);
return permissions.includes(permission);
});
}
/**
* Get access to the underlying RBAC controllers for advanced operations.
*
* @returns Object containing controller instances
*
* @example
* ```typescript
* const { userRole, feature } = this.rbacService.getControllers();
* const allRoles = await userRole.getAllRoles();
* const allFeatures = await feature.getAllFeatures();
* ```
*/
getControllers() {
// Note: Controllers are Express-specific, not available in NestJS-only mode
throw new Error('Controllers are not available in NestJS-only mode. Use the service methods instead.');
}
};
exports.RbacService = RbacService;
exports.RbacService = RbacService = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)('RBAC_CONFIG')),
__param(1, (0, common_1.Inject)('RBAC_INITIALIZED')),
__metadata("design:paramtypes", [Object, Boolean])
], RbacService);