UNPKG

react-jwt

Version:

Small library for decoding json web tokens (JWT)

2 lines (1 loc) 1.88 kB
(function(c,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],i):(c=typeof globalThis<"u"?globalThis:c||self,i(c["react-jwt"]={},c.react))})(this,(function(c,i){"use strict";const d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=new Map;for(let e=0;e<d.length;e++){let t=e.toString(2);const n=6-t.length;t="0".repeat(n)+t,a.set(d.charCodeAt(e),t)}function p(e){let t="";for(let r=0;r<e.length;r++)t+=a.get(e.charCodeAt(r));t=t.slice(0,t.length-t.length%8);const n=[];for(let r=0;r<t.length/8;r++)n.push(t.slice(r*8,r*8+8));return n}function h(e){return e=e.replaceAll("=",""),e=e.replaceAll("-","+"),e=e.replaceAll("_","/"),p(e).map(n=>parseInt(n,2))}function g(e){let t="",n;const r=e.length;for(let o=0;o<r;o++)n=e[o],t+=String.fromCodePoint(n>251&&n<254&&o+5<r?(n-252)*1073741824+(e[++o]-128<<24)+(e[++o]-128<<18)+(e[++o]-128<<12)+(e[++o]-128<<6)+e[++o]-128:n>247&&n<252&&o+4<r?(n-248<<24)+(e[++o]-128<<18)+(e[++o]-128<<12)+(e[++o]-128<<6)+e[++o]-128:n>239&&n<248&&o+3<r?(n-240<<18)+(e[++o]-128<<12)+(e[++o]-128<<6)+e[++o]-128:n>223&&n<240&&o+2<r?(n-224<<12)+(e[++o]-128<<6)+e[++o]-128:n>191&&n<224&&o+1<r?(n-192<<6)+e[++o]-128:n);return t}function l(e){try{if(typeof e!="string"||e.split(".").length!==3)return null;const t=e.split(".")[1],n=h(t),r=g(n);return JSON.parse(r)}catch(t){return console.error("There was an error decoding token: ",t),null}}function u(e){const t=l(e);let n=!0;if(t&&t.exp){const r=new Date(0);r.setUTCSeconds(t.exp),n=r.valueOf()<new Date().valueOf()}return n}function T(e){const[t,n]=i.useState(!1),[r,o]=i.useState(null);i.useEffect(()=>{s(e)},[e]);const s=f=>{o(l(f)),n(u(f))};return{isExpired:t,decodedToken:r,reEvaluateToken:s}}c.decodeToken=l,c.isExpired=u,c.useJwt=T,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})}));