Created
February 7, 2019 16:40
-
-
Save jakangah/f5c569e539d57ae21d70786571af45a5 to your computer and use it in GitHub Desktop.
Implementing custom authorization when using express-graphql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We accomplish this by passing the req and res objects from the expressjs router to the context option | |
# After getting the specific role or permission from the query instance we can accomplish route validation | |
let graphQLSchema = { | |
...... | |
resolve: async function(root, args, context){ | |
context.role = 'ADMIN' | |
} | |
} | |
app.use('/public', graphqlHTTP((req, res) => ({ | |
schema: graphQLSchema, | |
graphiql: true, | |
pretty: true, | |
context: { req, res }, | |
extensions ({ document, variables, operationName, result, context }) { | |
# over here we use which ever validation method we prefer to validate the user request either through the header token or body | |
let userRole = validateUserByToken(req.headers['token']) | |
let routeRole = context.role; | |
if(userRole === routeRole){ | |
# continue as normal | |
return result | |
}else{ | |
# user not permitted so return an error message | |
return { | |
status : 401, | |
message : "Forbidden" | |
} | |
} | |
} | |
}))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment