Skip to content

Remove callback API #285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 11 additions & 33 deletions sign.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ var options_for_objects = [
'jwtid',
];

module.exports = function (payload, secretOrPrivateKey, options, callback) {
module.exports = function (payload, secretOrPrivateKey, options) {
options = options || {};

var isObjectPayload = typeof payload === 'object' &&
Expand All @@ -54,21 +54,13 @@ module.exports = function (payload, secretOrPrivateKey, options, callback) {
kid: options.keyid
}, options.header);

function failure(err) {
if (callback) {
return callback(err);
}
throw err;
}


if (typeof payload === 'undefined') {
return failure(new Error('payload is required'));
throw new Error('payload is required');
} else if (isObjectPayload) {
var payload_validation_result = registered_claims_schema.validate(payload);

if (payload_validation_result.error) {
return failure(payload_validation_result.error);
throw payload_validation_result.error;
}

payload = xtend(payload);
Expand All @@ -78,22 +70,22 @@ module.exports = function (payload, secretOrPrivateKey, options, callback) {
});

if (invalid_options.length > 0) {
return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload'));
throw new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload');
}
}

if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') {
return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));
throw new Error('Bad "options.expiresIn" option the payload already has an "exp" property.');
}

if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') {
return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));
throw new Error('Bad "options.notBefore" option the payload already has an "nbf" property.');
}

var validation_result = sign_options_schema.validate(options);

if (validation_result.error) {
return failure(validation_result.error);
throw validation_result.error;
}

var timestamp = payload.iat || Math.floor(Date.now() / 1000);
Expand All @@ -107,42 +99,28 @@ module.exports = function (payload, secretOrPrivateKey, options, callback) {
if (typeof options.notBefore !== 'undefined') {
payload.nbf = timespan(options.notBefore);
if (typeof payload.nbf === 'undefined') {
return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
throw new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
}
}

if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
payload.exp = timespan(options.expiresIn, timestamp);
if (typeof payload.exp === 'undefined') {
return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
throw new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
}
}

Object.keys(options_to_payload).forEach(function (key) {
var claim = options_to_payload[key];
if (typeof options[key] !== 'undefined') {
if (typeof payload[claim] !== 'undefined') {
return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));
throw new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.');
}
payload[claim] = options[key];
}
});

var encoding = options.encoding || 'utf8';

if (typeof callback === 'function') {
callback = callback && once(callback);

jws.createSign({
header: header,
privateKey: secretOrPrivateKey,
payload: payload,
encoding: encoding
}).once('error', callback)
.once('done', function (signature) {
callback(null, signature);
});
} else {
return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
}
return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
};
60 changes: 0 additions & 60 deletions test/async_sign.tests.js

This file was deleted.

55 changes: 18 additions & 37 deletions test/invalid_exp.tests.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,39 @@
var jwt = require('../index');
var JsonWebTokenError = require('../lib/JsonWebTokenError');
var TokenExpiredError = require('../lib/TokenExpiredError');
var expect = require('chai').expect;
var assert = require('chai').assert;

