@first-line/firstline-react
Version:
React Library for Firstline IDP
3 lines (2 loc) • 7.77 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).reactFirstline={},e.React)}(this,(function(e,t){"use strict";function n(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{s(o.next(e))}catch(e){i(e)}}function c(e){try{s(o.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}s((o=o.apply(e,t||[])).next())}))}function o(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(s){return function(c){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(n=1,o&&(r=2&c[0]?o.return:c[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,c[1])).done)return r;switch(o=0,r&&(c=[2&c[0],r.value]),c[0]){case 0:case 1:r=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,o=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(r=a.trys,(r=r.length>0&&r[r.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!r||c[1]>r[0]&&c[1]<r[3])){a.label=c[1];break}if(6===c[0]&&a.label<r[1]){a.label=r[1],r=c;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(c);break}r[2]&&a.ops.pop(),a.trys.pop();continue}c=t.call(e,a)}catch(e){c=[6,e],o=0}finally{n=r=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,s])}}}async function r(e){return function(e){for(var t="",n=new Uint8Array(e),o=n.byteLength,r=0;r<o;r++)t+=String.fromCharCode(n[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}(await async function(e){const t=(new TextEncoder).encode(e);return window.crypto.subtle.digest("SHA-256",t)}(e))}function i(e){return Object.entries(e).filter((([e,t])=>t&&"undefined"!==t&&"null"!==t)).map((([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join("&")}function a(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.",n=window.crypto.getRandomValues(new Uint8Array(e));let o="";return n.forEach((e=>o+=t[e%65])),o}class c{constructor(e){this.options=e,this.serverUrl=e.domain.includes("localhost")?`http://${e.domain}`:`https://${e.domain}`}async loginRedirect(e){var t,n,o;const c=a(43),s={grant_type:"authorization_code",response_type:"code",response_mode:"query",audience:this.options.audience,client_id:this.options.client_id,redirect_uri:null!==(t=null==e?void 0:e.redirect_uri)&&void 0!==t?t:this.options.redirect_uri,state:null!==(n=null==e?void 0:e.state)&&void 0!==n?n:a(64),code_challenge:await r(c),action_hint:null!==(o=null==e?void 0:e.action_hint)&&void 0!==o?o:"login"},u=i(s);window.localStorage.setItem("state",s.state),window.localStorage.setItem("code_verifier",c),window.location.assign(`${this.serverUrl}/api/v3/authorize?${u}`)}async verifyRedirect(){window.location.assign(`${this.serverUrl}/ui/mail-confirmation?redirect_uri=${encodeURIComponent(this.options.redirect_uri)}`)}async exchangeAuthorizationCode(e,t,n){const o=i({grant_type:"authorization_code",code:e,client_id:this.options.client_id,code_verifier:t,redirect_uri:this.options.redirect_uri,state:n});return await fetch(`${this.serverUrl}/api/v3/oauth/token?${o}`,{method:"post"}).then((e=>e.json()))}async exchangeRefreshToken(e){const t=i({grant_type:"refresh_token",refresh_token:e,client_id:this.options.client_id});return await fetch(`${this.serverUrl}/api/v3/oauth/token?${t}`,{method:"post"}).then((e=>e.json()))}async logout(){var e;window.localStorage.removeItem("refresh_token");const t=i({client_id:this.options.client_id,logout_uri:null!==(e=this.options.logout_uri)&&void 0!==e?e:this.options.redirect_uri});window.location.assign(`${this.serverUrl}/api/v3/logout?${t}`)}async doExchangeCode(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),o=window.localStorage.getItem("state"),r=window.localStorage.getItem("code_verifier");if(t&&n&&o&&r&&n===o){const e=await this.exchangeAuthorizationCode(t,r,n);return window.localStorage.removeItem("state"),window.localStorage.removeItem("code_verifier"),window.localStorage.setItem("refresh_token",e.refresh_token),window.history.pushState("object or string","Title","/"+window.location.href.substring(window.location.href.lastIndexOf("/")+1).split("?")[0]),e}return null}async doRefresh(){const e=window.localStorage.getItem("refresh_token");if(e){const t=await this.exchangeRefreshToken(e);if(t.refresh_token)return window.localStorage.setItem("refresh_token",t.refresh_token),t;window.localStorage.removeItem("refresh_token")}return null}async doExchangeOrRefresh(){let e=await this.doRefresh();return e||(e=await this.doExchangeCode()),e}getUser(e){return(null==e?void 0:e.id_token)?function(e){const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(window.atob(t).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(n)}(e.id_token):null}isEmailVerified(e){return!!this.getUser(e).is_verified}}var s=function(){throw new Error("You need to wrap your components with <FirstlineProvider>")},u={getTokens:s,getAccessToken:s,loginWithRedirect:s,verifyEmail:s,logout:s,doRefresh:s,doExchangeOrRefresh:s,isAuthenticated:!1,isLoading:!0,user:void 0,isEmailVerified:!1},l=t.createContext(u);e.FirstlineClient=c,e.FirstlineProvider=function(e){var r=t.useState((function(){return new c(e.clientOptions)}))[0],i=t.useState(!0),a=i[0],s=i[1],u=t.useState(void 0),d=u[0],f=u[1],h=t.useState(void 0),p=h[0],v=h[1],w=t.useState(void 0),g=w[0],_=w[1],m=t.useCallback((function(e){return r.loginRedirect(e)}),[r]),y=t.useCallback((function(){return r.verifyRedirect()}),[r]),b=t.useCallback((function(e,t,n){return r.exchangeAuthorizationCode(e,t,n)}),[r]),k=t.useCallback((function(){return r.logout()}),[r]),C=t.useCallback((function(){return r.doRefresh()}),[r]),S=t.useCallback((function(e){return r.getUser(e)}),[r]),x=t.useCallback((function(e){return r.isEmailVerified(e)}),[r]),R=t.useCallback((function(e){return void 0===e&&(e=!1),n(void 0,void 0,void 0,(function(){var t;return o(this,(function(n){switch(n.label){case 0:return a&&!e?[3,2]:(s(!0),[4,r.doExchangeOrRefresh()]);case 1:return t=n.sent(),f(t),[2,t];case 2:return[2]}}))}))}),[d,r,a,s,f]),E=t.useCallback((function(){return n(void 0,void 0,void 0,(function(){var e;return o(this,(function(t){switch(t.label){case 0:return null==d?[3,1]:(e=d,[3,3]);case 1:return[4,R()];case 2:e=t.sent(),t.label=3;case 3:return[2,e]}}))}))}),[d,R]),I=t.useCallback((function(e){return void 0===e&&(e=!0),n(void 0,void 0,void 0,(function(){var t;return o(this,(function(n){switch(n.label){case 0:return(null==d?void 0:d.access_token)&&e&&1e3*function(e){try{return JSON.parse(atob(e.split(".")[1]))}catch(e){return null}}(d.access_token).exp>=Date.now()||d?[2,d.access_token]:[3,1];case 1:return[4,R()];case 2:return[2,null==(t=n.sent())?void 0:t.access_token]}}))}))}),[d,R]);t.useEffect((function(){R(!0).catch((function(e){}))}),[]),t.useEffect((function(){if(void 0!==d)if(null==d?void 0:d.id_token){var e=S(d);v(e);var t=x(d);_(t),s(!1)}else s(!1)}),[d]);var U=t.useMemo((function(){return{getTokens:E,getAccessToken:I,loginWithRedirect:m,verifyEmail:y,logout:k,doRefresh:C,doExchangeOrRefresh:R,isAuthenticated:!!p,isLoading:a,user:p,isEmailVerified:g}}),[E,I,m,b,y,k,C,R,d,a,p,g]);return t.createElement(l.Provider,{value:U},e.children)},e.useFirstline=function(){return t.useContext(l)}}));
//# sourceMappingURL=firstline-react.min.js.map