Skip to content

Commit

Permalink
Updating jwt.Attempt() to accept custom payload (#39)
Browse files Browse the repository at this point in the history
* fix(jwt): Allowed jwt.attempt() to accept an optional payload

With recent work on jwt.generate(), that function signature was updated to allow a user to push a
custom payload into the JWT that was created. Since jwt.attempt() uses jwt.generate() internally,
this fix just updates the jwt.attempt() method to allow also adding a custom payload

/issues/38

* test(jwt): JWT.attempt() test for updated method signature

Added a test for verifying JWT.attempt() works properly when you include a custom payload for the
token generation.
  • Loading branch information
K3TH3R authored and thetutlage committed May 17, 2017
1 parent e7fe312 commit 3c4a2b4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Schemes/Jwt/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,13 @@ class JwtScheme extends BaseScheme {
*
* @return {String}
*/
* attempt (uid, password) {
* attempt (uid, password, customPayload) {
let payload = null
const user = yield this.validate(uid, password, true)
return yield this.generate(user)
if (customPayload) {
payload = typeof (customPayload.toJSON) === 'function' ? customPayload.toJSON() : customPayload
}
return yield (payload !== null) ? this.generate(user, payload) : this.generate(user)
}

}
Expand Down
31 changes: 31 additions & 0 deletions test/unit/authenticators/jwt.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -368,5 +368,36 @@ describe('Authenticators', function () {
User.where.restore()
User.first.restore()
})

it('should be able to generate a token when password matches with a custom payload', function * () {
class User extends Model {
static get primaryKey () {
return 'id'
}

static query () {
return this
}

static where () {
return this
}

static * first () {
return {password: 'secret', id: 1}
}
}
sinon.spy(User, 'query')
sinon.spy(User, 'where')
sinon.spy(User, 'first')
const sessionAuth = new JwtScheme(request, this.serializer, Config(User))
const token = yield sessionAuth.attempt('foo@bar.com', 'secret', {name: 'test'})
const verified = jwt.verify(token, Config(User).secret)
expect(verified.payload.uid).to.equal(1)
expect(verified.payload.data).to.deep.equal({name: 'test'})
User.query.restore()
User.where.restore()
User.first.restore()
})
})
})

0 comments on commit 3c4a2b4

Please sign in to comment.