This repository has been archived on 2024-11-11. You can view files and clone it, but cannot push or open issues or pull requests.
socketio-jwt/oldCode/test/fixture/secret_function.js

88 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-12-27 17:25:44 +01:00
'use strict' // Node 4.x workaround
2019-10-14 04:13:25 +02:00
2020-12-27 17:25:44 +01:00
const express = require('express')
const http = require('http')
2020-12-27 17:25:44 +01:00
const socketIo = require('socket.io')
const socketio_jwt = require('../../lib')
2020-12-27 17:25:44 +01:00
const jwt = require('jsonwebtoken')
const xtend = require('xtend')
const enableDestroy = require('server-destroy')
2020-12-27 17:25:44 +01:00
let sio
exports.start = (options, callback) => {
const SECRETS = {
123: 'aaafoo super sercret',
555: 'other'
2020-12-27 17:25:44 +01:00
}
if (typeof options == 'function') {
2020-12-27 17:25:44 +01:00
callback = options
options = {}
}
2020-12-27 17:25:44 +01:00
options = xtend(
{
secret: (request, decodedToken, callback) => {
callback(null, SECRETS[decodedToken.id])
},
timeout: 1000,
handshake: true
},
2020-12-27 17:25:44 +01:00
options
)
2020-12-27 17:25:44 +01:00
const app = express()
const server = http.createServer(app)
sio = socketIo.listen(server)
2020-12-27 17:25:44 +01:00
app.use(express.json())
app.post('/login', (req, res) => {
const profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: req.body.username === 'valid_signature' ? 123 : 555
2020-12-27 17:25:44 +01:00
}
// We are sending the profile inside the token
2020-12-27 17:25:44 +01:00
const token = jwt.sign(profile, SECRETS[123], { expiresIn: 60 * 60 * 5 })
res.json({ token: token })
})
if (options.handshake) {
2020-12-27 17:25:44 +01:00
sio.use(socketio_jwt.authorize(options))
sio.sockets.on('echo', (m) => {
2020-12-27 17:25:44 +01:00
sio.sockets.emit('echo-response', m)
})
} else {
sio.sockets
.on('connection', socketio_jwt.authorize(options))
.on('authenticated', (socket) => {
socket.on('echo', (m) => {
2020-12-27 17:25:44 +01:00
socket.emit('echo-response', m)
})
})
}
2020-12-27 17:25:44 +01:00
server.__sockets = []
server.on('connection', (c) => {
2020-12-27 17:25:44 +01:00
server.__sockets.push(c)
})
2020-12-27 17:25:44 +01:00
server.listen(9000, callback)
enableDestroy(server)
}
exports.stop = (callback) => {
2020-12-27 17:25:44 +01:00
sio.close()
try {
2020-12-27 17:25:44 +01:00
server.destroy()
} catch (er) {}
2020-12-27 17:25:44 +01:00
callback()
}