Last active
December 19, 2015 07:28
-
-
Save vkareh/5918536 to your computer and use it in GitHub Desktop.
passport-drupal express middleware
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 passport = require('passport') | |
, express = require('express') | |
, app = express(); | |
// Passport session setup. | |
passport.serializeUser(function(user, done) { | |
done(null, user); | |
}); | |
passport.deserializeUser(function(user, done) { | |
done(null, user); | |
}); | |
var options = { | |
sessionKey: 'auth:drupal', | |
consumerKey: DRUPAL_CONSUMER_KEY, | |
consumerSecret: DRUPAL_CONSUMER_SECRET, | |
requestTokenURL: 'http://www.example.com/oauth/request_token', | |
accessTokenURL: 'http://www.example.com/oauth/access_token', | |
userAuthorizationURL: 'https://www.example.com/oauth/authorize', | |
resourceURL: 'http://www.example.com/oauthlogin/api/user/info', | |
callbackURL: 'http://www.example.net/auth/drupal/callback' | |
} | |
var verify = function(token, tokenSecret, profile, done) { | |
// Temporarily put the oauth details into the user object | |
// to allow us to get them into the session. | |
profile.oauth = { | |
token: token, | |
token_secret: tokenSecret | |
}; | |
return done(null, profile); | |
} | |
// Store the strategy instance in a separate variable, so we can access it easily. | |
var strategy = new (require('passport-drupal').Strategy)(options, verify); | |
// Mount the passport strategy. | |
passport.use(strategy); | |
// Give the request access to the strategy instance | |
// to allow re-use of the oauth instance to make requests. | |
app.use(function(req, res, next) { | |
req.passportStrategy = strategy; | |
next(); | |
}); | |
app.use(passport.initialize()); | |
app.use(passport.session()); | |
app.get('/auth/drupal', passport.authenticate(key, { | |
successRedirect: '/', | |
failureRedirect: '/error' | |
})); | |
app.get('/auth/drupal/logout', function(req, res) { | |
req.logout(); | |
// Remove user object from session as well | |
delete req.session.user; | |
res.redirect('/'); | |
}); | |
app.get('/auth/drupal/callback', passport.authenticate('drupal'), function(req, res) { | |
// Move the oauth credentials into the session proper, not the | |
// user record. This means we can push the user record to the | |
// client without leaking secrets. | |
req.session.oauth = req.user.oauth; | |
delete req.user.oauth; | |
// Depending on your application, you might also want to store | |
// the user object into the session for retrieval after the redirect | |
req.session.user = req.user; | |
// Successful authentication, redirect home. | |
res.redirect('/'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment