4

I am working on a project using graphcool-yoga with prisma bindings. Want to set up authentication using passport's Local, Bearer, Github and Twitter strategy. Here's what my graphql query looks like

user: (root, args, context, info) => {
const { id } = args;
if(!passport.authenticate('bearer')(context)){
    throw new Error('Not Authorised');
}
if (!id) {
  throw new Error('Id cannot be empty');
}

return context.db.query.user(
  {
    where: {
      id: id,
      active: true,
    },
  },
  info,
);}

My auth.js where I have implement my passport strategy for bearer token:

import express from 'express';
import passport from 'passport';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import jwt from 'jsonwebtoken';

passport.use(new BearerStrategy((token, done) => {
    jwt.verify(token, process.env.JWT_SECRET, function(err, decoded) {
        if (err) return done(null, err);
        if (decoded.sub) {
            done(null, decoded.sub || undefined);
        }
    });
}));
const middleware = express();
middleware.use(passport.initialize());
middleware.use(passport.session());
module.exports = {
    authMiddleware: middleware
};

and finally I used it as a middleware:

const server = new GraphQLServer({
  typeDefs: 'app/schema.graphql', // application api schema
  resolvers,
  context: req => ({
    ...req,
    db
  }),
});
server.express.use(authMiddleware);

This is what I could write after reading various sources but is not working. Any correct and best way to do it?

Bharat Chhabra
  • 1,686
  • 2
  • 14
  • 20
  • what is the error message you receive? – Peter Jun 04 '18 at 20:43
  • No error message. it was just that I wasn't able to add authentication middleware to specific routes. – Bharat Chhabra Jun 05 '18 at 04:21
  • ok, were you able to solve the problem? If not, please fix this post to include ALL relevant code, i'd be happy to help since i'm working on something similar right now. – Peter Jun 05 '18 at 14:58

0 Answers0