Last active
September 30, 2022 06:16
-
-
Save tchap/5643644 to your computer and use it in GitHub Desktop.
Set the path to return to after a successful authentication in Passport.js GitHub strategy (Express.js).
This file contains 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
/** | |
* Part 1: Set up the authentication endpoints. | |
*/ | |
// Point 1: Notice the checkReturnTo middleware, is defined at the bottom. | |
app.get('/auth/github', checkReturnTo, passport.authenticate('github', {state: 'Bublifuk'})); | |
// Point 2: Use 'successReturnToOrRedirect', otherwise the middleware will not work. | |
app.get('/auth/github/callback', | |
passport.authenticate('github', { successReturnToOrRedirect: '/', // IMPORTANT! | |
failureRedirect: '/error/account-not-found'})); | |
/** | |
* Part 2: The middleware to set up the parameters for Passport.js | |
*/ | |
var querystring = require('querystring'); | |
// The middleware to set up the parameters for the authenticate middleware. | |
function checkReturnTo(req, res, next) { | |
var returnTo = req.query['returnTo']; | |
if (returnTo) { | |
// Maybe unnecessary, but just to be sure. | |
req.session = req.session || {}; | |
// Set returnTo to the absolute path you want to be redirect to after the authentication succeeds. | |
req.session.returnTo = getFullUrl(querystring.unescape(returnTo)); | |
} | |
next(); | |
} | |
/** | |
* Part 3: Usage | |
*/ | |
// Restrict the important paths in your app using middleware. | |
// Just adding restrictTo('authenticated') will do the job. | |
function restrictTo(roles) { | |
if (roles === 'authenticated') return function (req, res, next) { | |
if (req.isAuthenticated()) return next(); | |
else res.redirect('/auth/github?returnTo=' + querystring.escape(req.url)); | |
}; | |
else return function(req, res, next) { | |
next(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment