Last active
May 27, 2017 19:29
-
-
Save pixelbacon/31df538286f4c1ab1c1c to your computer and use it in GitHub Desktop.
Simple Passport-Facebook, Passport-Twitter, Passport-Google redirect based on role
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express') | |
, router = express.Router() | |
, passport = require('passport'); | |
var loginUrl = '/#/auth/login' | |
, redirectUrl = '/auth/redirect/' | |
, loggedInUrl = '/#/account' | |
, logoutRedirect = '/'; | |
// Logout | |
router.get('/logout', function(req, res){ | |
req.logout(); | |
res.redirect(logoutRedirect); | |
}); | |
// Facebook /auth/facebook | |
router.get('/facebook', passport.authenticate('facebook', { scope : ['email', 'public_profile'] })); | |
router.get('/facebook/callback', passport.authenticate('facebook', { | |
successRedirect : redirectUrl, | |
failureRedirect : loginUrl | |
})); | |
// Twitter /auth/twitter | |
router.get('/twitter', passport.authenticate('twitter')); | |
router.get('/twitter/callback', passport.authenticate('twitter', { | |
successRedirect : redirectUrl, | |
failureRedirect : loginUrl | |
})); | |
// Google /auth/google | |
router.get('/google', passport.authenticate('google')); | |
router.get('/google/callback', passport.authenticate('google', { | |
successRedirect : redirectUrl, | |
failureRedirect : loginUrl | |
})); | |
// Where to send the user based on role | |
router.get('/redirect', passport.authenticate('session'), function(req, res, next){ | |
var url = loggedInUrl; | |
if(req.isAuthenticated()){ | |
switch(req.user.role){ | |
case 'admin':{ | |
url = '/#/admin/'; | |
break; | |
} | |
default: break; | |
} | |
res.redirect(url); | |
return; | |
} | |
res.redirect(loginUrl); | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment