|
| 1 | +const fromPairs = require('lodash/fromPairs') |
| 2 | + |
| 3 | + |
| 4 | +function getToken(key) { |
| 5 | + return readCookie(key) |
| 6 | +} |
| 7 | + |
| 8 | + |
| 9 | +function decodeToken(token) { |
| 10 | + const parts = token.split('.') |
| 11 | + |
| 12 | + if (parts.length !== 3) { |
| 13 | + throw new Error('The token is invalid') |
| 14 | + } |
| 15 | + |
| 16 | + const decoded = urlBase64Decode(parts[1]) |
| 17 | + |
| 18 | + if (!decoded) { |
| 19 | + throw new Error('Cannot decode the token') |
| 20 | + } |
| 21 | + |
| 22 | + // covert base64 token in JSON object |
| 23 | + let t = JSON.parse(decoded) |
| 24 | + |
| 25 | + // tweaking for custom claim for RS256 |
| 26 | + t.userId = _.parseInt(_.find(t, (value, key) => { |
| 27 | + return (key.indexOf('userId') !== -1) |
| 28 | + })) |
| 29 | + t.handle = _.find(t, (value, key) => { |
| 30 | + return (key.indexOf('handle') !== -1) |
| 31 | + }) |
| 32 | + t.roles = _.find(t, (value, key) => { |
| 33 | + return (key.indexOf('roles') !== -1) |
| 34 | + }) |
| 35 | + |
| 36 | + return t |
| 37 | +} |
| 38 | + |
| 39 | +function isTokenExpired(token, offsetSeconds = 0) { |
| 40 | + const d = getTokenExpirationDate(token) |
| 41 | + |
| 42 | + if (d === null) { |
| 43 | + return false |
| 44 | + } |
| 45 | + |
| 46 | + // Token expired? |
| 47 | + return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000))) |
| 48 | +} |
| 49 | + |
| 50 | +function urlBase64Decode(str) { |
| 51 | + let output = str.replace(/-/g, '+').replace(/_/g, '/') |
| 52 | + |
| 53 | + switch (output.length % 4) { |
| 54 | + case 0: |
| 55 | + break |
| 56 | + |
| 57 | + case 2: |
| 58 | + output += '==' |
| 59 | + break |
| 60 | + |
| 61 | + case 3: |
| 62 | + output += '=' |
| 63 | + break |
| 64 | + |
| 65 | + default: |
| 66 | + throw 'Illegal base64url string!' |
| 67 | + } |
| 68 | + return decodeURIComponent(escape(atob(output))) //polyfill https://github.com/davidchambers/Base64.js |
| 69 | +} |
| 70 | + |
| 71 | +function getTokenExpirationDate(token) { |
| 72 | + const decoded = decodeToken(token) |
| 73 | + |
| 74 | + if (typeof decoded.exp === 'undefined') { |
| 75 | + return null |
| 76 | + } |
| 77 | + |
| 78 | + const d = new Date(0) // The 0 here is the key, which sets the date to the epoch |
| 79 | + d.setUTCSeconds(decoded.exp) |
| 80 | + |
| 81 | + return d |
| 82 | +} |
| 83 | + |
| 84 | +function parseCookie(cookie) { |
| 85 | + return fromPairs(cookie.split(';').map((pair) => pair.split('=').map((part) => part.trim()))) |
| 86 | +} |
| 87 | + |
| 88 | +function readCookie(name) { |
| 89 | + return parseCookie(document.cookie)[name] |
| 90 | +} |
| 91 | + |
| 92 | + |
| 93 | +module.exports = { |
| 94 | + isTokenExpired, |
| 95 | + decodeToken, |
| 96 | + getToken |
| 97 | +} |
0 commit comments