From graphql yoga, inside of my resolvers I check before resolver call, if this resolver is protected or not.
If resolver is protected, and user is not signed in I can throw an error like this:
return new Error('Token is missing');
This stops execution of the request and returns correct shape of message, with an error field.
{
"data": null,
"errors": [
{
"message": "Token is missing",
"locations": [
{
"line": 3,
"column": 3
}
],
"path": [
"users"
]
}
]
}
The response has status 200 though, which is not correct. I'd like to be able to choose my own status, like 403 for example.
Here is my current implementation of resolvers:
const withAuth = authed => (_, args, context, ...rest) => {
if (!context.token) {
return new Error('Token is missing');
}
let result = null;
try {
result = jwt.verify(context.token, process.env.HASH);
} catch (__) {
return new Error('Incorrect token');
}
const { username, email } = result;
if (!username || !email) {
return new Error('Incorrect token');
}
return authed(_, args, { ...context, user: { username, email } }, ...rest);
};
const resolvers = {
Query: {
users: withAuth(resolver(User)), //get users from db
}
I would add a before request middleware in express, but there is no way of telling, which query is being called, as all calls are done to the same endpoint.
Any input will be appreciated!