const errors = require('restify-errors'); const config = require('../config'); const handlePassportResponse = (req, res, next) => (err, passportUser, info) => { if (err) { return next(err); } const isVerifiedUser = passportUser.isRegistrationVerified(); if (passportUser && isVerifiedUser) { const user = passportUser; user.token = passportUser.generateJWT(); return res.send({ ...user.toAuthJSON() }); } else if (passportUser && !isVerifiedUser){ return res.send({ registrationSuccess: true, nextSteps: 'Check your email for our confirmation email, you will not be able to login without confirming.' }); } return res.send(400, info); }; module.exports = function (server, auth) { const { passport } = auth; /* Local Auth */ server.post('/auth', (req, res, next) => { const { body: { username = null, password = null } = {} } = req; if (!username || !password) { let errors = {}; if (!username) { errors.username = 'is required'; } if (!password) { errors.password = 'is required'; } return res.send(422, { errors }); } const callback = handlePassportResponse(req, res, next); return passport.authenticate('local', { session: false }, callback)(req, res, next); }); /** * SERVICES */ /* Google */ server.get( '/auth/google', passport.authenticate('google', { scope: 'profile email', session: false }), ); server.get( '/auth/google/callback', (req, res, next) => { const callback = handlePassportResponse(req, res, next); return passport.authenticate( 'google', { failureRedirect: '/login' }, callback, )(req, res, next); }, ); /* Facebook */ server.get( '/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile'], session: false, }), ); server.get( '/auth/facebook/callback', (req, res, next) => { const callback = handlePassportResponse(req, res, next); return passport.authenticate( 'facebook', { failureRedirect: '/login' }, callback, )(req, res, next); } ); };