Skip to content

RolesModule

The RolesModule is a part of the Roles API that enables management of roles and their associated permissions within an application. This module provides the necessary functionality to create, update, and delete roles, as well as assign specific permissions and permission groups to them.

Here's a list of the available role types:

  1. System: These are built-in roles that cannot be deleted. They are predefined by the application and grant specific permissions for essential tasks.
  2. Organization: These are custom roles created by organization admins to tailor access and permissions within their organization.
  3. Brand: These roles are used for brand assignments and provide access to brand-specific data and management functions.
  4. Studio: Studio roles are assigned to users working within a studio environment, granting them access to studio-related data and tools.
  5. Passport Type: These roles are used for passport type assignments and provide access to passport type-specific data and management functions.
  6. Review: Review roles are designated for users who manage and oversee review processes, granting them the necessary permissions to perform their tasks effectively.

What System Roles are included Out-of-the-Box in NestKit

System roles are predefined roles that come built-in with an application or platform like NestKit. They provide a set of standard permissions and access levels for different types of users, allowing for easier management of user privileges. These roles are typically designed to cover common use cases and cannot be deleted, ensuring consistent access control across the system.

Superadmin

The Superadmin role is a unique system role that grants users assigned to it the highest level of access and control within an application.

With a permission set of ["*:*:*:*"], a Superadmin has unrestricted access to all projects, modules, resources, and actions across all organizations.

This role is ideal for users responsible for overall system administration and management, allowing them to oversee and manage all aspects of the application without any limitations.

Organization Admin

The Organization Admin role is a specialized system role designed for users who are responsible for managing resources and operations within a specific organization.

Users assigned to this role have administrative access to resources and actions exclusively within their assigned organization.

This allows Organization Admins to effectively manage and maintain their organization's resources, users, and processes,while ensuring that their access is limited to the scope of their own organization.

Organization Observer

The Organization Observer is a system role tailored for users who need read-only access to resources and information within their assigned organization.

This role enables users to view and monitor the organization's resources, processes, and activities without the ability to modify or manage them.

The Organization Observer role is particularly useful for users who require insight into the organization's operations but should not have the authority to make changes or perform administrative actions.

User

The User role is a general-purpose role designed for users who interact with the application within the scope of their assigned organization or project.

This role grants basic access and permissions to various resources, allowing users to perform routine tasks and contribute to the organization's activities.

The User role typically includes permissions tailored to the user's specific job function, ensuring they can effectively collaborate and work on assigned tasks without unnecessary privileges.

How to manage role permissions?

To manage permissions, we use the @deeepvision/auth library, which offers comprehensive documentation on the permissions format and access check strategy. You can refer to the library's documentation to learn more about how to define and implement permissions

Key Components

The module provides a set of reusable components that can be easily integrated into a NestJS project:

Role Entity

The Role entity represents a set of permissions and access levels within an application. Each role is characterized by its type, title, status, description, and associated permissions. Roles can be system-defined, organization-specific, or tailored for different entities like brands, studios, or passport types. They enable fine-grained control over user access and actions, ensuring that users only have the necessary permissions to perform their tasks.

Roles Service

The RolesService is a core component of the Roles API, responsible for handling the business logic and operations related to roles and their permissions within an application. It offers a set of methods to create, update, delete, and fetch roles, as well as to manage their associated permissions and permission groups.

Roles Resolver

The RolesResolver is a key part of the Roles API that handles incoming GraphQL queries and mutations related to roles and their permissions. It acts as an intermediary between the client and the RolesService, receiving requests, processing them, and returning the appropriate responses. Through the RolesResolver, developers can easily expose role management functionalities to the client, ensuring a flexible and intuitive interface for managing roles, permissions, and user access within an application.

Entity Inheritance

NestKit provide base classes that can be inherited and customized with your needs. For entities we use TypeORM TableInheritance.

How to install RolesModule to my app

To create a RolesModule in NestJS, you can follow these steps:

  1. Install the required dependencies for RolesModule:

  2. Create a roles folder in your project's src/modules directory.

  3. Inside the roles folder, create a role.entity.ts file and extends BaseRole from NestKit with the following code:

    ts
    // src/modules/roles/role.entity.ts
    
    import { Field, ObjectType } from '@nestjs/graphql';
    import { MaybeNull } from '@deeepvision/nest-kit';
    import { BaseRole } from '@deeepvision/nest-kit/dist/modules/roles/role.entity';
    import { ChildEntity } from 'typeorm';
    
    import { Organization } from '../organizations/organization.entity';
    import { UserToRole } from '../user-to-roles/user-to-role.entity';
    
    @ObjectType()
    @ChildEntity()
    export class Role extends BaseRole {
      @Field(() => Organization, {
        nullable: true,
      })
      organization!: Promise<MaybeNull<Organization>>;
    
      userToRoles!: Promise<UserToRole[]>;
    }
  4. Inside the roles folder, create a roles.service.ts file and extends BaseRolesService from NestKit with the following code:

    ts
    // src/modules/roles/roles.service.ts
    
    import { Role } from './role.entity';
    import { BaseRolesService, SystemRole } from '@deeepvision/nest-kit/dist/modules/roles';
    
    export class RolesService extends BaseRolesService<Role> {
      constructor(
      ) {
        super(
          SystemRole.SUPERADMIN,
          SystemRole.ORGANIZATION_ADMIN,
        );
      }
    }
    }
  5. Inside the roles folder, create a roles.resolver.ts file and extends BaseRolesResolver with the following code:

    ts
    // src/modules/roles/roles.resolver.ts
    
    import { BaseRolesResolver } from '@deeepvision/nest-kit/dist/modules/roles';
    import { Resolver } from '@nestjs/graphql';
    import { Role } from './role.entity';
    
    @Resolver(() => Role)
    export class RolesResolver extends BaseRolesResolver(Role) {}
  6. Inside the roles folder, create a roles.module.ts file with the following code:

    ts
    // src/modules/roles/roles.module.ts
    
    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { Role } from './role.entity';
    import { RolesService } from './roles.service';
    import { RolesResolver } from './roles.resolver';
    import { OrganizationsModule } from '../organizations/organizations.module';
    import { ROLES_SERVICE_TOKEN } from '@deeepvision/nest-kit/dist/modules/roles';
    
    @Module({
      imports: [
        TypeOrmModule.forFeature([Role]),
        OrganizationsModule,
      ],
      providers: [
        RolesService,
        {
          provide: ROLES_SERVICE_TOKEN,
          useExisting: RolesService,
        },
        RolesResolver,
      ],
      exports: [
        RolesService,
        {
          provide: ROLES_SERVICE_TOKEN,
          useExisting: RolesService,
        },
      ],
    })
    export class RolesModule {}
  7. Finally, import the RolesModule into your main AppModule or another module:

    ts
    // src/modules/app.module.ts
    
    import { Module } from '@nestjs/common';
    import { RolesModule } from './modules/roles/roles.module.ts';
    
    @Module({
      imports: [RolesModule],
    })
    export class AppModule {}

    In this code, we are importing the RolesModule and adding it to the imports array of our AppModule.

