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

71 lines
1.5 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');
2015-08-31 16:04:04 +02:00
const socketIo = require('socket.io');
const socketio_jwt = require('../../lib');
2015-08-31 16:04:04 +02:00
const jwt = require('jsonwebtoken');
const enableDestroy = require('server-destroy');
const bodyParser = require('body-parser');
2015-08-31 16:04:04 +02:00
let sio;
2015-08-31 16:04:04 +02:00
/**
* This is an example server that shows how to do namespace authentication.
*
* The /admin namespace is protected by JWTs while the global namespace is public.
*/
exports.start = (callback) => {
2015-08-31 16:04:04 +02:00
const options = {
2015-08-31 16:04:04 +02:00
secret: 'aaafoo super sercret',
timeout: 1000,
handshake: false
};
const app = express();
const server = http.createServer(app);
sio = socketIo.listen(server);
2015-08-31 16:04:04 +02:00
2015-08-31 16:08:31 +02:00
app.use(bodyParser.json());
app.post('/login', (req, res) => {
const profile = {
2015-08-31 16:04:04 +02:00
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 });
2015-08-31 16:04:04 +02:00
});
sio.on('connection', (socket) => {
2015-08-31 16:04:04 +02:00
socket.emit('hi');
});
const admin_nsp = sio.of('/admin');
2015-08-31 16:04:04 +02:00
admin_nsp.on('connection', socketio_jwt.authorize(options))
.on('authenticated', (socket) => {
2015-08-31 16:04:04 +02:00
socket.emit('hi admin');
});
server.listen(9000, callback);
enableDestroy(server);
};
exports.stop = (callback) => {
2015-08-31 16:04:04 +02:00
sio.close();
2015-08-31 16:14:48 +02:00
try {
server.destroy();
} catch (er) {}
2015-08-31 16:04:04 +02:00
callback();
};