mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-26 02:07:55 +00:00
Add permission and role management features
This commit is contained in:
@@ -0,0 +1 @@
|
||||
export * from './permission.service';
|
||||
@@ -0,0 +1,52 @@
|
||||
import { PermissionMapping } from '@app/common/constants/permissions-mapping';
|
||||
import { RolePermissions } from '@app/common/constants/role-permissions';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
import { RoleTypeRepository } from '@app/common/modules/role-type/repositories';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionService {
|
||||
constructor(private readonly roleTypeRepository: RoleTypeRepository) {}
|
||||
|
||||
async getPermissionsByRole(roleUuid: string) {
|
||||
try {
|
||||
const role = await this.roleTypeRepository.findOne({
|
||||
where: {
|
||||
uuid: roleUuid,
|
||||
},
|
||||
});
|
||||
|
||||
if (!role) {
|
||||
throw new HttpException('Role not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
const permissions = this.mapPermissions(role.type.toString() as RoleType);
|
||||
return permissions;
|
||||
} catch (err) {
|
||||
throw new HttpException(
|
||||
err.message || 'Internal Server Error',
|
||||
err.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
mapPermissions(role: RoleType): any[] {
|
||||
const rolePermissions = RolePermissions[role]; // Permissions for the role
|
||||
|
||||
const mappedPermissions = Object.entries(PermissionMapping).map(
|
||||
([title, subOptions]) => ({
|
||||
title,
|
||||
subOptions: Object.entries(subOptions).map(
|
||||
([subTitle, permissions]) => ({
|
||||
title: subTitle,
|
||||
subOptions: permissions.map((permission) => ({
|
||||
title: permission,
|
||||
isChecked: rolePermissions.includes(`${subTitle}_${permission}`), // Check if the role has the permission
|
||||
})),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
return mappedPermissions;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user