mirror of
https://github.com/Thream/socketio-jwt.git
synced 2024-07-21 09:38:31 +02:00
Add an "additionnal" option (Function(decoded, onSuccess, onError)). When the token is parser and validated the callback is triggered and allow addition of extra logic (e.g. validate the user status against database).
Improve returned errors.
This commit is contained in:
parent
346b4d7aa1
commit
f5a84eb9bb
38
lib/index.js
38
lib/index.js
@ -21,19 +21,39 @@ function noQsMethod(options) {
|
||||
socket.on('authenticate', function (data) {
|
||||
clearTimeout(auth_timeout);
|
||||
jwt.verify(data.token, options.secret, options, function(err, decoded) {
|
||||
// error handler
|
||||
var onError = function(err, code) {
|
||||
if (err) {
|
||||
code = code || 'unknown';
|
||||
var error = new UnauthorizedError(code, {
|
||||
message: (Object.prototype.toString.call(err) === '[object Object]' && err.message) ? err.message : err
|
||||
});
|
||||
socket.emit('unauthorized', error, function() {
|
||||
socket.disconnect('unauthorized');
|
||||
});
|
||||
return; // stop logic, socket will be close on next tick
|
||||
}
|
||||
};
|
||||
|
||||
if (err) {
|
||||
socket.emit('unauthorized', err, function() {
|
||||
socket.disconnect('unauthorized');
|
||||
});
|
||||
return; // stop logic, socket will be close on next tick
|
||||
return onError(err, 'invalid_token');
|
||||
}
|
||||
|
||||
socket.decoded_token = decoded;
|
||||
socket.emit('authenticated');
|
||||
if (server.$emit) {
|
||||
server.$emit('authenticated', socket);
|
||||
// success handler
|
||||
var onSuccess = function(){
|
||||
socket.decoded_token = decoded;
|
||||
socket.emit('authenticated');
|
||||
if (server.$emit) {
|
||||
server.$emit('authenticated', socket);
|
||||
} else {
|
||||
server.server.sockets.emit('authenticated', socket);
|
||||
}
|
||||
};
|
||||
|
||||
if(options.additional && typeof options.additional === 'function') {
|
||||
options.additional(decoded, onSuccess, onError);
|
||||
} else {
|
||||
server.server.sockets.emit('authenticated', socket);
|
||||
onSuccess();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user