【问题标题】:How do you omit fields in TypegraphQL如何在 TypegraphQL 中省略字段
【发布时间】:2022-10-18 05:28:58
【问题描述】:

假设我们有以下用户模型。 { id: ID, email: string, username: string }

然后我想定义2个查询:

  1. 所有者使用它来获取他们的设置页面,因此它包含敏感信息,例如电子邮件(可能是罪号)
  2. 被其他用户用来搜索用户(按用户名),我们这样做不是想暴露邮箱或sin号 我一直在研究文档,但找不到如何做到这一点。我正在考虑手动获取字段信息并根据查询解析它,但这似乎是一个疏忽。

    更新: 这是我正在尝试做的事情:

    class User {
      @Field(
        () => ID
      )
      id: string;
    
      @Authorized("CURRENT_USER")
      @Field(
        {
          nullable: true
        }
      )
      email: string;
    
      @Field()
      username: string;
    }
    

    解析器:

    export default class UserResolver {
      @Authorized("CURRENT_USER")
      @Query(
        () => User
      )
      async user(@Arg('username', () => String) username: string) {
         // TODO: if username is current user then allow email
         // else do not allow email, (I need auth checker in here)
      }
    }
    

【问题讨论】:

  • 我正在考虑制作2个模型? 1 用于公共,1 用于私人,但这似乎很奇怪。

标签: node.js typescript graphql typegraphql


【解决方案1】:

如果我正确理解您的问题,您应该能够在 TypegraphQL 中使用 Authorized 装饰器。使用此解决方案,您应该能够将其添加到用户模型中的电子邮件字段中。这也应该能够与 sid 字段一起使用

看看这里:https://typegraphql.com/docs/authorization.html

例如,您的 User 模型可能如下所示:

class User {
  @Field()
  id: ID;

  @Authorized("LOGGEDINUSER")
  @Field({nullable: true})
  email: string;

  @Field()
  username: string;
}

您必须允许电子邮件字段为空

您还需要定义一个 authChecker,通过它您可以运行您的逻辑来检查用户是否是数据的所有者,从而授予他们访问数据的权限。

authChecker 可能看起来像这样:

export const customAuthChecker: AuthChecker<Context> = (
  { args, context, info, root },
  roles
) => {
  // roles is an array of string which contains the authorization required to access the current resource
  // this is specified in the @Authorized decorator
  if (roles.includes("LOGGEDINUSER")) {
    // here check if the user is actually logged in and if they are allowed to access the resource
    // return true if they are allowed to access the resource
  }
  return false;
};

您还需要更改对 buildSchema 的调用以包含自定义 authChecker 和 authMode。 例如:

  const schema = await buildSchema({
    resolvers: [UserResolver],
    authChecker: customAuthChecker,
    authMode: "null",
  });

笔记这仍将返回一个电子邮件字段,但不会返回实际的电子邮件,而是在用户不满足身份验证要求时返回 null

【讨论】:

  • 惊人的!这种方法的一个问题是我们无法检查是否是所有者进行了查询。它说登录用户。有任何想法吗?
  • 好吧,您可以将其更改为所有者,然后在身份验证检查器中您可以访问上下文。例如,如果您使用快速会话,您将能够知道用户是谁,并将其与他们试图在根变量中接收的数据进行比较。
  • 另一种选择是不从数据库中选择电子邮件,并允许用户名字段在类型 graphql 模型中为空
  • 如果这些解决方案都不适合您,您可以向我发送/显示更多代码,因为我可能会提供进一步帮助
  • 当然,我可以尝试制作一个样本并在本周晚些时候发布。谢谢伊桑!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2020-05-04
  • 1970-01-01
  • 2014-07-08
  • 2013-02-22
  • 2020-12-12
相关资源
最近更新 更多