forked from itspoma/joi-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (40 loc) · 1.08 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
'use strict';
const jsonwebtoken = require('jsonwebtoken');
module.exports = (joi) => ({
name: 'jwt',
base: joi.string(),
language: {
valid: 'is invalid',
expired: 'has expired'
},
rules: [{
name: 'valid',
params: {
options: joi.object({
secret: joi.string(),
expiration: joi.any()
})
},
description: function (params) {
return 'Token should be valid'
},
setup: function (params) {
this._flags.secret = params.options.secret
},
validate: function (params, value, state, options) {
if (!/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*$/.test(value)) {
return this.createError('jwt.valid', { value }, state, options);
}
let decoded;
try {
decoded = jsonwebtoken.verify(value, params.options.secret)
} catch (err) {
if (err.name === 'TokenExpiredError') {
return this.createError('jwt.expired', { value }, state, options)
}
return this.createError('jwt.valid', { value }, state, options)
}
return decoded;
}
}]
})