DEV Community

Discussion on: Using GraphQL schema directives for role based authorization

Collapse
 
tushark1 profile image
Tushar Khubani • Edited

In the auth controller I have the logic for authenticating, example validating credentials, if credentials match, return a token, get the auth user (decode jwt token) etc.
How I set the user context is as follows

import { getMe } from "../controllers/authController";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  schemaDirectives,
  context: async ({ req }) => {
    const me = await getMe(req);
    return { me };
  }
});

and the getMe logic in auth controller is as following:

export const getMe = async req => {
  const token = req.headers["x-access-token"];
  if (token) {
    try {
      return await jwt.verify(token, JWT_SECRET);
    } catch (error) {
      throw new AuthenticationError("Session expired, please login!", error);
    }
  }
};

jwt.verify() returns the payload if the jwt token is valid and not expired.

Collapse
 
michelemassari profile image
Michele Massari

Amazing, thanks so much for clarifying that