UNPKG

@altanlabs/auth

Version:

React authentication library built on top of @altanlabs/database

3 lines (2 loc) 30.2 kB
import{jsx as e,Fragment as t,jsxs as r}from"react/jsx-runtime";import{createContext as n,useState as a,useMemo as o,useCallback as i,useEffect as l,useContext as s,memo as d,useRef as c}from"react";import u from"axios";import{Navigate as h}from"react-router-dom";function m(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]])}return r}function g(e,t,r,n){return new(r||(r=Promise))((function(a,o){function i(e){try{s(n.next(e))}catch(e){o(e)}}function l(e){try{s(n.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,l)}s((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;function p(){const e=window.location.hostname;if(e.endsWith(".preview.altan.ai"))return"https://auth.altan.ai";if(e.endsWith(".altanlabs.com")){const t=function(e){const t=e.split(".");return"www"===t[0]&&t.shift(),t.length>2?t.slice(0,t.length-2).join("."):null}(e);return`https://${t?`${t}.`:""}auth.altanlabs.com`}return`auth.${e}`}const b=e=>{if(!e)return!1;try{const t=(e=>{const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map((e=>`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`)).join(""));return JSON.parse(r)})(e),r=Date.now();return 1e3*t.exp>r+1}catch(e){return!1}},f=(e,t)=>{t?e.defaults.headers.common.Authorization=`Bearer ${t}`:(delete e.defaults.headers.common.Authorization,j("logged out"))};let v=!1,x=null;const w=u.create({baseURL:p(),withCredentials:!0}),y=new class{constructor(){this.controllers=new Map}hashString(e){let t=5381;for(let r=0;r<e.length;r++)t=33*t^e.charCodeAt(r);return(t>>>0).toString(36)}getRequestKey(e){const{method:t,url:r,params:n,data:a}=e,o=JSON.stringify({method:t,url:r,params:n,data:a});return this.hashString(o)}add(e){var t;const r=this.getRequestKey(e);this.controllers.has(r)&&(null===(t=this.controllers.get(r))||void 0===t||t.abort("Canceled duplicate request"),this.controllers.delete(r));const n=new AbortController;e.signal=n.signal,this.controllers.set(r,n)}remove(e){let t;t=e.headers&&e.headers["x-request-key"]?e.headers["x-request-key"]:this.getRequestKey(e),this.controllers.delete(t)}cancel(e,t="Operation canceled"){var r;this.controllers.has(e)&&(null===(r=this.controllers.get(e))||void 0===r||r.abort(t),this.controllers.delete(e))}cancelAll(e="Operation canceled"){this.controllers.forEach((t=>{t.abort(e)})),this.controllers.clear()}},N=()=>g(void 0,void 0,void 0,(function*(){return v||(v=!0,x=w.post("/refresh").then((e=>{const t=e.data.access_token;return v=!1,x=null,t})).catch((e=>(v=!1,x=null,Promise.reject(e))))),x})),k=(e=p())=>{const t=u.create({baseURL:e});return console.debug("[@altanlabs/auth] created new API with base url",t.defaults.baseURL),t.interceptors.request.use((r=>g(void 0,void 0,void 0,(function*(){y.add(r);const n=t.defaults.headers.common.Authorization,a=n&&"string"==typeof n&&n.startsWith("Bearer ")?n.substring(7):null;if(a&&b(a))console.debug(`[@altanlabs/auth] [axios api ${e}] request interceptor. valid token`);else{const e=yield N();f(t,e),r.headers.Authorization=`Bearer ${e}`}return r}))),(e=>Promise.reject(e))),t.interceptors.response.use((e=>(y.remove(e.config),e)),(e=>g(void 0,void 0,void 0,(function*(){var r,n;const a=e.config;if(!a)return Promise.reject(e);if(y.remove(a),a._retryCount=a._retryCount||0,401===(null===(r=e.response)||void 0===r?void 0:r.status)&&a._retryCount<1){a._retryCount++;const e=yield N();return f(t,e),a.headers.Authorization=`Bearer ${e}`,t(a)}return(null===(n=e.response)||void 0===n?void 0:n.status)>=500?Promise.reject(new Error("[@altanlabs/auth] A server error occurred. Please try again later.")):Promise.reject(e)})))),t},j=e=>{y.cancelAll(e)},B=n(null);function C({children:t,tableId:r,storageKey:n="",onAuthStateChange:s,authenticationOptions:d={persistSession:!0,redirectUrl:"/login"}}){const[c,u]=a(null),[h,b]=a(null),[v,x]=a(!1),[y,N]=a(0),[j,C]=a(!1),A=o((()=>k()),[r]),P=e=>Object.assign({id:Number(e.id||0),email:e.email||"",name:e.name,surname:e.surname,avatar:Array.isArray(e.avatar)?e.avatar:[],verified:Boolean(e.verified)},Object.fromEntries(Object.entries(e).filter((([e])=>!["id","email","name","surname","avatar","verified"].includes(e))))),L=i((()=>g(this,void 0,void 0,(function*(){try{yield w.post("/logout")}finally{f(A,null),u(null)}}))),[A,d.persistSession,r]);l((()=>{null==s||s(c)}),[c,s]);const S=i((e=>g(this,[e],void 0,(function*({email:e,password:t}){var n,a;try{x(!0),b(null);const n=new URLSearchParams;n.append("username",e),n.append("password",t);const{data:{access_token:a}}=yield A.post(`/login?table_id=${r}`,n,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});f(A,a),N((e=>e+1))}catch(e){const t=(null===(a=null===(n=e.response)||void 0===n?void 0:n.data)||void 0===a?void 0:a.detail)||"Invalid email or password";throw b(new Error(t)),e}finally{x(!1)}}))),[A,d.persistSession,r]),E=i((e=>g(this,void 0,void 0,(function*(){var t,n,{email:a,password:o,name:i,surname:l}=e,s=m(e,["email","password","name","surname"]);try{x(!0),b(null);200===(yield w.post(`/register?table_id=${r}`,Object.assign({email:a,password:o,name:i,surname:l},s))).status&&(yield S({email:a,password:o}))}catch(e){const r=(null===(n=null===(t=e.response)||void 0===t?void 0:t.data)||void 0===n?void 0:n.detail)||"Registration failed";throw b(new Error(r)),e}finally{x(!1)}}))),[A,S,r]),O=i((e=>g(this,void 0,void 0,(function*(){throw new Error("Not implemented")}))),[]),_=i((e=>g(this,void 0,void 0,(function*(){if(!c)throw new Error("No user logged in");try{x(!0),b(null);const t=Object.assign({},e);"avatar"in e&&(null===e.avatar?t.avatar=[]:"string"==typeof e.avatar?t.avatar=[{file_name:"avatar.jpg",mime_type:"image/jpeg",file_content:e.avatar}]:t.avatar=e.avatar);const r=yield A.patch("/update",t),n=P(r.data.user);u(n)}catch(e){throw b(e instanceof Error?e:new Error("Profile update failed")),e}finally{x(!1)}}))),[c,A,d.persistSession,r]),M=i((()=>g(this,void 0,void 0,(function*(){try{x(!0),b(null);window.open(`https://auth.altan.ai/google/authorize?table_id=${r}&redirect_url=${encodeURIComponent(window.location.origin)}`,"Auth","width=600,height=600,scrollbars=yes");const e=yield new Promise(((e,t)=>{let r;function n(a){const o=p();if(console.debug("@altanlabs/auth: signin with google: baseUrl:",o),console.debug("@altanlabs/auth: signin with google: event.origin:",a.origin),a.origin!==o)return;r&&clearTimeout(r),window.removeEventListener("message",n);const i=a.data;console.debug("@altanlabs/auth: signin with google: response:",i),i.error?t(new Error(i.error)):i.success?e(i):t(new Error("Invalid response format"))}window.addEventListener("message",n),r=setTimeout((()=>{window.removeEventListener("message",n),t(new Error("Authentication timed out"))}),12e4)})),{access_token:t,user:n}=e;console.debug("@altanlabs/auth: signin with google: googleUser:",n),d.persistSession&&t&&f(A,t),N((e=>e+1))}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw b(new Error(t)),e}finally{x(!1)}}))),[A,r,d.persistSession]);l((()=>{(()=>{g(this,void 0,void 0,(function*(){if(console.debug("@altanlabs/auth: @checkAuth: before:",r,v),r&&!v){x(!0);try{const{data:e}=yield A.get("/me"),t=P(e);console.debug("@altanlabs/auth: @checkAuth: setting user:",t),u(t)}catch(e){console.debug("@checkAuth: error",e),u(null)}finally{C(!0),x(!1)}}}))})()}),[A,y]);const z=o((()=>({user:c,isLoading:v||!j,error:h,isAuthenticated:!!c,login:S,logout:L,register:E,resetPassword:O,updateProfile:_,continueWithGoogle:M,api:A})),[c,j,v,h,S,L,E,O,_,M,A]);return console.debug("@altanlabs/auth: user:",c),console.debug("@altanlabs/auth: initialized:",j),console.debug("@altanlabs/auth: isLoading:",v),e(B.Provider,{value:z,children:t})}function A(){const e=s(B);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}function P(){const{user:e,isAuthenticated:t}=A();return{user:e,isAuthenticated:t}}function L(){const{isLoading:e}=A();return e}function S(){const{error:e}=A();return e}function E(){const{login:e,logout:t,register:r,resetPassword:n,updateProfile:a,continueWithGoogle:o}=A();return{login:e,logout:t,register:r,resetPassword:n,updateProfile:a,continueWithGoogle:o}}function O(e=!0){const t=s(B);if(!t){if(e)throw new Error("useAuth must be used within an AuthProvider");return null}return t.api}function _({children:r,redirectTo:n="/login"}){const{isAuthenticated:a,isLoading:o}=A();return o?e("div",{children:"Loading..."}):a?e(t,{children:r}):e(h,{to:n,replace:!0})}function M(){return r("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",viewBox:"0 0 32 32",width:"20",height:"20",children:[e("defs",{children:e("path",{id:"A",d:"M44.5 20H24v8.5h11.8C34.7 33.9 30.1 37 24 37c-7.2 0-13-5.8-13-13s5.8-13 13-13c3.1 0 5.9 1.1 8.1 2.9l6.4-6.4C34.6 4.1 29.6 2 24 2 11.8 2 2 11.8 2 24s9.8 22 22 22c11 0 21-8 21-22 0-1.3-.2-2.7-.5-4z"})}),e("clipPath",{id:"B",children:e("use",{xlinkHref:"#A"})}),r("g",{transform:"matrix(.727273 0 0 .727273 -.954545 -1.45455)",children:[e("path",{d:"M0 37V11l17 13z",clipPath:"url(#B)",fill:"#fbbc05"}),e("path",{d:"M0 11l17 13 7-6.1L48 14V0H0z",clipPath:"url(#B)",fill:"#ea4335"}),e("path",{d:"M0 37l30-23 7.9 1L48 0v48H0z",clipPath:"url(#B)",fill:"#34a853"}),e("path",{d:"M48 48L17 24l-4-3 35-10z",clipPath:"url(#B)",fill:"#4285f4"})]})]})}function z(e){var t,r,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(r=z(e[t]))&&(n&&(n+=" "),n+=r);else for(t in e)e[t]&&(n&&(n+=" "),n+=t);return n}function T(){for(var e,t,r=0,n="";r<arguments.length;)(e=arguments[r++])&&(t=z(e))&&(n&&(n+=" "),n+=t);return n}const I={light:{background:"bg-gradient-to-br from-gray-100 to-gray-200",card:"bg-white/30 backdrop-blur-md border border-white/20",text:"text-gray-900",textMuted:"text-gray-700",input:"bg-white text-gray-900 border-gray-300",button:"bg-black hover:bg-gray-900 text-white",googleButton:"bg-white/80 hover:bg-gray-50 text-gray-700 border border-gray-300",errorBg:"bg-red-50",errorText:"text-red-800",errorIcon:"text-red-400"},dark:{background:"bg-gradient-to-br from-gray-800 to-gray-900",card:"bg-gray-800/30 backdrop-blur-md border border-gray-700/30",text:"text-white",textMuted:"text-gray-300",input:"bg-gray-800 text-white border-gray-600",button:"bg-white hover:bg-gray-100 text-black",googleButton:"bg-gray-800 hover:bg-gray-700 text-white border border-gray-600",errorBg:"bg-red-900/20",errorText:"text-red-200",errorIcon:"text-red-400"}},U={heading:"Sign in",subtitle:"Welcome back! Please sign in to continue",googleButton:"Continue with Google",orDivider:"or",emailLabel:"Email address",passwordLabel:"Password",submitButton:"Continue",submitButtonLoading:"Signing in...",signupQuestion:"Don't have an account?",signupLink:"Sign up",securedBy:"Secured by"};function R(t){var n,o,{appearance:i={theme:"light",customTheme:{}},companyName:l,signUpUrl:s="/sign-up",routing:d="path",withSignUp:c=!0,labels:u={}}=t,h=m(t,["appearance","companyName","signUpUrl","routing","withSignUp","labels"]);const{continueWithGoogle:p,login:b,isLoading:f,isAuthenticated:v,error:x}=A(),w=i.theme||"light",y=Object.assign(Object.assign({},I[w]),i.customTheme),N=Object.assign(Object.assign({},U),u);l&&(N.heading=`${N.heading} to ${l}`);const[k,j]=a((null===(n=h.initialValues)||void 0===n?void 0:n.emailAddress)||""),[B,C]=a((null===(o=h.initialValues)||void 0===o?void 0:o.password)||"");if(v)return null;return e("div",{className:T("min-h-screen w-full flex items-center justify-center px-4 sm:px-6 lg:px-8",y.background,"transition-colors duration-500 ease-in-out"),children:r("div",{className:T("max-w-md w-full space-y-8 p-6 rounded-2xl shadow-md","transform transition-all duration-300 hover:shadow-lg",y.card),children:[r("div",{children:[e("h2",{className:T("text-center text-3xl font-bold",y.text),children:N.heading}),e("p",{className:T("mt-2 text-center text-sm",y.textMuted),children:N.subtitle})]}),r("button",{onClick:()=>p(),className:T("w-full flex justify-center items-center py-2 px-4 text-sm font-medium rounded-md shadow-sm transition",y.googleButton),children:[e(M,{}),e("span",{className:"ml-2",children:N.googleButton})]}),r("div",{className:"relative my-4",children:[e("div",{className:"absolute inset-0 flex items-center",children:e("div",{className:T("w-full border-t","dark"===w?"border-gray-700":"border-gray-300")})}),e("div",{className:"relative flex justify-center text-sm",children:e("span",{className:T("px-2",y.card,y.textMuted),children:N.orDivider})})]}),r("form",{className:"space-y-5",onSubmit:e=>g(this,void 0,void 0,(function*(){e.preventDefault(),yield b({email:k,password:B})})),children:[r("div",{children:[e("label",{htmlFor:"email",className:T("block text-sm font-medium",y.text),children:N.emailLabel}),e("input",{id:"email",type:"email",required:!0,className:T("mt-1 block w-full rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-1 focus:ring-blue-500 transition",y.input),value:k,onChange:e=>j(e.target.value)})]}),r("div",{children:[e("label",{htmlFor:"password",className:T("block text-sm font-medium",y.text),children:N.passwordLabel}),e("input",{id:"password",type:"password",required:!0,className:T("mt-1 block w-full rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-1 focus:ring-blue-500 transition",y.input),value:B,onChange:e=>C(e.target.value)})]}),x&&r("div",{className:T("rounded-md p-4 flex",y.errorBg,"shadow-sm"),children:[e("div",{className:"flex-shrink-0",children:e("svg",{className:T("h-5 w-5",y.errorIcon),viewBox:"0 0 20 20",fill:"currentColor",children:e("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm-1.293-9.707a1 1 0 011.414-1.414l1.293 1.293 1.293-1.293a1 1 0 011.414 1.414L12.414 10l1.293 1.293a1 1 0 01-1.414 1.414L11 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L9.586 10 8.293 8.707z",clipRule:"evenodd"})})}),e("div",{className:"ml-3",children:e("p",{className:T("text-sm font-medium",y.errorText),children:x.message})})]}),e("button",{type:"submit",className:T("w-full flex justify-center py-2 px-4 rounded-md shadow-sm text-sm font-medium transition-all duration-300",y.button,f&&"opacity-60 cursor-not-allowed"),disabled:f,children:f?N.submitButtonLoading:N.submitButton})]}),r("div",{className:T("border-t pt-6","dark"===w?"border-gray-700":"border-gray-200"),children:[c&&r("div",{className:"text-center mb-4",children:[e("span",{className:T(y.textMuted,"mr-1"),children:N.signupQuestion}),e("a",{href:s,onClick:e=>{e.preventDefault(),"hash"===d?window.location.hash=s:window.location.href=s},className:"text-blue-600 hover:text-blue-400 transition",children:N.signupLink})]}),r("div",{className:T("flex items-center justify-center space-x-2 text-xs",y.textMuted),children:[e("span",{children:N.securedBy}),e("img",{src:"dark"===w?"https://altan.ai/logos/horizontalWhite.png":"https://altan.ai/logos/horizontalBlack.png",alt:"Altan",className:"h-3"})]})]})]})})}const $={light:{background:"bg-gradient-to-br from-gray-100 to-gray-200",card:"bg-white/30 backdrop-blur-md border border-white/20",text:"text-gray-900",textMuted:"text-gray-600",input:"bg-white/40 text-gray-900 border-white/40 placeholder-gray-600",button:"bg-black hover:bg-gray-900 text-white",googleButton:"bg-white/40 hover:bg-white/60 border-white/40 text-gray-900",errorBackground:"bg-red-50",errorText:"text-red-800",errorIcon:"text-red-400",divider:"border-gray-300"},dark:{background:"bg-gradient-to-br from-gray-800 to-gray-900",card:"bg-gray-800/30 backdrop-blur-md border border-gray-700/30",text:"text-white",textMuted:"text-gray-300",input:"bg-gray-700/40 text-white border-gray-600 placeholder-gray-400",button:"bg-white hover:bg-gray-100 text-black",googleButton:"bg-gray-700/40 hover:bg-gray-700 border-gray-600 text-white",errorBackground:"bg-red-900/20",errorText:"text-red-200",errorIcon:"text-red-400",divider:"border-gray-700"}};function W(t){var n,o,{appearance:i={theme:"light"},companyName:l,signInUrl:s="/sign-in",routing:d="path",withSignIn:c=!0}=t,u=m(t,["appearance","companyName","signInUrl","routing","withSignIn"]);const{continueWithGoogle:h,register:p,isLoading:b,isAuthenticated:f,error:v}=A(),[x,w]=a((null===(n=u.initialValues)||void 0===n?void 0:n.emailAddress)||""),[y,N]=a((null===(o=u.initialValues)||void 0===o?void 0:o.password)||""),[k,j]=a(""),[B,C]=a(null),{background:P,card:L,text:S,textMuted:E,input:O,button:_,googleButton:z,errorBackground:I,errorText:U,errorIcon:R,divider:W}=$[i.theme||"light"];if(f)return null;return e("div",{className:T("min-h-screen w-full flex flex-col justify-center items-center p-4","transition-colors duration-500 ease-in-out",P),children:r("div",{className:T("max-w-md w-full space-y-8 p-6 rounded-2xl shadow-md","transform transition-all duration-300 hover:shadow-lg",L),children:[r("div",{className:"text-center",children:[e("h2",{className:T("text-3xl font-bold",S),children:l?`Create your ${l} account`:"Create account"}),e("p",{className:T("mt-2 text-sm",E),children:"Get started by creating your account"})]}),e("button",{onClick:()=>h(),className:T("w-full flex justify-center py-2 px-4 border rounded-md shadow-sm text-sm font-medium transition-all","hover:shadow-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1",z),children:r("span",{className:"flex items-center",children:[e(M,{}),e("span",{className:"ml-2",children:"Continue with Google"})]})}),r("div",{className:"relative",children:[e("div",{className:"absolute inset-0 flex items-center",children:e("div",{className:T("w-full border-t",W)})}),e("div",{className:"relative flex justify-center text-sm",children:e("span",{className:T("px-2",L,E),children:"or"})})]}),r("form",{className:"space-y-6",onSubmit:e=>g(this,void 0,void 0,(function*(){if(e.preventDefault(),C(null),y===k)try{yield p({email:x,password:y,displayName:""})}catch(e){}else C("Passwords don't match")})),children:[r("div",{children:[e("label",{htmlFor:"email",className:T("block text-sm font-medium",S),children:"Email address"}),e("input",{id:"email",type:"email",required:!0,className:T("mt-1 block w-full border rounded-md shadow-sm py-2 px-3 transition","focus:ring-1 focus:ring-blue-500 focus:border-blue-500",O),value:x,onChange:e=>w(e.target.value)})]}),r("div",{children:[e("label",{htmlFor:"password",className:T("block text-sm font-medium",S),children:"Password"}),e("input",{id:"password",type:"password",required:!0,className:T("mt-1 block w-full border rounded-md shadow-sm py-2 px-3 transition","focus:ring-1 focus:ring-blue-500 focus:border-blue-500",O),value:y,onChange:e=>N(e.target.value)})]}),r("div",{children:[e("label",{htmlFor:"confirmPassword",className:T("block text-sm font-medium",S),children:"Confirm Password"}),e("input",{id:"confirmPassword",type:"password",required:!0,className:T("mt-1 block w-full border rounded-md shadow-sm py-2 px-3 transition","focus:ring-1 focus:ring-blue-500 focus:border-blue-500",O),value:k,onChange:e=>j(e.target.value)})]}),(v||B)&&e("div",{className:T("rounded-md p-4 mt-2",I),children:r("div",{className:"flex",children:[e("div",{className:"flex-shrink-0",children:e("svg",{className:T("h-5 w-5",R),viewBox:"0 0 20 20",fill:"currentColor",children:e("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1\n 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0\n 00-1.414-1.414L10 8.586 8.707 7.293z",clipRule:"evenodd"})})}),e("div",{className:"ml-3",children:e("p",{className:T("text-sm font-medium",U),children:B||(null==v?void 0:v.message)})})]})}),e("button",{type:"submit",className:T("w-full flex justify-center py-2 px-4 rounded-md shadow-sm text-sm font-medium","border border-transparent transition focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1",_),disabled:b,children:b?"Creating account...":"Create account"})]}),r("div",{className:T("mt-8 border-t pt-6",W),children:[c&&r("div",{className:"text-center mb-4",children:[r("span",{className:T("text-sm",E),children:["Already have an account?"," "]}),e("a",{href:s,onClick:e=>{e.preventDefault(),"hash"===d?window.location.hash=s:window.location.href=s},className:"text-blue-600 hover:text-blue-400 transition",children:"Sign in"})]}),r("div",{className:T("flex items-center justify-center space-x-2 text-xs",E),children:[e("span",{children:"Secured by"}),e("img",{src:"dark"===i.theme?"https://altan.ai/logos/horizontalWhite.png":"https://altan.ai/logos/horizontalBlack.png",alt:"Altan",className:"h-3"})]})]})]})})}var q=d((t=>{var{src:r,refreshUrl:n="/auth/refresh",targetOrigin:a="*",onRefreshError:o}=t,i=m(t,["src","refreshUrl","targetOrigin","onRefreshError"]);const s=c(null),d=c(!1),u=c(null);return l((()=>{const e=e=>{var t;if("*"!==a&&e.origin!==a)return;const{type:r}=e.data;"refresh_token"===r&&(d.current||(d.current=!0,u.current=w.post(n).then((e=>{const t=e.data.access_token;return d.current=!1,u.current=null,t})).catch((e=>(d.current=!1,u.current=null,o&&o(e),Promise.reject(e))))),null===(t=u.current)||void 0===t||t.then((e=>{var t,r;null===(r=null===(t=s.current)||void 0===t?void 0:t.contentWindow)||void 0===r||r.postMessage({type:"new_access_token",token:e},a)})).catch((e=>{console.error("Refresh error in ParentCommunicator:",e)})))};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}),[n,o,a]),l((()=>{const e=()=>{var e,t;null===(t=null===(e=s.current)||void 0===e?void 0:e.contentWindow)||void 0===t||t.postMessage({type:"activate_interface_parenthood"},a)},t=s.current;return null==t||t.addEventListener("load",e),()=>null==t?void 0:t.removeEventListener("load",e)}),[a]),e("iframe",Object.assign({ref:s,src:r},i))}));function D({appearance:t={theme:"light"},onLogout:n,className:a=""}){const{logout:o}=E(),i={light:{button:"text-red-600 hover:text-red-800"},dark:{button:"text-red-400 hover:text-red-200"}}[t.theme||"light"];return r("button",{onClick:()=>g(this,void 0,void 0,(function*(){try{yield o(),null==n||n()}catch(e){console.error("Logout failed:",e)}})),className:`flex items-center space-x-2 px-4 py-2 rounded-md hover:bg-red-50 dark:hover:bg-red-900/20 ${i.button} ${a}`,children:[e("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})}),e("span",{children:"Logout"})]})}const F=["id","verified","created_time","last_modified_time","last_modified_by","password","avatar"],G=["name","surname"],H={headerTitle:"Profile",profileSectionTitle:"Your Profile",removeAvatar:"Remove avatar",profileInfoTitle:"Profile Info",editProfileButton:"Edit Profile",cancelButton:"Cancel",saveButton:"Save",savingButton:"Saving...",notSet:"Not set",placeholderPrefix:"Enter"},V={light:{background:"bg-gradient-to-br from-gray-100 to-gray-200",card:"bg-white/30 backdrop-blur-md border border-white/20",text:"text-gray-900",textSecondary:"text-gray-700",input:"bg-white/40 text-gray-900 placeholder-gray-600",badge:"bg-white/20 text-gray-700",primary:"bg-blue-600 hover:bg-blue-700",buttonText:"text-white"},dark:{background:"bg-gradient-to-br from-gray-800 to-gray-900",card:"bg-gray-800/30 backdrop-blur-md border border-gray-700/30",text:"text-white",textSecondary:"text-gray-300",input:"bg-gray-700/40 text-white placeholder-gray-400",badge:"bg-gray-700/20 text-gray-200",primary:"bg-blue-500 hover:bg-blue-600",buttonText:"text-white"}},K=({appearance:t,labels:n})=>r("header",{className:T("w-full px-4 py-3 flex justify-between items-center","backdrop-blur-xl border-b border-white/20 shadow-sm"),children:[e("h1",{className:"text-xl font-bold tracking-wide",children:n.headerTitle}),e(D,{appearance:t})]}),J=({user:t,updateProfile:n,theme:a,labels:o})=>{var i,l,s;const d=c(null);return r("div",{className:"flex flex-col sm:flex-row items-center space-y-4 sm:space-y-0 sm:space-x-6",children:[r("div",{className:"relative group",children:[e("div",{className:"w-28 h-28 sm:w-32 sm:h-32 rounded-full overflow-hidden bg-gray-200",children:(null===(l=null===(i=t.avatar)||void 0===i?void 0:i[0])||void 0===l?void 0:l.url)?e("img",{src:t.avatar[0].url,alt:"Avatar",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"}):e("div",{className:"w-full h-full flex items-center justify-center text-gray-400",children:e("svg",{className:"w-12 h-12",fill:"currentColor",viewBox:"0 0 24 24",children:e("path",{d:"M24 20.993V24H0v-2.996A14.977 14.977 0 0112.004 15c4.904 0 9.26 2.354 11.996 5.993zM16.002 8c0 2.208-1.79 4-3.998 4-2.208 0-3.998-1.792-3.998-4s1.79-4 3.998-4c2.208 0 3.998 1.792 3.998 4z"})})})}),e("button",{onClick:()=>{var e;return null===(e=d.current)||void 0===e?void 0:e.click()},className:T("absolute bottom-1 right-1 text-white p-2 rounded-full shadow-md transition-all duration-300",a.primary),title:"Edit avatar",children:e("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,viewBox:"0 0 24 24",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.232 5.232l3.536 3.536M16.732 3.732a2.5 2.5 0 013.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})})}),e("input",{type:"file",ref:d,onChange:e=>{var t;const r=null===(t=e.target.files)||void 0===t?void 0:t[0];if(!r)return;const a=new FileReader;a.onloadend=()=>g(void 0,void 0,void 0,(function*(){const e=a.result;yield n({avatar:[{file_name:"avatar.jpg",mime_type:r.type||"image/jpeg",file_content:e.split(",")[1]}]})})),a.readAsDataURL(r)},accept:"image/*",className:"hidden"})]}),r("div",{className:"text-center sm:text-left",children:[e("h3",{className:T("text-2xl font-semibold",a.text),children:t.name||t.email}),(null===(s=t.avatar)||void 0===s?void 0:s.length)>0&&e("button",{onClick:()=>n({avatar:[]}),className:"mt-2 text-xs underline text-gray-600 hover:text-gray-800 transition",children:o.removeAvatar})]})]})},Q=({user:t,isEditing:n,formData:a,setFormData:o,editableFields:i,theme:l,labels:s})=>{const d=F,c=Object.entries(t).filter((([e])=>!d.includes(e)&&!(!i.includes(e)&&n))).map((([e,t])=>{let r=t;return Array.isArray(t)?r=t.join(", "):null==t?r="":"object"==typeof t&&(r=JSON.stringify(t)),[e,r]}));return r("div",{children:[e("h4",{className:T("text-2xl font-semibold mb-4",l.text),children:s.profileInfoTitle}),e("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-6",children:c.map((([t,d])=>r("div",{children:[e("label",{className:T("block text-sm font-medium mb-1",l.textSecondary),children:t.replace(/_/g," ").replace(/\b\w/g,(e=>e.toUpperCase()))}),n&&i.includes(t)?e("input",{type:"text",value:a[t]||"",onChange:e=>o((r=>Object.assign(Object.assign({},r),{[t]:e.target.value}))),placeholder:`${s.placeholderPrefix} ${t}`,className:T("w-full rounded-lg p-2 text-sm border focus:ring-1 focus:ring-blue-500 focus:outline-none transition",l.input,"placeholder-gray-500")}):e("div",{className:T("rounded-md text-sm p-2",l.badge),children:d||s.notSet})]},t)))})]})};function X({appearance:n={},routing:o="path",path:i="/user-profile",showCustomFields:l=!0,editableFields:s=G,hiddenFields:d=[],customPages:c=[],fallback:u,children:h,labels:m={}}){const{user:p,updateProfile:b,isLoading:f,error:v}=A(),[x,w]=a(!1),[y,N]=a({});if(!p)return u||null;const{theme:k="light",customTheme:j={}}=n,B=Object.assign(Object.assign({},V[k]),j),C=Object.assign(Object.assign({},H),m);return r("div",{className:T("w-full h-full flex flex-col",B.background),children:[e(K,{appearance:n,labels:C}),r("main",{className:"flex-1 overflow-y-auto p-4",children:[e("section",{className:T("p-6 rounded-2xl transition-all duration-300",B.card),children:e(J,{user:p,updateProfile:b,theme:B,labels:C})}),r("section",{className:T("p-6 rounded-2xl mt-4 transition-all duration-300",B.card),children:[e("div",{className:"flex justify-end space-x-3 mb-4",children:x?r(t,{children:[e("button",{onClick:()=>{N({}),w(!1)},className:"px-4 py-2 text-sm rounded-md border transition",children:C.cancelButton}),e("button",{onClick:()=>g(this,void 0,void 0,(function*(){try{yield b(y),w(!1)}catch(e){}})),disabled:f,className:T("px-4 py-2 text-sm rounded-md font-medium transition",B.primary,B.buttonText,f&&"opacity-50 cursor-not-allowed"),children:f?C.savingButton:C.saveButton})]}):e("button",{onClick:()=>{N(p),w(!0)},className:T("px-4 py-2 text-sm rounded-md font-medium transition",B.primary,B.buttonText),children:C.editProfileButton})}),e(Q,{user:p,isEditing:x,formData:y,setFormData:N,editableFields:s,theme:B,labels:C})]}),v&&e("div",{className:"mt-4 p-4 rounded-lg bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 text-sm shadow transition",children:v.message}),h]})]})}const Y={light:{googleButton:"bg-white/40 hover:bg-white/60 border border-white/40 text-gray-900",text:"text-gray-900"},dark:{googleButton:"bg-gray-700/40 hover:bg-gray-700 border border-gray-600 text-white",text:"text-white"}};function Z({onClick:t,label:n="Continue with Google",disabled:a=!1,appearance:o={theme:"light"}}){const{continueWithGoogle:i}=A(),{theme:l="light",customStyles:s={}}=o,d={googleButton:s.googleButton||Y[l].googleButton,text:s.text||Y[l].text};return e("button",{onClick:t||i,disabled:a,className:T("w-full flex justify-center py-2 px-4 border rounded-md shadow-sm text-sm font-medium transition-all focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1",d.googleButton,a&&"opacity-50 cursor-not-allowed"),children:r("span",{className:"flex items-center",children:[e(M,{}),e("span",{className:"ml-2",children:n})]})})}export{C as AuthProvider,q as AuthenticatedIframe,Z as GoogleAuth,D as Logout,_ as ProtectedRoute,R as SignIn,W as SignUp,X as UserProfile,k as createAuthenticatedApi,A as useAuth,O as useAuthAPI,E as useAuthActions,S as useAuthError,L as useAuthLoading,P as useAuthUser}; //# sourceMappingURL=index.esm.js.map