const errors = require('restify-errors'); const config = require('../config'); const handlePassportResponse = (req, res, next) => (err, user, info) => { if (err) { return next(err); } const isVerifiedUser = user && user.isRegistrationVerified(); if (user && isVerifiedUser) { return res.send({ ...user.toAuthJSON() }); } else if (user && !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/login', passport.authenticate('facebook', { scope: ['email', 'public_profile'], session: false, }), ); server.get( '/auth/facebook/loggedin', (req, res, next) => { const callback = handlePassportResponse(req, res, next); return passport.authenticate( 'facebook', { failureRedirect: '/login' }, callback, )(req, res, next); } ); // server.get( // '/auth/facebook/link', // auth.secure, // (req, res, next) => { // req.user.record.setLinkCheckBit((err, linkCheckBit) => { // passport.authenticate('facebookLink', { // scope: ['email', 'public_profile'], // session: false, // state: linkCheckbit, // })(req, res, next); // }); // }, // ); // // server.get( // '/auth/facebook/linked', // (req, res, next) => { // const linkCheckBit = req.query.state; // // return passport.authenticate( // 'facebook', // { failureRedirect: '/profile' }, // (err, profile) => { // if (err) { // return next(err); // } // // User.linkFacebookProfile(linkCheckBit, profile, (err, user) => { // if (err) { // return next(err); // } // // if (!user) { // return next(err, false, 'Linking the account to Facebook was unsuccessful, please try again.'); // } // // res.send({ // success: true, // info: 'Facerbook account successfully linked', // }); // }); // }, // )(req, res, next); // } // ); };