Skip to content

Commit 9414fbc

Browse files
author
Luke William Westby
committedSep 27, 2015
added async signing
1 parent 6a715a1 commit 9414fbc

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed
 

‎index.js

+11-4
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ JWT.decode = function (jwt, options) {
3535
return payload;
3636
};
3737

38-
JWT.sign = function(payload, secretOrPrivateKey, options) {
38+
JWT.sign = function(payload, secretOrPrivateKey, options, callback) {
3939
options = options || {};
4040

4141
var header = {};
@@ -79,9 +79,16 @@ JWT.sign = function(payload, secretOrPrivateKey, options) {
7979
encoding = options.encoding;
8080
}
8181

82-
var signed = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
83-
84-
return signed;
82+
if(typeof callback === 'function') {
83+
jws.createSign({
84+
header: header,
85+
payload: payload,
86+
privateKey: secretOrPrivateKey,
87+
payload: JSON.stringify(payload)
88+
}).on('done', callback);
89+
} else {
90+
return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
91+
}
8592
};
8693

8794
JWT.verify = function(jwtString, secretOrPublicKey, options, callback) {

‎test/async_sign.tests.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var jwt = require('../index');
2+
3+
var expect = require('chai').expect;
4+
5+
describe('signing a token asynchronously', function() {
6+
7+
describe('when signing a token', function() {
8+
var secret = 'shhhhhh';
9+
var syncToken = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'HS256' });
10+
11+
it('should return the same result as singing synchronously', function(done) {
12+
jwt.sign({ foo: 'bar' }, secret, { algorithm: 'HS256' }, function (asyncToken) {
13+
expect(asyncToken).to.be.a('string');
14+
expect(asyncToken.split('.')).to.have.length(3);
15+
expect(asyncToken).to.equal(syncToken);
16+
done();
17+
});
18+
});
19+
});
20+
});

0 commit comments

Comments
 (0)
Please sign in to comment.