describe('invalid expiration', function() {

it('should fail with string', function (done) {
it('should fail with string', function () {
var broken_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIxMjMiLCJmb28iOiJhZGFzIn0.cDa81le-pnwJMcJi3o3PBwB7cTJMiXCkizIhxbXAKRg';

jwt.verify(broken_token, '123', function (err, decoded) {
expect(err.name).to.equal('JsonWebTokenError');
done();
});

var verify = jwt.verify.bind(null, broken_token, '123');
expect(verify).to.throw(JsonWebTokenError);
});

it('should fail with 0', function (done) {
it('should fail with 0', function () {
var broken_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjAsImZvbyI6ImFkYXMifQ.UKxix5T79WwfqAA0fLZr6UrhU-jMES2unwCOFa4grEA';

jwt.verify(broken_token, '123', function (err) {
expect(err.name).to.equal('TokenExpiredError');
done();
});

var verify = jwt.verify.bind(null, broken_token, '123');
expect(verify).to.throw(TokenExpiredError);
});

it('should fail with false', function (done) {
it('should fail with false', function () {
var broken_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOmZhbHNlLCJmb28iOiJhZGFzIn0.iBn33Plwhp-ZFXqppCd8YtED77dwWU0h68QS_nEQL8I';

jwt.verify(broken_token, '123', function (err) {
expect(err.name).to.equal('JsonWebTokenError');
done();
});

var verify = jwt.verify.bind(null, broken_token, '123');
expect(verify).to.throw(JsonWebTokenError);
});

it('should fail with true', function (done) {
it('should fail with true', function () {
var broken_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOnRydWUsImZvbyI6ImFkYXMifQ.eOWfZCTM5CNYHAKSdFzzk2tDkPQmRT17yqllO-ItIMM';

jwt.verify(broken_token, '123', function (err) {
expect(err.name).to.equal('JsonWebTokenError');
done();
});

var verify = jwt.verify.bind(null, broken_token, '123');
expect(verify).to.throw(JsonWebTokenError);
});

it('should fail with object', function (done) {
it('should fail with object', function () {
var broken_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOnt9LCJmb28iOiJhZGFzIn0.1JjCTsWLJ2DF-CfESjLdLfKutUt3Ji9cC7ESlcoBHSY';

jwt.verify(broken_token, '123', function (err) {
expect(err.name).to.equal('JsonWebTokenError');
done();
});

var verify = jwt.verify.bind(null, broken_token, '123');
expect(verify).to.throw(JsonWebTokenError);
});


});
});
6 changes: 3 additions & 3 deletions test/issue_70.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ var jwt = require('../');

describe('issue 70 - public key start with BEING PUBLIC KEY', function () {

it('should work', function (done) {
it('should work', function () {
var fs = require('fs');
var cert_pub = fs.readFileSync(__dirname + '/rsa-public.pem');
var cert_priv = fs.readFileSync(__dirname + '/rsa-private.pem');

var token = jwt.sign({ foo: 'bar' }, cert_priv, { algorithm: 'RS256'});

jwt.verify(token, cert_pub, done);
jwt.verify(token, cert_pub);
});

});
});
68 changes: 21 additions & 47 deletions test/jwt.hs.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,68 +15,42 @@ describe('HS256', function() {
expect(token.split('.')).to.have.length(3);
});

it('should without options', function(done) {
var callback = function(err, decoded) {
assert.ok(decoded.foo);
assert.equal('bar', decoded.foo);
done();
};
callback.issuer = "shouldn't affect";
jwt.verify(token, secret, callback );
it('should validate with secret', function() {
var decoded = jwt.verify(token, secret);
assert.ok(decoded.foo);
assert.equal('bar', decoded.foo);
});

it('should validate with secret', function(done) {
jwt.verify(token, secret, function(err, decoded) {
assert.ok(decoded.foo);
assert.equal('bar', decoded.foo);
done();
});
it('should throw with invalid secret', function() {
var verify = jwt.verify.bind(null, token, 'invalid secret');
expect(verify).to.throw('invalid signature');
});

it('should throw with invalid secret', function(done) {
jwt.verify(token, 'invalid secret', function(err, decoded) {
assert.isUndefined(decoded);
assert.isNotNull(err);
done();
});
});

it('should throw with secret and token not signed', function(done) {
it('should throw with secret and token not signed', function() {
var signed = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'none' });
var unsigned = signed.split('.')[0] + '.' + signed.split('.')[1] + '.';
jwt.verify(unsigned, 'secret', function(err, decoded) {
assert.isUndefined(decoded);
assert.isNotNull(err);
done();
});
var verify = jwt.verify.bind(null, unsigned, 'secret');
expect(verify).to.throw('jwt signature is required');
});

it('should throw when verifying null', function(done) {
jwt.verify(null, 'secret', function(err, decoded) {
assert.isUndefined(decoded);
assert.isNotNull(err);
done();
});
it('should throw when verifying null', function() {
var verify = jwt.verify.bind(null, null, 'secret');
expect(verify).to.throw('jwt must be provided');
});

it('should return an error when the token is expired', function(done) {
it('should return an error when the token is expired', function() {
var token = jwt.sign({ exp: 1 }, secret, { algorithm: 'HS256' });
jwt.verify(token, secret, { algorithm: 'HS256' }, function(err, decoded) {
assert.isUndefined(decoded);
assert.isNotNull(err);
done();
});
var verify = jwt.verify.bind(null, token, secret, { algorithm: 'HS256' });
expect(verify).to.throw('jwt expired');
});

it('should NOT return an error when the token is expired with "ignoreExpiration"', function(done) {
it('should NOT return an error when the token is expired with "ignoreExpiration"', function() {
var token = jwt.sign({ exp: 1, foo: 'bar' }, secret, { algorithm: 'HS256' });
jwt.verify(token, secret, { algorithm: 'HS256', ignoreExpiration: true }, function(err, decoded) {
assert.ok(decoded.foo);
assert.equal('bar', decoded.foo);
assert.isNull(err);
done();
});
var decoded = jwt.verify(token, secret, { algorithm: 'HS256', ignoreExpiration: true });
assert.ok(decoded.foo);
assert.equal('bar', decoded.foo);
});

});

});
Loading