Skip to content

UserToRolesModule

The UserToRoles module is a part of the application that manages the assignment of roles to users. It uses the UserToRole entity schema to store information about which users have specific roles and their associated organizations. The module enables administrators to grant roles to users, define the scope of roles within organizations, and set expiration dates for role assignments. This module plays a crucial role in access control and ensuring proper authorization for users within the application to them.

Entity Inheritance

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

Key Components

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

UserToRole Entity

The UserToRole entity represents the relationship between users and their assigned roles within the application. It contains essential information such as the user and role IDs, the organization where the role is granted, and the user who granted the role. Additionally, it stores the dates when the role was granted and when it expires, enabling precise control over the period of role assignments.

UserToRoles Service

The UserToRolesService is responsible for managing the assignment of roles to users within the application. It provides methods to create, update, and remove role assignments, as well as to fetch role assignments for a specific user or organization.

UserToRoles Resolver

The UserToRolesResolver is a GraphQL resolver responsible for handling queries and mutations related to user-to-role assignments in the application. It exposes the functionality of the UserToRolesService through the GraphQL API, enabling clients to request, assign, update, and remove role assignments for users.

How to install UserToRolesModule to my app

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

  1. Create a user-to-roles folder in your project's src/modules directory.

  2. Install the required dependencies for UserToRolesModule:

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

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

    ts
    // src/modules/user-to-roles/user-to-roles.service.ts
    
    import { InjectRepository } from '@nestjs/typeorm';
    import {
      InjectWinstonLoggerFactory,
      WinstonLoggerFactory,
    } from '@deeepvision/nest-kit';
    import { BaseUserToRolesService } from '@deeepvision/nest-kit/dist/modules/user-to-roles';
    import { IdService } from '@deeepvision/nest-kit/dist/modules/id';
    import { Repository } from 'typeorm';
    import { UserToRole } from './user-to-role.entity';
    
    export class UserToRolesService extends BaseUserToRolesService<UserToRole> {
      constructor(
        @InjectRepository(UserToRole) userToRoleRepository: Repository<UserToRole>,
      ) {
        super(
          userToRoleRepository,
        );
      }
    
      // protected generateEntityId() {
      //   return this.idService.generateEntityId('urol', 'hc');
      // }
    }
  5. Inside the user-to-roles folder, create a user-to-roles.resolver.ts file and extends BaseUserToRolesResolver with the following code:

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

    ts
    // src/modules/user-to-roles/user-to-roles.module.ts
    
    import { USER_TO_ROLES_SERVICE_TOKEN } from '@deeepvision/nest-kit/dist/modules/user-to-roles';
    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { UserToRole } from './user-to-role.entity';
    import { UserToRolesResolver } from './user-to-roles.resolver';
    import { UserToRolesService } from './user-to-roles.service';
    
    @Module({
      imports: [
        TypeOrmModule.forFeature([UserToRole]),
      ],
      providers: [
        UserToRolesService,
        {
          provide: USER_TO_ROLES_SERVICE_TOKEN,
          useExisting: UserToRolesService,
        },
        UserToRolesResolver,
      ],
      exports: [
        UserToRolesService,
        {
          provide: USER_TO_ROLES_SERVICE_TOKEN,
          useExisting: UserToRolesService,
        },
      ],
    })
    export class UserToRolesModule {}
  7. Finally, import the UserToRolesModule into your main AppModule or another module:

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

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

How to assign a role to a user in organization

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

ts
const userToRole = await this.userToRolesService.create({
  userId: 'hcu:2jg8592oknjw',
  roleId: 'hcrol:editor',
  organizationId: 'hcorg:ghk294ihlnb',
  grantedById: 'hcu:91485bgmvdk',
  expireAt: new Date('2023-12-31T23:59:59Z'),
});

In this example, the create method of the UserToRolesService is called with an object containing the necessary data to assign a role to a user. The role with ID hcrol:editor will be assigned to the user with ID hcu:2jg8592oknjw, within the organization with ID hcorg:ghk294ihlnb. The user with ID hcu:91485bgmvdk has granted the role, and the role assignment will expire at the end of December 31, 2023.

How to get user-to-role by ID

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

ts
const userToRole = await this.userToRolesService.getOne('hcurol:xxxxxxxxxxx');

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

ts
const userToRole = await this.userToRolesService.getOneOrFail('hcurol:xxxxxxxxxxx', ctx);

const role = await userToRole.role;
const user = await userToRole.user;
const organization = await userToRole.organization;

console.log(`User "${user.fullName}" was assigned to "${role.title}" role in "${organization.id}" organization.`)

How to get user roles list

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

ts
const [userToRoles, meta] = await this.userToRolesService.getMany({
  filter: {
    ...
  },
  orderBy: UserToRolesOrderBy.createdAt_ASC,
});

See UserToRolesFilter and UserToRolesOrderBy for more information on how to filter and order user roles.

Fetch user roles list with GraphQL

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

How to delete user-to-role

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

ts
await this.userToRolesService.delete('hcurol:xxxxxxxxxxx');

In this example, we are deleting an user-to-role with an id of hcurol:xxxxxxxxxxx.

Delete user-to-role with GraphQL

Here's an example GraphQL mutation to delete user-to-role

Created by DeepVision Software.