2014-01-13 20:00:21 +01:00
|
|
|
var express = require('express');
|
|
|
|
var http = require('http');
|
2012-11-16 16:43:12 +01:00
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
var socketIo = require('socket.io');
|
|
|
|
var socketio_jwt = require('../../lib');
|
|
|
|
|
|
|
|
var jwt = require('jsonwebtoken');
|
|
|
|
|
|
|
|
var xtend = require('xtend');
|
2012-11-16 16:43:12 +01:00
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
var server;
|
2012-11-16 16:43:12 +01:00
|
|
|
|
2013-01-07 15:30:15 +01:00
|
|
|
exports.start = function (options, callback) {
|
2014-01-13 20:00:21 +01:00
|
|
|
|
2013-01-07 15:30:15 +01:00
|
|
|
if(typeof options == 'function'){
|
|
|
|
callback = options;
|
2014-01-13 20:00:21 +01:00
|
|
|
options = {};
|
|
|
|
}
|
2013-01-07 15:30:15 +01:00
|
|
|
|
2014-01-13 22:41:10 +01:00
|
|
|
options = xtend({
|
|
|
|
secret: 'aaafoo super sercret',
|
2014-01-14 12:30:39 +01:00
|
|
|
timeout: 1000,
|
|
|
|
handshake: true
|
2014-01-13 22:41:10 +01:00
|
|
|
}, options);
|
2012-11-16 16:43:12 +01:00
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
var app = express();
|
2012-11-16 16:43:12 +01:00
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
app.configure(function(){
|
|
|
|
this.use(express.json());
|
|
|
|
this.use(express.urlencoded());
|
2012-11-16 16:43:12 +01:00
|
|
|
});
|
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
app.post('/login', function (req, res) {
|
|
|
|
var profile = {
|
|
|
|
first_name: 'John',
|
|
|
|
last_name: 'Doe',
|
|
|
|
email: 'john@doe.com',
|
|
|
|
id: 123
|
|
|
|
};
|
|
|
|
|
|
|
|
// We are sending the profile inside the token
|
|
|
|
var token = jwt.sign(profile, options.secret, { expiresInMinutes: 60*5 });
|
2012-11-16 16:43:12 +01:00
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
res.json({token: token});
|
2012-11-16 16:43:12 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
server = http.createServer(app);
|
|
|
|
|
|
|
|
var sio = socketIo.listen(server);
|
|
|
|
|
2014-01-13 20:00:21 +01:00
|
|
|
sio.configure(function(){
|
2014-01-14 12:30:39 +01:00
|
|
|
if (options.handshake) {
|
2014-01-13 22:41:10 +01:00
|
|
|
this.set('authorization', socketio_jwt.authorize(options));
|
|
|
|
}
|
2012-11-16 16:43:12 +01:00
|
|
|
this.set('log level', 0);
|
|
|
|
});
|
|
|
|
|
2014-01-14 12:30:39 +01:00
|
|
|
if (options.handshake) {
|
2014-01-13 22:41:10 +01:00
|
|
|
sio.sockets.on('echo', function (m) {
|
|
|
|
sio.sockets.emit('echo-response', m);
|
|
|
|
});
|
|
|
|
} else {
|
2014-01-14 12:30:39 +01:00
|
|
|
sio.sockets
|
|
|
|
.on('connection', socketio_jwt.authorize(options))
|
|
|
|
.on('authenticated', function (socket) {
|
|
|
|
socket.on('echo', function (m) {
|
|
|
|
socket.emit('echo-response', m);
|
|
|
|
});
|
2014-01-13 22:41:10 +01:00
|
|
|
});
|
|
|
|
}
|
2012-11-16 16:43:12 +01:00
|
|
|
|
|
|
|
server.listen(9000, callback);
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.stop = function (callback) {
|
|
|
|
server.close();
|
|
|
|
callback();
|
|
|
|
};
|