graphql-compose / graphql-compose/graphql-compose-mongoose

Authorization using wrapResolve

Open
#219 11 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
706
Forks
98
PR merge metrics
No merged PRs in 30d

Description

Hi,

first of all thanks to Pavel for implementing the issue I sent him via Twitter Direct.

What I want to acchieve is the ability to check for permissions before a query or mutation is executed. The user info is transmitted via JWT.

What I have done so far:
I've created the method requirePermissions which wraps the resolvers and to which the required permission(s) can be passed as string(s). For now it looks like this:
```javascript
function requirePermissions(resolvers: Record, ...permissions: Array): Record {
Object.keys(resolvers).forEach((k) => {
resolvers[k].wrapResolve((next) => async (rp) => {
// to be done
return next(rp);
});
});

return resolvers;
};
```

It is meant to be used in the following way:
```javascript
schemaComposer.Query.addFields({
...requirePermissions({
userById: UserTC.getResolver('findById'),
userByIds: UserTC.getResolver('findByIds'),
// ...
}, 'users:read'),
// ...
```
In this case users:read is the required permission string.

The Express request object is passed to the context field in the GraphQLHTTP Middleware:
```javascript
this.app.use(this.route + '/api', graphqlHTTP((req) => ({
schema: graphql,
graphiql: this.debug,
context: { req }
})));
```

Now, the following is left to do:

- Find the user document in MongoDB using username in req.body.username. (Authencity of the JWT is verified via separate middleware, so no need to worry about that.)
- Check if the user doc includes the required permission string.
- If so, allow the request.
- If not, block the request and return an error (e.g. Unauthorized) instead.

Hope someone can point me in the right direction :)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.