import { GraphQLError} from 'graphql' const jwt = require('jsonwebtoken'); require('dotenv').config(); export const VerifyToken = token => { try { if (token) { const verification = jwt.verify( token , 'RGlobal^') return verification; } return null } catch (err) { if(err.name === 'TokenExpiredError'){ return err; } return null } } export const AuthMiddleWare = ( cntx ) => { return ({ req }) => { //try to retrieve auth & getUser functions from extend let user; if ( true == true) { // get the user token from the headers const token = req.headers.authentication || ''; if(!req.headers.authentication) throw new GraphQLError('No authorization code provided'); if(req.headers.authentication === '') throw new GraphQLError('Invalid authorization code'); // try to retrieve a user with the token user = VerifyToken(token); // optionally block the user // we could also check user roles/permissions here if (!user) throw new GraphQLError('you must be logged in to query this schema'); if(user.error) throw new GraphQLError(user.message); if( user && user.identity ){ return { user: user.identity || null, ...cntx } } else{ throw new GraphQLError('no user identity'); } } else { return { user: user || null, ...cntx, } } } }