forked from thebinarypenguin/socket.io-chess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·59 lines (51 loc) · 1.85 KB
/
server.js
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
var path = require('path')
, http = require('http')
, express = require('express')
, socket = require('socket.io')
, httpRoutes = require('./routes/http')
, socketRoutes = require('./routes/socket')
, GameStore = require('./lib/GameStore');
var app = express()
, server = http.createServer(app)
, io = socket.listen(server);
var DB = new GameStore();
var cookieParser = express.cookieParser('I wish you were an oatmeal cookie')
, sessionStore = new express.session.MemoryStore();
// Settings
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// Middleware
app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(cookieParser);
app.use(express.session({ store: sessionStore }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/*
* Only allow socket connections that come from clients with an established session.
* This requires re-purposing Express's cookieParser middleware in order to expose
* the session info to Socket.IO
*/
io.set('authorization', function (handshakeData, callback) {
cookieParser(handshakeData, {}, function(err) {
if (err) return callback(err);
sessionStore.load(handshakeData.signedCookies['connect.sid'], function(err, session) {
if (err) return callback(err);
handshakeData.session = session;
var authorized = (handshakeData.session) ? true : false;
callback(null, authorized);
});
});
});
// Attach routes
httpRoutes.attach(app, DB);
socketRoutes.attach(io, DB);
// And away we go
server.listen(app.get('port'), function(){
console.log('Socket.IO Chess is listening on port ' + app.get('port'));
});