-
-
Save PatrickHeneise/2132062 to your computer and use it in GitHub Desktop.
var flatiron = require('flatiron') | |
, connect = require('connect') | |
, path = require('path') | |
, fs = require('fs') | |
, plates = require('plates') | |
, director = require('director') | |
, util = require('util') | |
, keys = require('./auth_keys') | |
, passport = require('passport') | |
, TwitterStrategy = require('passport-twitter').Strategy | |
, union = require('union'); | |
passport.use(new TwitterStrategy({ | |
consumerKey: keys.twitter.consumerKey, | |
consumerSecret: keys.twitter.consumerSecret, | |
callbackURL: "http://127.0.0.1:3000/auth/twitter/callback" | |
}, | |
function(token, tokenSecret, profile, done) { | |
console.log("strategy"); | |
// asynchronous verification, for effect... | |
process.nextTick(function () { | |
console.log("strategy tick"); | |
return done(null, profile); | |
}); | |
} | |
)); | |
passport.serializeUser(function(user, done) { | |
console.log("serialize"); | |
done(null, user); | |
}); | |
passport.deserializeUser(function(obj, done) { | |
console.log("deserialize"); | |
done(null, obj); | |
}); | |
var router = new director.http.Router(); | |
var server = union.createServer({ | |
before: [ | |
connect.cookieParser("secret"), | |
connect.session(), | |
passport.initialize(), | |
passport.session(), | |
function (req, res) { | |
var found = router.dispatch(req, res); | |
if (!found) { | |
res.emit('next'); | |
} | |
}, | |
connect.static('public') | |
] | |
}); | |
router.get('/auth/twitter', | |
passport.authenticate('twitter'), | |
function(){} | |
); | |
router.get('/auth/twitter/callback', | |
passport.authenticate('twitter', { failureRedirect: '/login' }), | |
function() { | |
this.res.writeHead(302, { | |
'Location': 'login.html' | |
}); | |
this.res.end(); | |
}); | |
router.get(/logout/, function() { | |
// req.logout(); | |
this.res.writeHead(302, { | |
'Location': '/' | |
}); | |
this.res.end(); | |
}); | |
// GET / | |
// Main function | |
router.get('/', function () { | |
console.log("GET /"); | |
var self = this; | |
// fs.get etc. | |
}) | |
}); | |
// 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, next) { | |
if (req.isAuthenticated()) { return next(); } | |
res.redirect('/login') | |
} | |
server.listen(3000, function () { | |
console.log('Application is now started on port 3000'); | |
}); |
Hey Jared,
I am picking up where Patrick left off. However, I am currently only using local authentication.
I've got it working, but I've had to make some hacky changes to flatiron and passport. I want to be able to do as you suggested and come up some example code that works with a vanilla passport/flatiron install but I need your help in moving my "hacky" work-arounds to stable solutions that can be contained within the passport module. Where can I reach you for some questions on this?
Thanks!
Sounds great. Send me email to gmail user jaredhanson.
Anyone successfully use passport in flatiron?
Hey Steele, check out this branch of Passport:
https://github.com/jaredhanson/passport/tree/flatiron
I am currently using the two together, however, this is only for plain authentication. I have yet to try the oAuth, but I dont see any reason why it would not work.
However, just keep in mind that you will have to use a few tricks as Jared mentioned above to get it working. Here are the relevant snippets from my code:
// User is a flatiron/Resourceful model factory here. The set up of this is not shown below.
u = User.new(
{
"username": "test_user",
"password": "secret",
"email": "[email protected]"
}
);
u.save();
function findByUsername(username, done) {
User.find({"username":username}, function(err, user) {
if (err) {
return done(err, null);
}
else if (user) {
return done(null, user[0]);
}
else {
return done(null, null);
}
});
}
passport.use(new LocalStrategy(
function(username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unkown user ' + username }); }
debugger;
console.log(password);
console.log(user.password);
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(username, done) {
findByUsername(username, function (err, user) {
done(err, user);
});
});
App.router.path('/', function() {
this.post('/login',
function() {
self = this;
function next() {
console.log('next wrap');
self.res.emit('next');
}
passport.authenticate('local', function(err, user) {
console.log(user);
if (err) { self.res.end("SERVER ERROR\n") }
if (!user) { self.res.end("false") }
else {
self.req.logIn(user, function(err) {
if (err) {throw err}
self.res.writeHead(200, {'Content-Type': 'text/html',
'Authentication': JSON.stringify(self.req._passport.session)});
self.res.end("true");
});
}
})(this.req, this.res, next);
}
);
});
I believe I got this working with a simple package.
https://npmjs.org/package/flatiron-passport
https://github.com/travist/flatiron-passport
Please read the README.md on how to use. For the most part, it is a pretty simple wrapper around passport that makes it work within flatiron. I have only so far tested LocalStrategy, but it should work with others since I basically maintained the API between the two. Please test this and let me know if this works for you guys.
Hi,
I'm having some trouble the debugger says that "req" has no method "isAuthenticated". I'm checking if the user is authenticated in the before hook to not go all the way up to the app's router. What do you think that the problem might be.
app.use(flatiron.plugins.http, {
before : [
function(req, res) {
req.originalUrl = req.url;
res.emit('next');
},
connect.cookieParser(),
connect.session({ secret : 'keyboard cat' }),
passport.initialize(),
passport.session(),
function(req, res) {
if (!/^\/dashboard$|dashboard\/.*$/.test(req.url)) {
return res.emit('next');
}
if (req.isAuthenticated()) {
return res.emit('next');
}
res.redirect('/');
},
ecstatic(path.join(__dirname, './public'), {
autoIndex : false,
cache : "0, no-cache, no-store, must-revalidate"
}) //cache control was turned off
]
});
Robert.
Thanks a lot!
I'm not sure if I should further pursue it. Even if I figure that out, there'll be the next problem right there tomorrow. I just set up the project in Express.js and within 10 minutes I'm at the same point which took me 5 evenings in flatiron. I think it just needs some more time.