Created
November 19, 2012 16:58
-
-
Save robert52/4111865 to your computer and use it in GitHub Desktop.
Flatiron and passport authentication
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
var flatiron = require('flatiron') | |
, app = module.exports = flatiron.app | |
, union = require('union') | |
, connect = require('connect') | |
, passport = require('passport') | |
, LocalStrategy = require('passport-local').Strategy; | |
var Bob = { | |
id : '1234-5678-9012', | |
username : 'bob', | |
password : '1234' | |
}; | |
var authenticate = function(name, options, callback) { | |
return function() { | |
passport.authenticate(name, options, callback)(this.req, this.res, (function(self) { | |
return function() { | |
self.res.emit('next'); | |
} | |
})(this)); | |
}; | |
}; | |
passport.use('local', new LocalStrategy(function(username, password, done) { | |
process.nextTick(function() { | |
if (Bob.username !== username) { return done(null, false, {message: 'Unknown user ' + username}); } | |
if (Bob.username === username && Bob.password === password) { | |
return done(null, Bob); | |
} | |
}); | |
})); | |
passport.serializeUser(function(user, done) { | |
console.log("serialize"); | |
done(null, user); | |
}); | |
passport.deserializeUser(function(obj, done) { | |
console.log("deserialize"); | |
done(null, obj); | |
}); | |
app.use(flatiron.plugins.http, { | |
before: [ | |
function (req, res) { | |
req.originalUrl = req.url; | |
res.emit('next'); | |
}, | |
connect.cookieParser(), | |
connect.session({secret: 'i have secrets'}), | |
passport.initialize(), | |
passport.session(), | |
connect.static('public'), | |
function (req, res) { | |
req.isAuthenticated = res.req.isAuthenticated; | |
req.isUnauthenticated = res.req.isUnauthenticated; | |
req.login = req.logIn = res.req.login; | |
req.logout = req.logOut = res.req.logout; | |
res.emit('next'); | |
} | |
] | |
}); | |
app.router.post('/login', authenticate('local', { | |
successRedirect: '/protected', | |
failureRedirect: '/' | |
})); | |
// Simple route middleware to ensure user is authenticated. | |
// Use this route middleware on any resource that needs to be protected. If | |
// the request is authenticated (typically via a persistent login session), | |
// the request will proceed. Otherwise, the user will be redirected to the | |
// login page. | |
function ensureAuthenticated(req, res) { | |
if (req.isAuthenticated()) { return res.emit('next'); } | |
res.redirect('/'); | |
} | |
app.start(3000, function(err) { | |
if (err) { | |
throw err; | |
} | |
var addr = app.server.address(); | |
app.log.info('Listening on http://' + addr.address + ':' + addr.port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment