UNPKG

@kinde-oss/kinde-auth-react

Version:

Kinde React SDK for authentication

2 lines (1 loc) 5.22 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("./useKindeAuth-BD1u4rmN.cjs"),b=require("react/jsx-runtime"),t=require("./index-Cex2voa3.cjs"),o=require("react");var i=(s=>(s.domain="domain",s.clientId="client_id",s.audience="audience",s.redirectUri="redirect_uri",s.logoutUri="logout_uri",s))(i||{});const f=new t.ae,T=new t.ie;t._e(f);t.ye(T);const L=s=>s||window.location.origin,K="5.5.0",q={version:K};t.c.keyPrefix="";const F=()=>{window.history.replaceState({},document.title,window.location.pathname)},J={onSuccess:F},$=({audience:s,scope:O,clientId:l,children:I,domain:h,useInsecureForRefreshToken:x=!1,redirectUri:m,callbacks:N={},logoutUri:S,forceChildrenRender:j=!1})=>{const c={...J,...N};t._.framework="react",t._.frameworkVersion=o.version,t._.sdkVersion=q.version,t.c.useInsecureForRefreshToken=x;const[v,w]=o.useState({user:void 0,isAuthenticated:!1,isLoading:!0}),E=o.useRef(!1);o.useEffect(()=>{f.setItems({[i.domain]:h,[i.clientId]:l,[i.audience]:s,[i.redirectUri]:m,[i.logoutUri]:S})},[s,O,l,h,m,S]);const p=o.useCallback(async(e={})=>{const r=e.state||{};e.state=void 0;const a={audience:s,clientId:l,...e,supportsReauth:!0,state:t.L(JSON.stringify({kinde:{event:"login"},...r})),redirectURL:L(e.redirectURL||m)},d=await f.getSessionItem(i.domain),y=await t.ne(d,t.I.login,a);document.location=y.url.toString()},[s,l,m]),_=o.useCallback(async(e={})=>{const r=e.state||{};e.state=void 0;const a={...e,state:t.L(JSON.stringify({kinde:{event:"register"},...r})),supportsReauth:!0,audience:await f.getSessionItem(i.audience),clientId:await f.getSessionItem(i.clientId),redirectURL:L(e?.redirectURL||m),prompt:t.N.create};try{const d=await f.getSessionItem(i.domain),y=await t.ne(d,t.I.register,a);document.location=y.url.toString()}catch(d){console.error("Register error:",d),c.onError?.({error:"ERR_REGISTER",errorDescription:String(d)},{},u)}},[m]),U=o.useCallback(async e=>{try{const r=await f.getSessionItem(i.domain),a=new URLSearchParams;e?e&&typeof e=="string"?a.append("redirect",e):typeof e=="object"&&((e.redirectUrl||S)&&a.append("redirect",e.redirectUrl||S||""),e.allSessions&&a.append("all_sessions",String(e.allSessions))):a.append("redirect",S||""),w(d=>({...d,user:void 0,isAuthenticated:!1})),await Promise.all([f.destroySession(),T.destroySession()]),document.location=`${r}/logout?${a.toString()}`}catch(r){console.error("Logout error:",r),c.onError?.({error:"ERR_LOGOUT",errorDescription:String(r)},{},u)}},[]),u=o.useMemo(()=>({login:p,logout:U,register:_,getIdToken:async()=>await t.p()?.getSessionItem(t.a.idToken),getAccessToken:async()=>await t.p()?.getSessionItem(t.a.accessToken),getToken:async()=>await t.p()?.getSessionItem(t.a.accessToken),getClaim:async e=>t.le(e),getClaims:async(...e)=>t.M(...e),getOrganization:async()=>await t.ue(),getCurrentOrganization:async()=>await t.ue(),getFlag:async e=>await t.fe(e),getUserProfile:async()=>t.he(),getPermission:async e=>await t.ge(e),getPermissions:async()=>t.me(),getUserOrganizations:async()=>await t.ke(),getRoles:async()=>await t.we(),generatePortalUrl:async e=>await t.K({domain:h,returnUrl:e.returnUrl||window.location.href,subNav:e.subNav}),refreshToken:async(...e)=>await t.$(...e),...v}),[v,p,U,_]),R=o.useCallback(e=>{c.onEvent&&c.onEvent("tokenRefreshed",e,u)},[c,u]),k=o.useCallback(()=>{document.visibilityState==="visible"&&v.isAuthenticated&&t.$({domain:h,clientId:l,onRefresh:R}).catch(e=>{console.error("Error refreshing token:",e)})},[v.isAuthenticated,h,l,R]);o.useEffect(()=>(document.removeEventListener("visibilitychange",k),document.addEventListener("visibilitychange",k),()=>{document.removeEventListener("visibilitychange",k)}),[k]);const A=o.useCallback(async()=>{if(E.current)return;await t.se({domain:h,clientId:l}),E.current=!0;const e=new URLSearchParams(window.location.search);let r,a;if(e.has("error")){if(e.get("error")?.toLowerCase()==="login_link_expired"){const g=e.get("reauth_state");g&&p({reauthState:g});return}w(g=>({...g,isLoading:!1}));return}if(!e.has("code")){try{const n=await t.he();n&&w(g=>({...g,user:n,isAuthenticated:!0}))}catch(n){console.warn("Error getting user profile",n)}finally{w(n=>({...n,isLoading:!1}))}return}const y=atob(e.get("state")||"");try{r=JSON.parse(y),a=Object.assign(r.kinde||{event:t.N.login})}catch(n){console.error("Error parsing state:",n),c.onError?.({error:"ERR_STATE_PARSE",errorDescription:String(n)},{},u),r={},a={event:"login"}}try{const n=await f.getSessionItem(i.redirectUri),g=await t.oe({urlParams:new URLSearchParams(window.location.search),domain:h,clientId:l,redirectURL:L(n||m),autoRefresh:!0,onRefresh:R});if(g.success){const C=await t.he();C&&(w(D=>({...D,user:C,isAuthenticated:!0})),c.onSuccess?.(C,{...r,kinde:void 0},u),c.onEvent&&c.onEvent(a.event,{...r,kinde:void 0},u))}else c.onError?.({error:"ERR_CODE_EXCHANGE",errorDescription:g.error},r,u)}finally{w(n=>({...n,isLoading:!1}))}},[l,h,m,c,u,R]);return o.useEffect(()=>{const e={current:!0};return e.current&&A(),()=>{e.current=!1}},[A]),j||E.current?b.jsx(P.KindeContext.Provider,{value:u,children:I}):b.jsx(b.Fragment,{})};exports.KindeContext=P.KindeContext;exports.useKindeAuth=P.useKindeAuth;exports.KindeProvider=$;