forked from koajs/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (46 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var assert = require('assert');
var thunkify = require('thunkify');
var _JWT = require('jsonwebtoken');
// Make verify function play nice with co/koa
var JWT = {decode: _JWT.decode, sign: _JWT.sign, verify: thunkify(_JWT.verify)};
module.exports = function(opts) {
opts = opts || {};
opts.key = opts.key || 'user';
assert(opts.secret, '"secret" option is required');
return function *jwt(next) {
var token, msg, user, parts, scheme, credentials;
if (this.header.authorization) {
parts = this.header.authorization.split(' ');
if (parts.length == 2) {
scheme = parts[0];
credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
token = credentials;
}
} else {
if (!opts.passthrough) {
this.throw(401, 'Bad Authorization header format. Format is "Authorization: Bearer <token>"\n');
}
}
} else {
if (!opts.passthrough) {
this.throw(401, 'No Authorization header found\n');
}
}
try {
user = yield JWT.verify(token, opts.secret, opts);
} catch(e) {
msg = 'Invalid token' + (opts.debug ? ' - ' + e.message + '\n' : '\n');
}
if (user || opts.passthrough) {
this[opts.key] = user;
yield next;
} else {
this.throw(401, msg);
}
};
};
// Export JWT methods as a convenience
module.exports.sign = JWT.sign;
module.exports.verify = JWT.verify;
module.exports.decode = JWT.decode;