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

78 lines
1.6 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');
2012-11-16 16:43:12 +01:00
var server;
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
app.configure(function(){
this.use(express.json());
this.use(express.urlencoded());
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);
var sio = socketIo.listen(server);
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();
};