0

I'm implementing facebook-auth using https://www.npmjs.com/package/passport and https://www.npmjs.com/package/passport-facebook-token npm packages

this is my code in the passport config file:

passport.use(
  new FacebookTokenStrategy(
    {
      clientID: config.FACEBOOK_CLIENT_ID,
      clientSecret: config.FACEBOOK_CLIENT_SECRET,
      fbGraphVersion: 'v3.0',
    },
    (accessToken, refreshToken, profile, done) => {
      User.findOne(
        { 'facebookProvider.id': profile.id },
        (error: any, user: any) => {
          if (!user) {
            const newUser = new User({
              name: profile.displayName,
              email: profile.emails[0].value,
              facebookProvider: { id: profile.id, token: accessToken },
              imageProfile: profile.photos[0].value,
            });
            newUser.save((error, result) => {
              if (error) {
                return done(error);
              }
              return done(null, result);
            });
          }
          return done(error, user);
        }
      );
    }
  )
);

and below is my route handler:

const authRouter = express.Router();

authRouter
  .route('/facebook')
  .get(
    passport.authenticate('facebook-token'),
    async (req: Request, res: Response) => {
      if (req.user) {
        const accessToken: String = jwt.sign(
          { user: req.user },
          config.JWT_SECRET_KEY,
          {
            expiresIn: config.TOKEN_LIFE_TIME,
          }
        );
        return sendSuccesResponse(res, 200, accessToken);
      }
      return sendErrorResponse(res, 400, 'Something went wrong');
    }
  );

export default authRouter;

also, I initialized the passport in the index.ts file which is the entry point of API and imported the passport config file:

import './config/passport';
.
.
.
app.use(passport.initialize());
app.use('/api/v1/oauth2', authRouter);

Moreover, I got the token from Facebook and when I request my API with the provided token, Facebook can authenticate and return the user profile but after authentication and creating a new user or if the user already exists in DB, then it does not go to the route handler where I want to generate JWT token for the user and return to the user.

I got the following error in postman: 500 internal server error

H_POYA
  • 1
  • 3

1 Answers1

0

After a lot of struggling, I found that I must provide a second parameter { session: false } for passport.authenticate function.

The below code is working just fine:

passport.authenticate('facebook-token', { session: false })
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
H_POYA
  • 1
  • 3