How to get User Access Control in NestJs Guard for authorizations?

1k Views Asked by At

I am new in @Nestjs. I am using graphql in @Nestjs. I have a question in this field. How can I access UserSchema or UserModel from AuthGuard.ts?

Here in AuthGuard.ts I am checking request context headers is and verify jwt token-

import { Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus } from "@nestjs/common"; import { GqlExecutionContext } from "@nestjs/graphql"; import * as jwt from "jsonwebtoken";

@Injectable()
export class AuthGaurd implements CanActivate {

    async canActivate(context: ExecutionContext) {
        const ctx = GqlExecutionContext.create(context).getContext();
        if (!ctx.headers.authorization) {
            return false;
        }
        ctx.user = await this.validateToken(ctx.headers.authorization);
        console.log(ctx.user.info);
        return true;
    }

    validateToken(auth: string) {
        if (auth.split(' ')[0] !== 'Bearer') {
            throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
        }
        const token = auth.split(' ')[1];
        try {
            return jwt.verify(token, process.env.JWT_SECRET_KEY)
        } catch (err) {
            throw new HttpException("Invalid token", HttpStatus.UNAUTHORIZED)
        }
    }
}

Here We find Email as Info from jwt token. Now I have to check this email is still registered, or this user role is user, creator and admin?

I call this AuthGuard in my resolver-

import { Resolver, Mutation, Query, Args, Context } from "@nestjs/graphql";
import { UseGuards } from "@nestjs/common";

//Service
import { QuestionService } from "./question.service";
//Guardss
import { AuthGaurd } from "src/helpers/auth.guard";
//Entity
import { CreateQuestionEntity } from "./entities/create-question.entity";
//Dto
import { CreateQuestionInput } from "./dto/create-question.input";

@Resolver()
export class QuestionResolver {
    //Constructor
    constructor(private readonly questionService: QuestionService) { }

    //Create Question Resolver
    @Mutation(() => CreateQuestionEntity, { name: "addQuestion" })
    @UseGuards(new AuthGaurd()) // Here I call AuthGuard
    createQuestion(
        @Args('createQuestionInput')
        createQuestionInput: CreateQuestionInput
    ) {
        return this.questionService.create(createQuestionInput)
    }
}

Again, my question is- This Authguard.ts only check if user sent request context header and verify jwt token. After verifying jwt token I get email from this jwt token. After getting the email, I have to create 3 new Guards. One for checking this user still has in my database, second is if this user is creator, third is if this user is admin. And then I have to check when and which one I need. If I need a creator, then I have to call the creator guard. Or if I need admin then I have to call admin guard.

I think I can clear my question? Please help me, How can I do that in my project?

enter image description here

This is my folder structure-

in user folder I handle user creation, login, getting user-info in question folder I handle question creation, updating and getting

in question folder I need to check user is Authorized or Creator or Admin.

That's why I create one new folder named helper.

in this helper I create AuthGuard.ts file here I need to create 2 more file for CreatorGuard and AdminGuard. and I have to check the roles.

Here is my repo- https://github.com/siamahnaf198/nest-graphql

Please give me the full instructions and examples.

0

There are 0 best solutions below