When I used REST api I used to place users on req.user but now I am doing my first graphql auth and i struggle to place the user on context object.
Here is what I am trying to accomplish but does not work:
- get admin ID from token and fetch admin from DB
- add fetched admin to the context object so that I can check admin permissions before each resolver
export const validateAccessToken = async (req) => {
try {
const accessToken = req.headers.authorization.slice(7);
if (!accessToken) throw new AuthenticationError('Unauthorized access');
const { id } = verify(accessToken, process.env.JWT_ACCESS_SECRET);
const admin = await Admin.findById(id);
return admin;
} catch {
return null;
}
};
// index.js
import { validateAccessToken } from './auth';
const server = new ApolloServer({
modules: [auth],
context: ({ req, res }) => ({ req, res, admin: validateAccessToken(req) }),
});
The value of admin in context is Promise { <pending> }