kogosoftwarellc / open-api

A Monorepo of various packages to power OpenAPI in node
MIT License
892 stars 235 forks source link

passport.js integration question #800

Closed baophamtd closed 2 years ago

baophamtd commented 2 years ago

Has anyone integrated passport with social media platform auth before? I'm struggling to set this up and can't find any example that uses the same combination (express-openapi and passport). Here is my app.js (I should hide the passport setup in config but bringing it out here for better visibility):

import express from 'express';
import { initialize } from 'express-openapi';
import swaggerUi from 'swagger-ui-express';
import path from 'path';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import cors from 'cors';
import bodyParser from 'body-parser';
import passport from 'passport';
import passportFacebook from 'passport-facebook';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const FacebookStrategy = passportFacebook.Strategy;

const app = express();
app.use(cors());
app.use(bodyParser.json());

//passport setup
app.use(passport.initialize());
app.use(passport.session());
passport.use(new FacebookStrategy({
  clientID: "<ID>",
  clientSecret: "<Secret>",
  callbackURL: "http://localhost:3000/v1/auth/facebook/callback"
},
  function (accessToken, refreshToken, profile, done) {
       return done(null, profile);
  }
));

//express-openapi setup
initialize({
  app,
  apiDoc: fs.readFileSync(path.resolve(__dirname, './api/api-doc.yml'), 'utf8'),
  paths: path.resolve(__dirname, './api/v1/routes'),
  routesGlob: '**/*.{cjs,js}',
  routesIndexFileRegExp: /(?:index)?\.cjs$/,
});

app.use(
  "/api-documentation",
  swaggerUi.serve,
  swaggerUi.setup(null, {
    swaggerOptions: {
      url: "http://localhost:3000/v1/api-docs",
    },
  })
);

app.listen(3000);

Here is my ./api/v1/routes/auth/{provider.js} using xpress-openapito handle the routes:

const authService = require('../../services/authService');
const passport = require('passport');

module.exports = {
    get: [
        function (req, res, next) {
            console.log('facebook')
            passport.authenticate('facebook', {
                scope: ['public_profile', 'email']
            })
            next()
        },
        get,
    ],
};

function get(req, res) {}

The GET endpoint is fired every time I call it, but the browser just hangs. Any help would be greatly appreciated!

baophamtd commented 2 years ago

I figured it out :( passport.authentication() returns a function, so I have to call it as

passport.authenticate('facebook', {
        scope: ['public_profile', 'email']
    })(req, res, next)