Skip to content

How can i use passportJS strategy with ApolloServer #1057

Description

@eraycetinx

I'm using the PassportJS GitHub strategy and ApolloServer. I'm opening a separate '4001' port for PassportJS and another '4000' port for GraphQL endpoints. My question is: How can I use PassportJS operations with GraphQL endpoints? Can I use both on a single port, or should I run them on two separate ports? Are there any issues if I run both ports open?

import express from 'express';
import { prisma } from '@peerpush/db';
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { typeDefs } from './src/graphql/schema/typeDefs.js';
import { resolvers } from './src/graphql/resolvers/index.js';
import passport from 'passport';
import { Strategy as GitHubStrategy } from 'passport-github2';
import session from 'express-session';
import dotenv from 'dotenv';

(async function () {
  dotenv.config();
  const app = express();
  const server = new ApolloServer({
    typeDefs,
    resolvers,
  });
  app.use(session({
    secret: 'keyboard cat',
    resave: false, // don't save session if unmodified
    saveUninitialized: false, // don't create session until something stored
  }));

  app.use(passport.authenticate('session'));
  app.get('/auth/github',passport.authenticate('github'));

  passport.serializeUser(function(user, done) {
    done(null, user);
  });

  passport.deserializeUser(function(obj, done) {
    done(null, obj);
  });

  passport.use(new GitHubStrategy({
      clientID: process.env['clientID']!,
      clientSecret: process.env['clientSecret']!,
      callbackURL: "/oauth2/redirect/github"
    },
    function(accessToken, refreshToken, profile, done) {
      console.log({accessToken, refreshToken, profile});
    }
  ));

  app.get('/login/federated/github', passport.authenticate('github'));

  app.get('/oauth2/redirect/github', passport.authenticate('github', {
    successReturnToOrRedirect: '/',
    failureRedirect: '/login'
  }));

  const { url } = await startStandaloneServer(server, {
    listen: { port: 4000 },
  });
  console.log(`🚀 Server ready at: ${url}`);

  app.listen(4001,() => console.log('server'));

})().then(async () => {
  await prisma.$disconnect();
}).catch(async (e) => {
  console.error(e);
  await prisma.$disconnect();
  process.exit(1);
})

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions