Skip to content

Commit

Permalink
added async signing
Browse files Browse the repository at this point in the history
  • Loading branch information
Luke William Westby committed Sep 27, 2015
1 parent 6a715a1 commit 9414fbc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
15 changes: 11 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ JWT.decode = function (jwt, options) {
return payload;
};

JWT.sign = function(payload, secretOrPrivateKey, options) {
JWT.sign = function(payload, secretOrPrivateKey, options, callback) {
options = options || {};

var header = {};
Expand Down Expand Up @@ -79,9 +79,16 @@ JWT.sign = function(payload, secretOrPrivateKey, options) {
encoding = options.encoding;
}

var signed = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});

return signed;
if(typeof callback === 'function') {
jws.createSign({
header: header,
payload: payload,
privateKey: secretOrPrivateKey,
payload: JSON.stringify(payload)
}).on('done', callback);
} else {
return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
}
};

JWT.verify = function(jwtString, secretOrPublicKey, options, callback) {
Expand Down
20 changes: 20 additions & 0 deletions test/async_sign.tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var jwt = require('../index');

var expect = require('chai').expect;

describe('signing a token asynchronously', function() {

describe('when signing a token', function() {
var secret = 'shhhhhh';
var syncToken = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'HS256' });

it('should return the same result as singing synchronously', function(done) {
jwt.sign({ foo: 'bar' }, secret, { algorithm: 'HS256' }, function (asyncToken) {
expect(asyncToken).to.be.a('string');
expect(asyncToken.split('.')).to.have.length(3);
expect(asyncToken).to.equal(syncToken);
done();
});
});
});
});

0 comments on commit 9414fbc

Please sign in to comment.