gpt4 book ai didi

node.js - 如何在 GraphQL 查询中检查权限和其他条件?

转载 作者:IT老高 更新时间:2023-10-28 23:14:33 24 4
gpt4 key购买 nike

我如何检查用户是否有权查看查询某些东西?我不知道该怎么做。

  • args 中?这怎么行?
  • resolve() 中?查看用户是否有权限并以某种方式消除/更改一些参数?

示例:

如果用户是“访问者”,他只能看到公开的帖子,“管理员”可以看到一切。

const userRole = 'admin';  // Let's say this could be "admin" or "visitor"

const Query = new GraphQLObjectType({
name: 'Query',
fields: () => {
return {
posts: {
type: new GraphQLList(Post),
args: {
id: {
type: GraphQLString
},
title: {
type: GraphQLString
},
content: {
type: GraphQLString
},
status: {
type: GraphQLInt // 0 means "private", 1 means "public"
},
},

// MongoDB / Mongoose magic happens here
resolve(root, args) {
return PostModel.find(args).exec()
}
}
}
}
})

更新 - Mongoose 模型看起来像这样:

import mongoose from 'mongoose'

const postSchema = new mongoose.Schema({
title: {
type: String
},
content: {
type: String
},
author: {
type: mongoose.Schema.Types.ObjectId, // From user model/collection
ref: 'User'
},
date: {
type: Date,
default: Date.now
},
status: {
type: Number,
default: 0 // 0 -> "private", 1 -> "public"
},
})

export default mongoose.model('Post', postSchema)

最佳答案

您可以在解析函数或模型层中检查用户的权限。以下是您必须采取的步骤:

  1. 在执行查询之前对用户进行身份验证。这取决于您的服务器,通常发生在 graphql 之外,例如通过查看与请求一起发送的 cookie。见 this Medium post有关如何使用 Passport.js 执行此操作的更多详细信息。
  2. 将经过身份验证的用户对象或用户 ID 添加到上下文中。在 express-graphql 中,您可以通过 context 参数来实现:

    app.use('/graphql', (req, res) => {
    graphqlHTTP({ schema: Schema, context: { user: req.user } })(req, res);
    }
  3. 像这样在 resolve 函数中使用上下文:

    resolve(parent, args, context){
    if(!context.user.isAdmin){
    args.isPublic = true;
    }
    return PostModel.find(args).exec();
    }

您可以直接在解析函数中进行授权检查,但如果您有模型层,我强烈建议通过将用户对象传递给模型层来实现它。这样,您的代码将更加模块化,更易于重用,而且您不必担心在某处忘记解析器中的某些检查。

有关授权的更多背景信息,请查看这篇文章(也是我自己写的): Auth in GraphQL - part 2

关于node.js - 如何在 GraphQL 查询中检查权限和其他条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37356362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com