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

79 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-10-14 04:13:25 +02:00
'use strict'; // Node 4.x workaround
const express = require('express');
const http = require('http');
2012-11-16 16:43:12 +01:00
const socketIo = require('socket.io');
const socketio_jwt = require('../../lib');
const jwt = require('jsonwebtoken');
const xtend = require('xtend');
const bodyParser = require('body-parser');
const enableDestroy = require('server-destroy');
let sio;
2012-11-16 16:43:12 +01:00
exports.start = (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
const app = express();
const server = http.createServer(app);
sio = socketIo.listen(server);
2012-11-16 16:43:12 +01:00
2015-08-31 16:08:31 +02:00
app.use(bodyParser.json());
app.post('/login', (req, res) => {
const profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: 123
};
// We are sending the profile inside the token
const token = jwt.sign(profile, options.secret, { expiresIn: 60*60*5 });
res.json({token: token});
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
sio.sockets.on('echo', (m) => {
2014-01-13 22:41:10 +01:00
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', (socket) => {
socket.on('echo', (m) => {
2014-01-14 12:30:39 +01:00
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', (c) => {
2015-05-29 14:39:49 +02:00
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 = (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();
};