nestjs role based authorization

  • STEP1 : create @Role annotation using metadata (nestjs doc)
import { SetMetadata } from '@nestjs/common';
import { UserRole } from 'src/users/entities/user.entity';

export enum UserRole {
  Host = 'Host',
  Listener = 'Listener',
}

export type AllowedRoles = keyof typeof UserRole | 'Any';

export const Role = (roles: AllowedRoles[]) => SetMetadata('roles', roles);
  • STEP2 : AuthGuard determine continue process with checking Role
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext) {
    const roles = this.reflector.get('roles', context.getHandler());
    console.log('CanActivie roles: ', roles);
    if (!roles) {
      return true;
    }

    ........
    return roles.includes(user.role);
  }
  • STEP3 : add providers using APP_GUARD(global)
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './auth.guard';

@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
  ],
})
export class AuthModule {}
  • STEP4 : add AuthModule to AppModule
  • STEP5 : use @Role like this (@Role([‘Host’]) or @Role([‘Any’])….)
@Mutation(returns => EditProfileOutput)
  @Role(['Host'])
  editProfile(
    @AuthUser() authUser: User,
    @Args('input') editProfileInput: EditProfileInput,
  ): Promise<EditProfileOutput> {
    return this.usersService.editProfile(authUser.id, editProfileInput);
  }

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です