Skip to content

Instantly share code, notes, and snippets.

@katanacrimson
Created December 2, 2012 18:23
Show Gist options
  • Save katanacrimson/4190316 to your computer and use it in GitHub Desktop.
Save katanacrimson/4190316 to your computer and use it in GitHub Desktop.
nodejs app - expressjs 3.0 + socket.io v9 + passport + redis
var express = require('express'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
connect = require('connect'),
http = require('http'),
path = require('path'),
util = require('util'),
fs = require('fs'),
redis = require('redis'),
cookie = require('cookie'),
connectSession = require('connect/lib/middleware/session/session'),
socketRedisStore = require('socket.io/lib/stores/redis')
var app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server),
redisPub = redis.createClient(),
redisSub = redis.createClient(),
redisClient = redis.createClient(),
RedisStore = require('connect-redis')(express),
sessionStore
nconf = require('nconf')
// nconf setup...
var arp = require('./lib/arp')
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
arp.user.findByUsername(username, function(err, user) {
if (err) {
done(err)
return
}
if (!user) {
user.checkPassword('$2a$10$va3CGzjy.g/Z8cuEcO844O', 'test', function(err, result) {
// ignoring result - just doing this to spend CPU time to throw off high-precision timing attacks
done(null, false, { message: 'Invalid username or password'})
})
return
}
user.checkPassword(password, function(err, result) {
if(err) {
done(err)
return
}
if(result == false) {
done(null, false, { message: 'Invalid username or password'})
return
} else {
// @todo ban-check
// green light
done(null, user)
}
})
})
})
}
))
function ensureAuthenticated(req, res, next) {
if(req.isAuthenticated()) return next()
res.redirect('/login')
return null
}
app.configure(function(){
var cookieMaxAge = nconf.get('app:cookie:maxAge')
sessionStore = new RedisStore({
client: redisClient,
})
app.set('port', nconf.get('app:port'))
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.favicon())
if(nconf.get('app:env') === 'development')
app.use(express.logger('dev'))
app.use(express.cookieParser(nconf.get('app:cookie:secret')))
app.use(express.bodyParser())
app.use(express.methodOverride())
app.use(express.session({
key: nconf.get('app:cookie:key'),
store: sessionStore,
secret: nconf.get('app:cookie:secret'),
cookie: { maxAge: (cookieMaxAge !== 0) ? cookieMaxAge : null }
}))
app.use(express.csrf())
app.use(flash())
app.use(passport.initialize())
app.use(passport.session())
app.use(app.router)
app.use(express.static(__dirname + '/public'))
app.use(express.errorHandler())
})
// @note expressjs routes et al here....
/**
* socket.io stuff. Streaming.
*/
// authentication verification
io.configure(function () {
io.set('log level', 1)
io.set('store', new socketRedisStore({
redisPub : redisPub,
redisSub : redisSub,
redisClient : redisClient
}))
io.set('authorization', function (data, accept) {
if (data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie)
data.cookie = connect.utils.parseSignedCookies(data.cookie, nconf.get('app:cookie:secret'))
data.cookie = connect.utils.parseJSONCookies(data.cookie)
data.sessionID = data.cookie[nconf.get('app:cookie:key')]
sessionStore.load(data.sessionID, function (err, session) {
if (err || !session) {
// invalid session identifier. tl;dr gtfo.
accept('session error', false)
} else {
data.session = session
accept(null, true)
}
})
} else {
// no auth cookie...
accept('session error', false)
}
})
})
io.sockets.on('connection', function (socket) {
var sessionID = socket.handshake.sessionID,
session = new connect.middleware.session.Session({ sessionStore: sessionStore }, socket.handshake.session)
console.log('socket: new ' + sessionID)
socket.broadcast.emit('arpNewConn', session.passport.user)
var intervalID = setInterval(function() {
socket.handshake.session.reload(function() {
socket.handshake.session.touch().save()
})
socket.emit('pulse', { heartbeat: new Date().toString(), timestamp: new Date().getTime() })
}, 300 * 1000) // every 300 seconds, pulse to maintain the session (10s for testing)
// @note more socket.io stuff here...
socket.on('disconnect', function () {
// clear the socket interval to stop refreshing the session
console.log('socket: dump ' + sessionID)
socket.broadcast.emit('arpLostConn', session.passport.user)
clearInterval(intervalID)
})
})
/**
* start the server
*/
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'))
})
@joeneldeasis
Copy link

arp.user.findByUsername(username, function(err, user) { is the database command for finding the database by username? So if I'm using redis is the only line do I need to change? Thanks, cause I'm having trouble using passport with my redis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment