假设我们有以下用户模型。{ id: ID, email: string, username: string }
然后,我想定义两个查询:
更新:以下是我想要做的事情:
class User {
@Field(
() => ID
)
id: string;
@Authorized("CURRENT_USER")
@Field(
{
nullable: true
}
)
email: string;
@Field()
username: string;
}Resolver:
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)
}
}发布于 2022-09-26 01:24:39
如果我正确理解您的问题,您应该能够在TypegraphQL中使用授权的装饰器。使用此解决方案,您应该能够将其添加到用户模型中的电子邮件字段中。这也应该能够与sid字段一起工作。
在这里看一下: https://typegraphql.com/docs/authorization.html
例如,您的用户模型可能如下所示:
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,而不是返回实际的电子邮件。
https://stackoverflow.com/questions/73840722
复制相似问题