public
Last active

nodejs app - expressjs 3.0 + socket.io v9 + passport + redis

  • Download Gist
app.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
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'))
})

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.