Search code examples
reactjsnode.jsadminnest

How can I best implement the admin role in a Nest.js + React application?


I am writing a term project on the topic of a forum and want to separate the functionality for a regular user and an admin. My problem is that I don't know how to display a specific tab or link for accessing admin features after authorization, such as adding topics and so on..

I tried implementing role-based access control in my Nest.js + React application. I expected to be able to display a specific tab or link for accessing admin features after a user has been authenticated. However, I'm unsure of the best way to accomplish this within the application


Solution

  • There are many ways to skin this cat. I think we would require more information around how you tried implementing role-based access control in your nest.js application to give a more verbose answer.

    What are you sending to your react application from nest.js when a user has been authorised?

    If you are currently using Nest.js guards for authorization and RBAC, you could

    import { ExtractJwt, Strategy } from 'passport-jwt';
    import { PassportStrategy } from '@nestjs/passport';
    import { Injectable } from '@nestjs/common';
    
    @Injectable()
    export class JwtStrategy extends PassportStrategy(Strategy) {
      constructor() {
        super({
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          ignoreExpiration: false,
          secretOrKey: 'secrete',
        });
      }
    
      async validate(payload) {
        return {
          userId: payload.id,
          userName: payload.userName,
          role: payload.role,
        };
      }
    }
    

    which can then be imported into your app.module file

    import { JwtModule } from '@nestjs/jwt';
    import { JwtStrategy } from './auth/jwt.strategy';
    
    @Module({
      imports: [
        ...,
        JwtModule.register({ secret: 'secrete', signOptions: { expiresIn: '1h' } }),
      ],
      ...,
      providers: [..., JwtStrategy],
    })
    export class AppModule {}
    

    Now you will have access to the role context in your frontend application.

    Again this is just one of many ways to do this & I think without further information of what has been currently done, it would be hard to guide you in the right direction.