首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在TypegraphQL中省略字段

如何在TypegraphQL中省略字段
EN

Stack Overflow用户
提问于 2022-09-24 21:33:44
回答 1查看 77关注 0票数 0

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

然后,我想定义两个查询:

  1. 被所有者用来获取他们的设置页面,因此它包含敏感信息,比如电子邮件(可能是sin号)、
  2. ,其他用户用来搜索用户(使用用户名)&我们做,而不是,希望公开我一直在研究的文档中的电子邮件或sin编号&无法找到如何完成这一任务。我正在考虑手动获取字段的信息&对每个查询进行解析,但这似乎是一个疏忽。

更新:以下是我想要做的事情:

代码语言:javascript
复制
class User {
  @Field(
    () => ID
  )
  id: string;

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

  @Field()
  username: string;
}

Resolver:

代码语言:javascript
复制
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)
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-26 01:24:39

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

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

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

代码语言:javascript
复制
class User {
  @Field()
  id: ID;

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

  @Field()
  username: string;
}

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

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

authChecker可以如下所示:

代码语言:javascript
复制
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。例如:

代码语言:javascript
复制
  const schema = await buildSchema({
    resolvers: [UserResolver],
    authChecker: customAuthChecker,
    authMode: "null",
  });

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73840722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档