I'm trying to use redis with express to create a user login and session. I test the route using this curl script:
curl -d 'email=testEmail&password=testPass' http://localhost:3000/users/session
When I do this, passport works fine through serialization, and then it returns http 302. I haven't figured out what it does after serialization, but when I try it in the browser with my login html form instead of curl, It shows me "Unauthorized" 401, and I don't see any of my console logs. Here's my app.js:
var express = require('express')
, fs = require('fs')
, cons = require('consolidate')
, http = require('http')
, flash = require('connect-flash')
, passport = require('passport')
, RedisStore = require( "connect-redis" )(express) //for sessions (instead of MemoryStore)
, redis = require('redis')
, env = process.env.NODE_ENV || 'development'
, config = require('./config/config')[env]
, db = redis.createClient(config.db.port, config.db.host);
db.select(config.db.users)
db.auth(config.db.auth);
var app = express();
//require passport strategies (see code block below)
require('./config/passport')(passport, config, app)
app.use('/assets', express.static(__dirname + '/public'));
app.use('/', express.static(__dirname + '/'));
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.configure(function(){
app.set('config', config);
app.set('db', db);
app.set('port', process.env.PORT || 3000);
app.engine('.html', cons.swig);
app.use(express.logger('dev'))
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.cookieParser())
app.use(express.bodyParser()) //enables req.body
app.use(express.methodOverride()) //enables app.put and app.delete (can also just use app.post)
app.use(express.session({
secret: 'topsecret',
cookie: {secure: true, maxAge:86400000},
store: new RedisStore({
client:db,
secret:config.db.auth
})
}));
app.use(flash())
app.use(passport.initialize())
app.use(passport.session())
app.use(app.router)
});
// Bootstrap routes
require('./config/routes')(app, passport);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port')+', mode='+env);
});
And the session POST route:
app.post('/users/session', passport.authenticate('local', {successRedirect: '/', failureFlash: 'Invalid email or password.', successFlash: 'Welcome!'}), users.session);
I could only really find examples of passport with mongodb, so I'm not sure about the following. I attempt to find a user, but I'm not sure about the callbacks or what passport is doing with the user info when I return done:
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
function(email, password, done) {
var db = app.get('db')
var multi = db.multi();
db.get('email:'+email, function(err, uid){
if (err) { console.log(err); return err }
if (!uid) { console.log('no uid found'); return null }
console.log('found '+uid)
db.hgetall('uid:'+uid, function(err, user){
if (err) { console.log(err); return err }
if (!user) {
console.log('unkwn usr')
return done(null, false, { message: 'Unknown user' })
}
if (password != user.password) {
console.log('invalid pwd')
return done(null, false, { message: 'Invalid password' })
}
console.log('found user '+user) //I see this fine with curl, but no logs with browser
return done(null, user)
});
});
}
))
Passport serialization:
passport.serializeUser(function(user, done) {
console.log('passport serializing...'+user.name)
done(null, user.name) //no idea what happens to it after this. returns a 302 with curl, and 401 with browser
})
Why does this act differently with a browser than with curl? Any help or comments much appreciated!
Figured it out! To use passport with any database (not just mongo), I would recommend trying it with a dummy user first. Here's what I did.
Login Form (login.html):
<form method="post" action="http://localhost:3000/users/session" name="loginform">
<input id="login_input_username" type="text" name="email" />
<input id="login_input_password" type="password" name="password" autocomplete="off" />
<input type="submit" name="login" value="Submit" />
</form>
Routing (route.js):
app.post('/users/session', passport.authenticate('local'),
function(req, res){
res.end('success!');
});
Passport Local Strategy setup (passport.js):
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
function(email, password, done) {
//find user in database here
var user = {id: 1, email:'test', password:'pass'};
return done(null, user);
}
));
passport.serializeUser(function(user, done) {
//serialize by user id
done(null, user.id)
});
passport.deserializeUser(function(id, done) {
//find user in database again
var user = {id: 1, email:'test', password:'pass'};
done(null, user);
})
Although I'm wondering if it's necessary to find user in my database twice, or if I'm using deserialize incorrectly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With