UNPKG

762 BJavaScriptView Raw
1const base64url = require('../help/base64url')
2const errors = require('../errors')
3
4module.exports = (token, { complete = false } = {}) => {
5 if (typeof token !== 'string' || !token) {
6 throw new TypeError('JWT must be a string')
7 }
8
9 const { 0: header, 1: payload, 2: signature, length } = token.split('.')
10
11 if (length === 5) {
12 throw new TypeError('JWTs must be decrypted first')
13 }
14
15 if (length !== 3) {
16 throw new errors.JWTMalformed('JWTs must have three components')
17 }
18
19 try {
20 const result = {
21 header: base64url.JSON.decode(header),
22 payload: base64url.JSON.decode(payload),
23 signature
24 }
25
26 return complete ? result : result.payload
27 } catch (err) {
28 throw new errors.JWTMalformed('JWT is malformed')
29 }
30}