How to check permissions and other conditions in GraphQL query?

Answer • 1 Asked • Mar 13 2019
How could I check if user has permission to see or query something? I have no idea how to do this.
  • In args? How would that even work?
  • In resolve()? See if user has permission and somehow eliminate/change some of the args?

Example:
If user is "visitor", he can only see public posts, "admin" can see everything.
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() } } } } })


Update - Mongoose model looks something like this:
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)

Write your answer...

On a mission to build Next-Gen Community Platform for Developers