【问题标题】:how to protect user data from eachother using typegraphql-prisma如何使用 typegraphql-prisma 保护用户数据
【发布时间】:2022-01-08 14:14:23
【问题描述】:

我正在构建一个基于 typegraphql-prisma 的服务器,如下所示:https://github.com/prisma/prisma-examples/tree/latest/typescript/graphql-typegraphql-crud

我现在有一个服务器,可以在其中创建不同的用户,并且可以按照示例代码中的不同帖子。是否有指示或路径让每个用户都经过身份验证并且无法删除彼此的帖子?因为现在,我的消费客户端上的任何人都可以删除其他人的帖子。我在那里看到了一些 auth 的东西,但是我看不到在像“if (notOwner) {return null}”这样的删除突变期间在哪里添加代码当然有一种方法可以通过一些中间来在 autogen 解析器中验证这些类型的突变器皿什么的。

谢谢

【问题讨论】:

标签: node.js authentication graphql prisma typegraphql


【解决方案1】:

你可以使用Casl,它是一个授权库。您可以限制的不仅仅是所有者可以管理其资源。

【讨论】:

    【解决方案2】:

    MichalLytek 给了我以下对我有帮助的链接:

    https://typegraphql.com/docs/custom-decorators.html

    我在此处将该链接与 typegraphql-prisma 说明结合使用:

    https://prisma.typegraphql.com/docs/advanced/additional-decorators

    buildSchema 之前拨打applyResolversEnhanceMap(resolversEnhanceMap); 之类的电话就成功了。然后我将连接的PrismaClient 传递给装饰器函数,以检查 ORM 模型中的内容,例如我的“问题”模型:

    import { validate, ValidationError } from "class-validator";
    import {
      ClassType,
      ArgumentValidationError,
      createMethodDecorator,
    } from "type-graphql";
    import { PrismaClient } from "@prisma/client";
    
    // sample implementation of custom validation decorator
    // this example use `class-validator` however you can plug-in `joi` or any other lib
    export function ValidateDeleteIssueOwnership<T extends object>(
      Type: ClassType<T>,
      prisma: PrismaClient
    ) {
      return createMethodDecorator(async ({ args, context, info }, next) => {
        const instance = Object.assign(new Type(), args);
        console.log(" instance: ", instance);
    
        // console.log(' context: ', context);
        // console.log(' info: ', info);
    
        // const validationErrors = await validate(instance);
        // if (validationErrors.length > 0) {
        //   throw new ArgumentValidationError(validationErrors);
        // }
    
        const numberIssues = await prisma.issue.count();
        if (numberIssues === 0) {
          throw new Error(
            "CUSTOM DECORATOR - Oh Nos!!!  There were no issues to delete!  "
          );
        }
    
        return next();
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-10
      • 2021-01-20
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多