@kinde-oss/kinde-auth-react
Version:
Kinde React SDK for authentication
2 lines (1 loc) • 8.9 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("./useKindeAuth-DzGXYhS9.cjs"),x=require("react/jsx-runtime"),e=require("./utils.cjs"),u=require("react");var _=(o=>(o.performingLogout="performing_logout",o))(_||{});const V=new e.MemoryStorage,T=new e.LocalStorage;e.setActiveStorage(V);e.setInsecureStorage(T);const D=o=>o||window.location.origin,B="5.10.1",Q={version:B};var j=(o=>(o.preWarning="preWarning",o.timeout="timeout",o))(j||{});e.storageSettings.keyPrefix="";const Y=()=>{window.history.replaceState({},document.title,window.location.pathname)},Z={onSuccess:Y},I=()=>{try{const o=window.opener;return!o||o.closed?!1:o.location.origin===window.location.origin}catch{return!1}},ee=(o,{skipInitial:v=!1}={})=>{const l=u.useRef(!0);u.useEffect(()=>{const k=()=>{if(v&&l.current){l.current=!1;return}o(window.location)},a=()=>k();window.addEventListener("popstate",a),window.addEventListener("hashchange",a);const p=history.pushState,g=history.replaceState;return history.pushState===p&&(history.pushState=function(...R){p.apply(this,R),k()}),history.replaceState===g&&(history.replaceState=function(...R){g.apply(this,R),k()}),()=>{window.removeEventListener("popstate",a),window.removeEventListener("hashchange",a),history.pushState=p,history.replaceState=g}},[o,v])},te=({audience:o,scope:v,clientId:l,children:k,domain:a,useInsecureForRefreshToken:p=!1,redirectUri:g,callbacks:R={},logoutUri:A,forceChildrenRender:H=!1,popupOptions:y={},store:w=V,activityTimeout:S,refreshOnFocus:b=!1})=>{const i={...Z,...R},[E,N]=u.useState(!1),[m,h]=u.useState({user:void 0,isAuthenticated:!1,isLoading:!0}),X=u.useCallback(t=>{E&&S&&m.isAuthenticated&&e.updateActivityTimestamp()},[E,S,m.isAuthenticated]);ee(X,S?{}:{skipInitial:!0}),u.useEffect(()=>{e.setActiveStorage(w);const t=()=>{if(!(!S||E)){e.storageSettings.activityTimeoutMinutes=S.timeoutMinutes,e.storageSettings.activityTimeoutPreWarningMinutes=S.preWarningMinutes,e.storageSettings.onActivityTimeout=async(r,n)=>{try{if(r===j.timeout){const f=n?.accessToken,O=n?.refreshToken,F=async(q,J)=>{if(!q)return;const G=await fetch(`${a}/oauth2/revoke`,{method:"POST",body:`token=${encodeURIComponent(q)}&client_id=${encodeURIComponent(l)}&token_type_hint=${J}`,headers:{"Content-Type":"application/x-www-form-urlencoded"}});G.ok||console.warn(`Failed to revoke ${J}:`,G.status)};await Promise.allSettled([F(f,"access_token"),F(O,"refresh_token")])}}catch(f){console.error("Failed to logout:",f)}finally{S.onTimeout?.(r)}};try{e.updateActivityTimestamp()}catch(r){console.error("Failed to update activity timestamp:",r);return}N(!0)}},s=()=>{E&&(e.storageSettings.activityTimeoutMinutes=void 0,e.storageSettings.activityTimeoutPreWarningMinutes=void 0,e.storageSettings.onActivityTimeout=void 0,N(!1))},c=w.subscribe(async()=>{try{const[r,n]=await Promise.all([e.isAuthenticated(),e.getUserProfile()]);r&&n?(t(),h(f=>({...f,user:n,isAuthenticated:!0}))):(s(),h(f=>({...f,user:void 0,isAuthenticated:!1})))}catch(r){console.error("Store subscription update failed:",r),s(),h(n=>({...n,user:void 0,isAuthenticated:!1}))}});return()=>{c(),s()}},[w,S,E]),e.frameworkSettings.framework="react",e.frameworkSettings.frameworkVersion=u.version,e.frameworkSettings.sdkVersion=Q.version,e.storageSettings.useInsecureForRefreshToken=p;const K=u.useRef(!1),C=u.useCallback(async(t={})=>{const s=t.state||{};t.state=void 0;const c={audience:o,clientId:l,...t,supportsReauth:!0,scope:v?.split(" "),state:e.base64UrlEncode(JSON.stringify({kinde:{event:"login"},...s})),redirectURL:D(t.redirectURL||g)},r=await e.generateAuthUrl(a,e.IssuerRouteTypes.login,c);try{e.navigateToKinde({url:r.url.toString(),popupOptions:y,handleResult:L})}catch(n){i.onError?.({error:"ERR_POPUP",errorDescription:n.message},{},{})}},[o,l,g,y,i,a,v]),$=u.useCallback(async(t={})=>{const s=t.state||{};t.state=void 0;const c={...t,state:e.base64UrlEncode(JSON.stringify({kinde:{event:"register"},...s})),supportsReauth:!0,audience:o,clientId:l,redirectURL:D(t?.redirectURL||g),prompt:e.PromptTypes.create};try{const r=await e.generateAuthUrl(a,e.IssuerRouteTypes.register,c);try{e.navigateToKinde({url:r.url.toString(),popupOptions:y,handleResult:L})}catch(n){i.onError?.({error:"ERR_POPUP",errorDescription:n.message},{},{})}}catch(r){console.error("Register error:",r),i.onError?.({error:"ERR_REGISTER",errorDescription:String(r)},{},d)}},[g,y,i,o,l,a]),z=u.useCallback(async t=>{try{const s=new URLSearchParams;t?t&&typeof t=="string"?s.append("redirect",t):typeof t=="object"&&((t.redirectUrl||A)&&s.append("redirect",t.redirectUrl||A||""),t.allSessions&&s.append("all_sessions",String(t.allSessions))):s.append("redirect",A||""),await Promise.all([w.removeSessionItem(e.StorageKeys.idToken),w.removeSessionItem(e.StorageKeys.accessToken),w.removeSessionItem(e.StorageKeys.refreshToken),T.removeSessionItem(e.StorageKeys.refreshToken)]),h(c=>({...c,user:void 0,isAuthenticated:!1})),await T.setSessionItem(_.performingLogout,"true");try{await e.navigateToKinde({url:`${a}/logout?${s.toString()}`,popupOptions:y})}catch(c){i.onError?.({error:"ERR_POPUP",errorDescription:c.message},{},{})}}catch(s){console.error("Logout error:",s),i.onError?.({error:"ERR_LOGOUT",errorDescription:String(s)},{},d)}},[w,y,i,A,a]),d=u.useMemo(()=>({login:C,logout:z,register:$,getIdToken:async()=>await e.getActiveStorage()?.getSessionItem(e.StorageKeys.idToken),getAccessToken:async()=>await e.getActiveStorage()?.getSessionItem(e.StorageKeys.accessToken),getToken:async()=>await e.getActiveStorage()?.getSessionItem(e.StorageKeys.accessToken),getClaim:async(t,s)=>e.getClaim(t,s),getClaims:async(...t)=>e.getClaims(...t),getOrganization:async()=>await e.getCurrentOrganization(),getCurrentOrganization:async()=>await e.getCurrentOrganization(),getFlag:async t=>await e.getFlag(t),getUserProfile:e.getUserProfile,getPermission:async t=>await e.getPermission(t),getPermissions:async()=>e.getPermissions(),getUserOrganizations:async()=>await e.getUserOrganizations(),getRoles:async()=>await e.getRoles(),generatePortalUrl:async t=>await e.generatePortalUrl({domain:a,returnUrl:t.returnUrl||window.location.href,subNav:t.subNav}),refreshToken:async(...t)=>await e.refreshToken(...t),...m}),[m,C,z,$]),P=u.useCallback(t=>{i.onEvent&&i.onEvent("tokenRefreshed",t,d)},[i,d]),L=u.useCallback(async t=>{const s=atob(t.get("state")||"");let c,r;try{c=JSON.parse(s),r=Object.assign(c.kinde||{event:e.PromptTypes.login})}catch(n){console.error("Error parsing state:",n),i.onError?.({error:"ERR_STATE_PARSE",errorDescription:String(n)},{},d),c={},r={event:"login"}}try{const n=await e.exchangeAuthCode({urlParams:t,domain:a,clientId:l,redirectURL:D(g),autoRefresh:!0,onRefresh:P});if(n.success){const f=await e.getUserProfile();f&&(h(O=>({...O,user:f,isAuthenticated:!0})),i.onSuccess?.(f,{...c,kinde:void 0},d),i.onEvent&&i.onEvent(r.event,{...c,kinde:void 0},d))}else i.onError?.({error:"ERR_CODE_EXCHANGE",errorDescription:n.error},c,d)}catch(n){i.onError?.({error:"ERR_POPUP_AUTH",errorDescription:String(n)},c,d)}finally{h(n=>({...n,isLoading:!1}))}},[a,l,g,P,i,d]),U=u.useCallback(()=>{document.visibilityState==="visible"&&m.isAuthenticated&&b&&e.refreshToken({domain:a,clientId:l,onRefresh:P}).catch(t=>{console.error("Error refreshing token:",t)})},[m.isAuthenticated,a,l,P,b]);u.useEffect(()=>{if(document.removeEventListener("visibilitychange",U),b)return document.addEventListener("visibilitychange",U),()=>{document.removeEventListener("visibilitychange",U)}},[U,b]);const W=u.useCallback(async()=>{if(!K.current)try{try{K.current=!0,await e.checkAuth({domain:a,clientId:l})}catch(r){console.warn("checkAuth failed:",r),h(n=>({...n,isLoading:!1}))}const t=new URLSearchParams(window.location.search);if(t.has("error")){if(t.get("error")?.toLowerCase()==="login_link_expired"){const n=t.get("reauth_state");n&&C({reauthState:n});return}h(n=>({...n,isLoading:!1}));return}await T.getSessionItem(_.performingLogout)==="true"&&(await T.removeSessionItem(_.performingLogout),I()&&window.close());const s=t.has("code"),c=window.location.href.startsWith(g);if(!s||!c){try{const r=await e.getUserProfile();r&&h(n=>({...n,user:r,isAuthenticated:!0}))}catch(r){console.warn("Error getting user profile",r)}finally{h(r=>({...r,isLoading:!1}))}return}if(I()){const r=new URLSearchParams(window.location.search);window.opener.postMessage({type:"KINDE_AUTH_RESULT",result:Object.fromEntries(r.entries())},window.location.origin),window.close();return}await L(new URLSearchParams(window.location.search))}finally{I()&&window.close()}},[l,a,g,i,d,P,C,L]);return u.useEffect(()=>{const t={current:!0};return t.current&&W(),()=>{t.current=!1}},[W]),H||K.current?x.jsx(M.KindeContext.Provider,{value:d,children:k}):x.jsx(x.Fragment,{})};exports.KindeContext=M.KindeContext;exports.useKindeAuth=M.useKindeAuth;exports.KindeProvider=te;exports.TimeoutActivityType=j;