2
1
mirror of https://github.com/Thream/socketio-jwt.git synced 2024-07-21 09:38:31 +02:00
socketio-jwt/test/fixture/index.js

80 lines
1.7 KiB
JavaScript
Raw Normal View History

var express = require('express');
var http = require('http');
2012-11-16 16:43:12 +01:00
var socketIo = require('socket.io');
var socketio_jwt = require('../../lib');
var jwt = require('jsonwebtoken');
var xtend = require('xtend');
2015-08-31 16:08:31 +02:00
var bodyParser = require('body-parser');
2012-11-16 16:43:12 +01:00
2015-05-29 14:39:49 +02:00
var server, sio;
2015-08-31 16:04:04 +02:00
var enableDestroy = require('server-destroy');
2012-11-16 16:43:12 +01:00
exports.start = function (options, callback) {
if(typeof options == 'function'){
callback = options;
options = {};
}
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
var app = express();
2012-11-16 16:43:12 +01:00
2015-08-31 16:08:31 +02:00
app.use(bodyParser.json());
2012-11-16 16:43:12 +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
res.json({token: token});
2012-11-16 16:43:12 +01:00
});
server = http.createServer(app);
2015-05-29 14:39:49 +02:00
sio = socketIo.listen(server);
2012-11-16 16:43:12 +01:00
if (options.handshake) {
sio.use(socketio_jwt.authorize(options));
2012-11-16 16:43:12 +01:00
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
2015-05-29 14:39:49 +02:00
server.__sockets = [];
server.on('connection', function (c) {
server.__sockets.push(c);
});
2012-11-16 16:43:12 +01:00
server.listen(9000, callback);
2015-08-31 16:04:04 +02:00
enableDestroy(server);
2012-11-16 16:43:12 +01:00
};
exports.stop = function (callback) {
2015-05-29 14:39:49 +02:00
sio.close();
2015-08-31 16:14:48 +02:00
try {
server.destroy();
} catch (er) {}
2012-11-16 16:43:12 +01:00
callback();
};