How to create new organization role

Here's an example of how to call RolesService.create with an object literal based on CreateRoleOptions:

ts
const newRole = await this.rolesService.create({
  title: 'Editor',
  description: 'The "Editor" role is a user role within an application, granting users assigned to this role the ability to create, modify, and manage content.',
  type: RoleType.ORGANIZATION,
  organizationId: 'hcrol:xxxxxxxxxxx',
  permissions: [
    'exp:core:insights:list',
    'exp:core:insights:create',
    'exp:core:insights:update',
    'exp:core:insights:delete',
    ...
  ],
});

Create new organization role with GraphQL

Here's an example GraphQL mutation to create a new organization role.

How to create new organization role with permission groups

Here's an example of how to call this.rolesService.create with permissionGroups:

ts
const newRole = await this.rolesService.create({
  id: 'someUniqueId',
  title: 'Content Manager',
  description: 'The "Content Manager" role is responsible for managing various types of content within the application',
  type: RoleType.ORGANIZATION,
  organizationId: 'hcrol:xxxxxxxxxxx',
  permissionGroups: ['g:exp:core:users:view', 'g:exp:core:insights:edit'],
});

In this example, the new role "Content Manager" is created with two permission groups - g:exp:core:users:view and g:exp:core:insights:edit. These groups contain related permissions, and by using the group identifiers, the role automatically inherits all the permissions from both groups.

How to get role by ID

Use the getOne() method from your RolesService to get a role by id in other parts of your application.

ts
const role = await this.rolesService.getOne('hcrol:xxxxxxxxxxx');

Use the getOneOrFail() method to retrieve a role by id or throw an error if the role is not found.

ts
const role = await this.rolesService.getOneOrFail('hcrol:xxxxxxxxxxx', ctx);

Fetch role by id with GraphQL

Here's an example GraphQL query to fetch role by id.

How to get roles list

Use the getMany() method in other parts of your application to retrieve a list of roles.

ts
const [roles, meta] = await this.rolesService.getMany({
  filter: {
    ...
  },
  orderBy: RolesOrderBy.title_ASC,
});

See RolesFilter and RolesOrderBy for more information on how to filter and order roles.

Fetch roles list with GraphQL

Here's an example GraphQL query to fetch roles.

How to get roles list of roles that can be assigned to other users

This getAvailableRoles is responsible for fetching a list of roles that can be assigned to other users by the calling user.

Based on the calling user's permissions, this method returns a filtered list of roles that they are authorized to assign.

This ensures that users can only assign roles within their allowed scope, maintaining the integrity and security of the application.

ts
const [roles, meta] = await this.rolesService.getAvailableRoles({
  filter: {
    ...
  },
  orderBy: RolesOrderBy.title_ASC,
}, ctx);

See AvailableRolesFilter and AvailableRolesOrderBy for more information on how to filter and order available roles.

Fetch available role list with GraphQL

Here's an example GraphQL query to fetch available roles.

How to update role

Here's an example of calling the RolesService.update method with an UpdateRoleOptions object:

ts
const updatedOrg = await this.rolesService.update({
  id: 'hcrol:xxxxxxxxxx',
  title: 'Updated Editor',
  description: 'The "Updated Editor" role allows users to create, modify, and manage content with some additional capabilities.',
  permissions: [
    'bo:core:users:list',
    'bo:core:users:get',
    'bo:core:roles:list',
    'bo:core:roles:get',
  ],
  permissionGroups: [
    'g:bo:core:content:manage',
    'g:bo:core:media:upload',
  ],
});

All fields in the upate input are optional except for the id field.

The update method returns a Promise that resolves to the updated role object.

Update role with GraphQL

Here's an example GraphQL mutation to update role.

How to delete role

Call the delete method of the RolesService and pass in the id of the role you want to delete:

ts
await this.rolesService.delete('hcrol:xxxxxxxxxxx');

In this example, we are deleting an role with an id of hcrol:xxxxxxxxxxx.

Delete role with GraphQL

Here's an example GraphQL mutation to delete role.

RolesService uses Soft-Delete feature

Soft delete is a feature in NestKit that allows you to mark a record as "deleted" instead of physically deleting it from the database. When you use soft delete, the record is not actually removed from the database, but a status sets to DELETED to indicate that the record has been "soft-deleted". This allows you to retain the data and history associated with the record, while still hiding it from normal queries.

Created by DeepVision Software.