Created
June 20, 2013 17:50
-
-
Save jkresner/5824963 to your computer and use it in GitHub Desktop.
Passport.js user mocking version 2
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
users = require './../data/users' | |
data = users: [] | |
data.users.anon = authenticated: false | |
data.users.admin = users[0] | |
data.users.jk = users[1] | |
data.users.artle = users[5] | |
data.users.beountain = users[4] | |
setSession = (userKey) -> | |
if data.users[userKey]? | |
global.session = data.users[userKey] | |
else | |
global.session = data.users.admin | |
module.exports = | |
setSession: setSession | |
initialize: (app) -> | |
# default to admin | |
global.session = data.users.admin | |
(req, res, next) -> | |
passport = @ | |
passport._key = 'passport' | |
passport._userProperty = 'user' | |
passport.serializeUser = (user, done) -> done null, user | |
passport.deserializeUser = (user, done) -> done null, global.session | |
req._passport = instance: passport | |
req._passport.session = user: session | |
# allow us to change the session from the client in integration tests | |
app.get '/set-session/:id', (req, r) => | |
setSession req.params.id | |
r.send { set: data.users[req.params.id] } | |
next() |
Awesome dude! This code helped a lot. It's worth to mention an issue that took me one hour to figure out. I was having this exception: TypeError: object is not a function -> Object.passport.deserializeUser. Digging a little at passport code it turns out that the done function is the third param when deserializeUser is called, and the second is the req. At least for the version 0.2.0 which is the one I'm using right now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh man - you're a hero! Thanks so much! Saved me hours of passport spelunking.