如何在Nestjs Guard中获得用户访问控制?

发布于 2025-01-30 18:00:23 字数 3205 浏览 3 评论 0原文

我是@nestjs的新手。我在@nestjs中使用GraphQl。我在这个领域有一个问题。如何访问userChemausermodel来自authguard.ts

authguard.ts中,我正在检查请求上下文标头 is is and verify jwt token-

import {indectable,canactivate,canactivate,executionContext,httppexception,httpstatus}}来自“@nestjs/common”; 从“@nestjs/graphql” import {gqlexecutionContext}; 从“ jsonwebtoken”中导入 *作为JWT;

@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)
        }
    }
}

在这里,我们从JWT令牌找到电子邮件为。现在,我必须检查此电子邮件仍在注册中,还是此用户角色是用户,创建者和管理员?

我在解析器中调用此authguard-

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)
    }
}

再次,我的问题是 - 此authguard.ts仅检查用户是否已发送请求上下文标头验证jwt token。验证JWT令牌后,我会从此jwt令牌中获取电子邮件。收到电子邮件后,我必须创建3个新警卫。一个用于检查此用户在我的数据库中仍然存在的一个,其次是如果此用户是创建者,则第三是如果此用户是管理员。然后我必须检查我需要的何时以及哪个。如果我需要一个创作者,那么我必须打电话给造物主守卫。或者,如果我需要管理员,则必须致电管理员。

我想我可以清除我的问题吗?请帮助我,我该如何在项目中做到这一点?

这是我的文件夹结构 -

用户文件夹中我处理用户创建,登录,获取用户info 在问题文件夹中,我处理问题创建,更新和获取

问题文件夹我需要检查用户已授权或创建者或管理员。

这就是为什么我创建一个名为Helper的新文件夹的原因。

在此助手中,我创建authguard.ts文件 在这里,我需要为creatorGuardadminguard创建2个文件。我必须检查角色。

这是我的repo- https://github.com/siamahnaf198/nest-graphql

请给我的完整说明和示例。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文