import { Injectable, Logger, OnApplicationBootstrap } from "@nestjs/common"; import { RbacRepository } from "./repositories/rbac.repository"; @Injectable() export class RbacService implements OnApplicationBootstrap { private readonly logger = new Logger(RbacService.name); constructor(private readonly rbacRepository: RbacRepository) {} async onApplicationBootstrap() { this.logger.log("RbacService initialized, checking roles..."); await this.seedRoles(); } async seedRoles() { try { const count = await this.rbacRepository.countRoles(); if (count === 0) { this.logger.log("No roles found, seeding default roles..."); const defaultRoles = [ { name: "Administrator", slug: "admin", description: "Full system access", }, { name: "Moderator", slug: "moderator", description: "Access to moderation tools", }, { name: "User", slug: "user", description: "Standard user access" }, ]; for (const role of defaultRoles) { await this.rbacRepository.createRole( role.name, role.slug, role.description, ); this.logger.log(`Created role: ${role.slug}`); } this.logger.log("Default roles seeded successfully."); } else { this.logger.log(`${count} roles already exist, skipping seeding.`); } } catch (error) { this.logger.error("Error during roles seeding:", error); } } async getUserRoles(userId: string) { return this.rbacRepository.findRolesByUserId(userId); } async getUserPermissions(userId: string) { return this.rbacRepository.findPermissionsByUserId(userId); } async countAdmins() { return this.rbacRepository.countAdmins(); } async assignRoleToUser(userId: string, roleSlug: string) { return this.rbacRepository.assignRole(userId, roleSlug); } }