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

260 lines
7.6 KiB
JavaScript
Raw Normal View History

const xtend = require('xtend');
const jwt = require('jsonwebtoken');
const UnauthorizedError = require('./UnauthorizedError');
function noQsMethod (options) {
const defaults = { required: true };
options = xtend(defaults, options);
2015-05-29 13:52:14 +02:00
return (socket) => {
2019-10-14 04:13:25 +02:00
'use strict'; // Node 4.x workaround
const server = this.server || socket.server;
2014-01-14 12:30:39 +01:00
if (!server.$emit) {
//then is socket.io 1.0
const Namespace = Object.getPrototypeOf(server.sockets).constructor;
if (!~Namespace.events.indexOf('authenticated')) {
Namespace.events.push('authenticated');
}
}
2015-05-29 13:52:14 +02:00
let auth_timeout = null;
if (options.required) {
auth_timeout = setTimeout(() => {
2015-05-29 13:52:14 +02:00
socket.disconnect('unauthorized');
}, options.timeout || 5000);
}
socket.on('authenticate', (data) => {
if (options.required) {
2015-05-29 13:52:14 +02:00
clearTimeout(auth_timeout);
}
// error handler
const onError = (err, code) => {
2017-11-13 16:54:19 +01:00
if (err) {
code = code || 'unknown';
const error = new UnauthorizedError(code, {
2017-11-13 16:54:19 +01:00
message: (Object.prototype.toString.call(err) === '[object Object]' && err.message) ? err.message : err
});
let callback_timeout;
// If callback explicitly set to false, start timeout to disconnect socket
2017-11-13 16:54:19 +01:00
if (options.callback === false || typeof options.callback === 'number') {
if (typeof options.callback === 'number') {
if (options.callback < 0) {
// If callback is negative(invalid value), make it positive
options.callback = Math.abs(options.callback);
}
}
callback_timeout = setTimeout(() => {
socket.disconnect('unauthorized');
2017-11-13 16:54:19 +01:00
}, (options.callback === false ? 0 : options.callback));
}
socket.emit('unauthorized', error, () => {
2017-11-13 16:54:19 +01:00
if (typeof options.callback === 'number') {
clearTimeout(callback_timeout);
}
socket.disconnect('unauthorized');
});
return; // stop logic, socket will be close on next tick
}
};
const token = options.cookie ? socket.request.cookies[options.cookie] : (data ? data.token : undefined);
2018-09-27 10:53:48 +02:00
if (!token || typeof token !== 'string') {
return onError({ message: 'invalid token datatype' }, 'invalid_token');
}
// Store encoded JWT
socket[options.encodedPropertyName] = token;
2015-05-29 13:52:14 +02:00
const onJwtVerificationReady = (err, decoded) => {
if (err) {
return onError(err, 'invalid_token');
2014-01-13 22:41:10 +01:00
}
2015-05-29 13:52:14 +02:00
// success handler
const onSuccess = () => {
socket[options.decodedPropertyName] = options.customDecoded
? options.customDecoded(decoded)
: decoded;
socket.emit('authenticated');
if (server.$emit) {
server.$emit('authenticated', socket);
} else {
2015-08-31 16:04:04 +02:00
//try getting the current namespace otherwise fallback to all sockets.
const namespace = (server.nsps && socket.nsp &&
2017-11-13 16:54:19 +01:00
server.nsps[socket.nsp.name]) ||
server.sockets;
2015-08-31 16:04:04 +02:00
// explicit namespace
2015-08-31 16:04:04 +02:00
namespace.emit('authenticated', socket);
}
};
2015-05-29 13:52:14 +02:00
if (options.additional_auth && typeof options.additional_auth === 'function') {
2015-07-05 18:57:24 +02:00
options.additional_auth(decoded, onSuccess, onError);
} else {
onSuccess();
}
};
const onSecretReady = (err, secret) => {
if (err || !secret) {
return onError(err, 'invalid_secret');
}
2014-01-13 22:41:10 +01:00
2018-09-27 10:53:48 +02:00
jwt.verify(token, secret, options, onJwtVerificationReady);
};
2018-09-27 10:53:48 +02:00
getSecret(socket.request, options.secret, token, onSecretReady);
});
2014-01-13 22:41:10 +01:00
};
}
function authorize (options) {
options = xtend({ decodedPropertyName: 'decoded_token', encodedPropertyName: 'encoded_token' }, options);
if (typeof options.secret !== 'string' && typeof options.secret !== 'function') {
throw new Error(`Provided secret ${options.secret} is invalid, must be of type string or function.`);
}
2015-05-29 13:52:14 +02:00
if (!options.handshake) {
return noQsMethod(options);
}
const defaults = {
success: (socket, accept) => {
if (socket.request) {
2014-06-03 13:12:07 +02:00
accept();
} else {
accept(null, true);
}
},
fail: (error, socket, accept) => {
if (socket.request) {
accept(error);
2014-06-03 13:12:07 +02:00
} else {
accept(null, false);
}
}
};
2012-09-05 20:14:36 +02:00
const auth = xtend(defaults, options);
2013-06-30 21:06:21 +02:00
return (socket, accept) => {
2019-10-14 04:13:25 +02:00
'use strict'; // Node 4.x workaround
let token, error;
2019-10-14 04:13:25 +02:00
const handshake = socket.handshake;
const req = socket.request || socket;
const authorization_header = (req.headers || {}).authorization;
2014-06-03 13:12:07 +02:00
if (authorization_header) {
const parts = authorization_header.split(' ');
if (parts.length == 2) {
const scheme = parts[0],
credentials = parts[1];
2012-09-05 20:14:36 +02:00
2015-05-18 03:05:00 +02:00
if (scheme.toLowerCase() === 'bearer') {
token = credentials;
}
} else {
error = new UnauthorizedError('credentials_bad_format', {
message: 'Format is Authorization: Bearer [token]'
});
return auth.fail(error, socket, accept);
}
}
// Check if the header has to include authentication
if (options.auth_header_required && !token) {
return auth.fail(new UnauthorizedError('missing_authorization_header', {
message: 'Server requires Authorization Header'
}), socket, accept);
}
// Get the token from handshake or query string
if (handshake && handshake.query.token) {
token = handshake.query.token;
}
else if (req._query && req._query.token) {
token = req._query.token;
}
else if (req.query && req.query.token) {
token = req.query.token;
}
2012-09-05 20:14:36 +02:00
if (!token) {
error = new UnauthorizedError('credentials_required', {
2017-08-04 17:18:23 +02:00
message: 'no token provided'
2012-09-05 20:14:36 +02:00
});
return auth.fail(error, socket, accept);
}
// Store encoded JWT
socket[options.encodedPropertyName] = token;
const onJwtVerificationReady = (err, decoded) => {
if (err) {
error = new UnauthorizedError(err.code || 'invalid_token', err);
return auth.fail(error, socket, accept);
}
socket[options.decodedPropertyName] = options.customDecoded
? options.customDecoded(decoded)
: decoded;
2012-09-05 20:14:36 +02:00
return auth.success(socket, accept);
};
const onSecretReady = (err, secret) => {
if (err) {
error = new UnauthorizedError(err.code || 'invalid_secret', err);
return auth.fail(error, socket, accept);
}
jwt.verify(token, secret, options, onJwtVerificationReady);
};
getSecret(req, options.secret, token, onSecretReady);
2012-09-05 20:14:36 +02:00
};
}
function getSecret (request, secret, token, callback) {
2019-10-14 04:13:25 +02:00
'use strict'; // Node 4.x workaround
if (typeof secret === 'function') {
if (!token) {
return callback({ code: 'invalid_token', message: 'jwt must be provided' });
}
const parts = token.split('.');
if (parts.length < 3) {
return callback({ code: 'invalid_token', message: 'jwt malformed' });
}
if (parts[2].trim() === '') {
return callback({ code: 'invalid_token', message: 'jwt signature is required' });
}
let decodedToken = jwt.decode(token);
if (!decodedToken) {
return callback({ code: 'invalid_token', message: 'jwt malformed' });
}
secret(request, decodedToken, callback);
} else {
callback(null, secret);
}
2017-11-13 16:54:19 +01:00
}
2012-09-05 20:14:36 +02:00
exports.authorize = authorize;
exports.UnauthorizedError = UnauthorizedError;