@kinde-oss/kinde-auth-react
Version:
Kinde React SDK for authentication
2 lines (1 loc) • 6.16 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("./useKindeAuth-BD1u4rmN.cjs"),L=require("react/jsx-runtime"),r=require("./index-D_oWPEME.cjs"),i=require("react");var c=(o=>(o.domain="domain",o.clientId="client_id",o.audience="audience",o.redirectUri="redirect_uri",o.logoutUri="logout_uri",o.performingLogout="performing_logout",o))(c||{});const d=new r.Ie,v=new r.Ee;r.De(d);r.je(v);const T=o=>o||window.location.origin,G="5.6.0",F={version:G};r.c.keyPrefix="";const H=()=>{window.history.replaceState({},document.title,window.location.pathname)},q={onSuccess:H},z=({audience:o,scope:I,clientId:g,children:O,domain:f,useInsecureForRefreshToken:x=!1,redirectUri:m,callbacks:D={},logoutUri:S,forceChildrenRender:j=!1,popupOptions:R={}})=>{const s={...q,...D};r.S.framework="react",r.S.frameworkVersion=i.version,r.S.sdkVersion=F.version,r.c.useInsecureForRefreshToken=x;const[E,h]=i.useState({user:void 0,isAuthenticated:!1,isLoading:!0}),C=i.useRef(!1);i.useEffect(()=>{d.setItems({[c.domain]:f,[c.clientId]:g,[c.audience]:o,[c.redirectUri]:m,[c.logoutUri]:S})},[o,I,g,f,m,S]);const k=i.useCallback(async(e={})=>{const a=e.state||{};e.state=void 0;const t={audience:o,clientId:g,...e,supportsReauth:!0,state:r.j(JSON.stringify({kinde:{event:"login"},...a})),redirectURL:T(e.redirectURL||m)},n=await d.getSessionItem(c.domain),u=await r.Te(n,r.b.login,t);try{r.Ge({url:u.url.toString(),popupOptions:R,handleResult:P})}catch(w){s.onError?.({error:"ERR_POPUP",errorDescription:w.message},{},{})}},[o,g,m,R,s]),U=i.useCallback(async(e={})=>{const a=e.state||{};e.state=void 0;const t={...e,state:r.j(JSON.stringify({kinde:{event:"register"},...a})),supportsReauth:!0,audience:await d.getSessionItem(c.audience),clientId:await d.getSessionItem(c.clientId),redirectURL:T(e?.redirectURL||m),prompt:r.H.create};try{const n=await d.getSessionItem(c.domain),u=await r.Te(n,r.b.register,t);try{r.Ge({url:u.url.toString(),popupOptions:R,handleResult:P})}catch(w){s.onError?.({error:"ERR_POPUP",errorDescription:w.message},{},{})}}catch(n){console.error("Register error:",n),s.onError?.({error:"ERR_REGISTER",errorDescription:String(n)},{},l)}},[m,R,s]),p=i.useCallback(async e=>{try{const a=await d.getSessionItem(c.domain),t=new URLSearchParams;e?e&&typeof e=="string"?t.append("redirect",e):typeof e=="object"&&((e.redirectUrl||S)&&t.append("redirect",e.redirectUrl||S||""),e.allSessions&&t.append("all_sessions",String(e.allSessions))):t.append("redirect",S||""),h(n=>({...n,user:void 0,isAuthenticated:!1})),await Promise.all([d.removeSessionItem(r.i.idToken),d.removeSessionItem(r.i.accessToken),d.removeSessionItem(r.i.refreshToken),v.removeSessionItem(r.i.refreshToken)]),await v.setSessionItem(c.performingLogout,"true");try{await r.Ge({url:`${a}/logout?${t.toString()}`,popupOptions:R})}catch(n){s.onError?.({error:"ERR_POPUP",errorDescription:n.message},{},{})}}catch(a){console.error("Logout error:",a),s.onError?.({error:"ERR_LOGOUT",errorDescription:String(a)},{},l)}},[]),l=i.useMemo(()=>({login:k,logout:p,register:U,getIdToken:async()=>await r.y()?.getSessionItem(r.i.idToken),getAccessToken:async()=>await r.y()?.getSessionItem(r.i.accessToken),getToken:async()=>await r.y()?.getSessionItem(r.i.accessToken),getClaim:async(e,a)=>r.M(e,a),getClaims:async(...e)=>r.W(...e),getOrganization:async()=>await r.be(),getCurrentOrganization:async()=>await r.be(),getFlag:async e=>await r.Re(e),getUserProfile:async()=>r.Le(),getPermission:async e=>await r.ze(e),getPermissions:async()=>r.oe(),getUserOrganizations:async()=>await r.Fe(),getRoles:async()=>await r.ce(),generatePortalUrl:async e=>await r._e({domain:f,returnUrl:e.returnUrl||window.location.href,subNav:e.subNav}),refreshToken:async(...e)=>await r.x(...e),...E}),[E,k,p,U]),y=i.useCallback(e=>{s.onEvent&&s.onEvent("tokenRefreshed",e,l)},[s,l]),P=i.useCallback(async e=>{const a=atob(e.get("state")||"");let t,n;try{t=JSON.parse(a),n=Object.assign(t.kinde||{event:r.H.login})}catch(u){console.error("Error parsing state:",u),s.onError?.({error:"ERR_STATE_PARSE",errorDescription:String(u)},{},l),t={},n={event:"login"}}try{const u=await r.xe({urlParams:e,domain:f,clientId:g,redirectURL:T(m),autoRefresh:!0,onRefresh:y});if(u.success){const w=await r.Le();w&&(h(N=>({...N,user:w,isAuthenticated:!0})),s.onSuccess?.(w,{...t,kinde:void 0},l),s.onEvent&&s.onEvent(n.event,{...t,kinde:void 0},l))}else s.onError?.({error:"ERR_CODE_EXCHANGE",errorDescription:u.error},t,l)}catch(u){s.onError?.({error:"ERR_POPUP_AUTH",errorDescription:String(u)},t,l)}finally{h(u=>({...u,isLoading:!1}))}},[f,g,m,y,s,l]),b=i.useCallback(()=>{document.visibilityState==="visible"&&E.isAuthenticated&&r.x({domain:f,clientId:g,onRefresh:y}).catch(e=>{console.error("Error refreshing token:",e)})},[E.isAuthenticated,f,g,y]);i.useEffect(()=>(document.removeEventListener("visibilitychange",b),document.addEventListener("visibilitychange",b),()=>{document.removeEventListener("visibilitychange",b)}),[b]);const A=i.useCallback(async()=>{if(C.current)return;await r.Ce({domain:f,clientId:g}),C.current=!0;const e=new URLSearchParams(window.location.search);if(e.has("error")){if(e.get("error")?.toLowerCase()==="login_link_expired"){const n=e.get("reauth_state");n&&k({reauthState:n});return}h(n=>({...n,isLoading:!1}));return}if(await v.getSessionItem(c.performingLogout)==="true"&&(await v.removeSessionItem(c.performingLogout),window.close()),!e.has("code")){try{const t=await r.Le();t&&h(n=>({...n,user:t,isAuthenticated:!0}))}catch(t){console.warn("Error getting user profile",t)}finally{h(t=>({...t,isLoading:!1}))}return}if(window.opener){const t=new URLSearchParams(window.location.search);window.opener.postMessage({type:"KINDE_AUTH_RESULT",result:Object.fromEntries(t.entries())},window.location.origin),window.close()}await P(new URLSearchParams(window.location.search))},[g,f,m,s,l,y,k,P]);return i.useEffect(()=>{const e={current:!0};return e.current&&A(),()=>{e.current=!1}},[A]),j||C.current?L.jsx(_.KindeContext.Provider,{value:l,children:O}):L.jsx(L.Fragment,{})};exports.KindeContext=_.KindeContext;exports.useKindeAuth=_.useKindeAuth;exports.KindeProvider=z;