@altanlabs/auth
Version:
React authentication library built on top of @altanlabs/database
3 lines (2 loc) • 31 kB
JavaScript
;var e=require("react/jsx-runtime"),t=require("react"),r=require("axios"),s=require("react-router-dom");function a(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(s=Object.getOwnPropertySymbols(e);a<s.length;a++)t.indexOf(s[a])<0&&Object.prototype.propertyIsEnumerable.call(e,s[a])&&(r[s[a]]=e[s[a]])}return r}function n(e,t,r,s){return new(r||(r=Promise))((function(a,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function i(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,i)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;function o(){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 i=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}},l=(e,t)=>{t?e.defaults.headers.common.Authorization=`Bearer ${t}`:(delete e.defaults.headers.common.Authorization,x("logged out"))};let d=!1,c=null;const u=r.create({baseURL:o(),withCredentials:!0}),h=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:s,data:a}=e,n=JSON.stringify({method:t,url:r,params:s,data:a});return this.hashString(n)}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 s=new AbortController;e.signal=s.signal,this.controllers.set(r,s)}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()}},g=()=>n(void 0,void 0,void 0,(function*(){return d||(d=!0,c=u.post("/refresh").then((e=>{const t=e.data.access_token;return d=!1,c=null,t})).catch((e=>(d=!1,c=null,Promise.reject(e))))),c})),m=(e=o())=>{const t=r.create({baseURL:e});return console.debug("[@altanlabs/auth] created new API with base url",t.defaults.baseURL),t.interceptors.request.use((r=>n(void 0,void 0,void 0,(function*(){h.add(r);const s=t.defaults.headers.common.Authorization,a=s&&"string"==typeof s&&s.startsWith("Bearer ")?s.substring(7):null;if(a&&i(a))console.debug(`[@altanlabs/auth] [axios api ${e}] request interceptor. valid token`);else{const e=yield g();l(t,e),r.headers.Authorization=`Bearer ${e}`}return r}))),(e=>Promise.reject(e))),t.interceptors.response.use((e=>(h.remove(e.config),e)),(e=>n(void 0,void 0,void 0,(function*(){var r,s;const a=e.config;if(!a)return Promise.reject(e);if(h.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 g();return l(t,e),a.headers.Authorization=`Bearer ${e}`,t(a)}return(null===(s=e.response)||void 0===s?void 0:s.status)>=500?Promise.reject(new Error("[@altanlabs/auth] A server error occurred. Please try again later.")):Promise.reject(e)})))),t},x=e=>{h.cancelAll(e)},p=t.createContext(null);function f(){const e=t.useContext(p);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}function b(){const{login:e,logout:t,register:r,resetPassword:s,updateProfile:a,continueWithGoogle:n}=f();return{login:e,logout:t,register:r,resetPassword:s,updateProfile:a,continueWithGoogle:n}}function v(){return e.jsxs("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.jsx("defs",{children:e.jsx("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.jsx("clipPath",{id:"B",children:e.jsx("use",{xlinkHref:"#A"})}),e.jsxs("g",{transform:"matrix(.727273 0 0 .727273 -.954545 -1.45455)",children:[e.jsx("path",{d:"M0 37V11l17 13z",clipPath:"url(#B)",fill:"#fbbc05"}),e.jsx("path",{d:"M0 11l17 13 7-6.1L48 14V0H0z",clipPath:"url(#B)",fill:"#ea4335"}),e.jsx("path",{d:"M0 37l30-23 7.9 1L48 0v48H0z",clipPath:"url(#B)",fill:"#34a853"}),e.jsx("path",{d:"M48 48L17 24l-4-3 35-10z",clipPath:"url(#B)",fill:"#4285f4"})]})]})}function w(e){var t,r,s="";if("string"==typeof e||"number"==typeof e)s+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(r=w(e[t]))&&(s&&(s+=" "),s+=r);else for(t in e)e[t]&&(s&&(s+=" "),s+=t);return s}function y(){for(var e,t,r=0,s="";r<arguments.length;)(e=arguments[r++])&&(t=w(e))&&(s&&(s+=" "),s+=t);return s}const j={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"}},N={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"};const k={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"}};var C=t.memo((r=>{var{src:s,refreshUrl:n="/auth/refresh",targetOrigin:o="*",onRefreshError:i}=r,l=a(r,["src","refreshUrl","targetOrigin","onRefreshError"]);const d=t.useRef(null),c=t.useRef(!1),h=t.useRef(null);return t.useEffect((()=>{const e=e=>{var t;if("*"!==o&&e.origin!==o)return;const{type:r}=e.data;"refresh_token"===r&&(c.current||(c.current=!0,h.current=u.post(n).then((e=>{const t=e.data.access_token;return c.current=!1,h.current=null,t})).catch((e=>(c.current=!1,h.current=null,i&&i(e),Promise.reject(e))))),null===(t=h.current)||void 0===t||t.then((e=>{var t,r;null===(r=null===(t=d.current)||void 0===t?void 0:t.contentWindow)||void 0===r||r.postMessage({type:"new_access_token",token:e},o)})).catch((e=>{console.error("Refresh error in ParentCommunicator:",e)})))};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)}),[n,i,o]),t.useEffect((()=>{const e=()=>{var e,t;null===(t=null===(e=d.current)||void 0===e?void 0:e.contentWindow)||void 0===t||t.postMessage({type:"activate_interface_parenthood"},o)},t=d.current;return null==t||t.addEventListener("load",e),()=>null==t?void 0:t.removeEventListener("load",e)}),[o]),e.jsx("iframe",Object.assign({ref:d,src:s},l))}));function A({appearance:t={theme:"light"},onLogout:r,className:s=""}){const{logout:a}=b(),o={light:{button:"text-red-600 hover:text-red-800"},dark:{button:"text-red-400 hover:text-red-200"}}[t.theme||"light"];return e.jsxs("button",{onClick:()=>n(this,void 0,void 0,(function*(){try{yield a(),null==r||r()}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 ${o.button} ${s}`,children:[e.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("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.jsx("span",{children:"Logout"})]})}const S=["id","verified","created_time","last_modified_time","last_modified_by","password","avatar"],P=["name","surname"],B={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"},L={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"}},E=({appearance:t,labels:r})=>e.jsxs("header",{className:y("w-full px-4 py-3 flex justify-between items-center","backdrop-blur-xl border-b border-white/20 shadow-sm"),children:[e.jsx("h1",{className:"text-xl font-bold tracking-wide",children:r.headerTitle}),e.jsx(A,{appearance:t})]}),O=({user:r,updateProfile:s,theme:a,labels:o})=>{var i,l,d;const c=t.useRef(null);return e.jsxs("div",{className:"flex flex-col sm:flex-row items-center space-y-4 sm:space-y-0 sm:space-x-6",children:[e.jsxs("div",{className:"relative group",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-32 rounded-full overflow-hidden bg-gray-200",children:(null===(l=null===(i=r.avatar)||void 0===i?void 0:i[0])||void 0===l?void 0:l.url)?e.jsx("img",{src:r.avatar[0].url,alt:"Avatar",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-400",children:e.jsx("svg",{className:"w-12 h-12",fill:"currentColor",viewBox:"0 0 24 24",children:e.jsx("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.jsx("button",{onClick:()=>{var e;return null===(e=c.current)||void 0===e?void 0:e.click()},className:y("absolute bottom-1 right-1 text-white p-2 rounded-full shadow-md transition-all duration-300",a.primary),title:"Edit avatar",children:e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,viewBox:"0 0 24 24",children:e.jsx("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.jsx("input",{type:"file",ref:c,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=()=>n(void 0,void 0,void 0,(function*(){const e=a.result;yield s({avatar:[{file_name:"avatar.jpg",mime_type:r.type||"image/jpeg",file_content:e.split(",")[1]}]})})),a.readAsDataURL(r)},accept:"image/*",className:"hidden"})]}),e.jsxs("div",{className:"text-center sm:text-left",children:[e.jsx("h3",{className:y("text-2xl font-semibold",a.text),children:r.name||r.email}),(null===(d=r.avatar)||void 0===d?void 0:d.length)>0&&e.jsx("button",{onClick:()=>s({avatar:[]}),className:"mt-2 text-xs underline text-gray-600 hover:text-gray-800 transition",children:o.removeAvatar})]})]})},_=({user:t,isEditing:r,formData:s,setFormData:a,editableFields:n,theme:o,labels:i})=>{const l=S,d=Object.entries(t).filter((([e])=>!l.includes(e)&&!(!n.includes(e)&&r))).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 e.jsxs("div",{children:[e.jsx("h4",{className:y("text-2xl font-semibold mb-4",o.text),children:i.profileInfoTitle}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-6",children:d.map((([t,l])=>e.jsxs("div",{children:[e.jsx("label",{className:y("block text-sm font-medium mb-1",o.textSecondary),children:t.replace(/_/g," ").replace(/\b\w/g,(e=>e.toUpperCase()))}),r&&n.includes(t)?e.jsx("input",{type:"text",value:s[t]||"",onChange:e=>a((r=>Object.assign(Object.assign({},r),{[t]:e.target.value}))),placeholder:`${i.placeholderPrefix} ${t}`,className:y("w-full rounded-lg p-2 text-sm border focus:ring-1 focus:ring-blue-500 focus:outline-none transition",o.input,"placeholder-gray-500")}):e.jsx("div",{className:y("rounded-md text-sm p-2",o.badge),children:l||i.notSet})]},t)))})]})};const M={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"}};exports.AuthProvider=function({children:r,tableId:s,storageKey:i="",onAuthStateChange:d,authenticationOptions:c={persistSession:!0,redirectUrl:"/login"}}){const[h,g]=t.useState(null),[x,f]=t.useState(null),[b,v]=t.useState(!1),[w,y]=t.useState(0),[j,N]=t.useState(!1),k=t.useMemo((()=>m()),[s]),C=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))))),A=t.useCallback((()=>n(this,void 0,void 0,(function*(){try{yield u.post("/logout")}finally{l(k,null),g(null)}}))),[k,c.persistSession,s]);t.useEffect((()=>{null==d||d(h)}),[h,d]);const S=t.useCallback((e=>n(this,[e],void 0,(function*({email:e,password:t}){var r,a;try{v(!0),f(null);const r=new URLSearchParams;r.append("username",e),r.append("password",t);const{data:{access_token:a}}=yield k.post(`/login?table_id=${s}`,r,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});l(k,a),y((e=>e+1))}catch(e){const t=(null===(a=null===(r=e.response)||void 0===r?void 0:r.data)||void 0===a?void 0:a.detail)||"Invalid email or password";throw f(new Error(t)),e}finally{v(!1)}}))),[k,c.persistSession,s]),P=t.useCallback((e=>n(this,void 0,void 0,(function*(){var t,r,{email:n,password:o,name:i,surname:l}=e,d=a(e,["email","password","name","surname"]);try{v(!0),f(null);200===(yield u.post(`/register?table_id=${s}`,Object.assign({email:n,password:o,name:i,surname:l},d))).status&&(yield S({email:n,password:o}))}catch(e){const s=(null===(r=null===(t=e.response)||void 0===t?void 0:t.data)||void 0===r?void 0:r.detail)||"Registration failed";throw f(new Error(s)),e}finally{v(!1)}}))),[k,S,s]),B=t.useCallback((e=>n(this,void 0,void 0,(function*(){throw new Error("Not implemented")}))),[]),L=t.useCallback((e=>n(this,void 0,void 0,(function*(){if(!h)throw new Error("No user logged in");try{v(!0),f(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 k.patch("/update",t),s=C(r.data.user);g(s)}catch(e){throw f(e instanceof Error?e:new Error("Profile update failed")),e}finally{v(!1)}}))),[h,k,c.persistSession,s]),E=t.useCallback((()=>n(this,void 0,void 0,(function*(){try{v(!0),f(null);window.open(`https://auth.altan.ai/google/authorize?table_id=${s}&redirect_url=${encodeURIComponent(window.location.origin)}`,"Auth","width=600,height=600,scrollbars=yes");const e=yield new Promise(((e,t)=>{let r;function s(a){const n=o();if(console.debug("@altanlabs/auth: signin with google: baseUrl:",n),console.debug("@altanlabs/auth: signin with google: event.origin:",a.origin),a.origin!==n)return;r&&clearTimeout(r),window.removeEventListener("message",s);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",s),r=setTimeout((()=>{window.removeEventListener("message",s),t(new Error("Authentication timed out"))}),12e4)})),{access_token:t,user:r}=e;console.debug("@altanlabs/auth: signin with google: googleUser:",r),c.persistSession&&t&&l(k,t),y((e=>e+1))}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw f(new Error(t)),e}finally{v(!1)}}))),[k,s,c.persistSession]);t.useEffect((()=>{(()=>{n(this,void 0,void 0,(function*(){if(console.debug("@altanlabs/auth: @checkAuth: before:",s,b),s&&!b){v(!0);try{const{data:e}=yield k.get("/me"),t=C(e);console.debug("@altanlabs/auth: @checkAuth: setting user:",t),g(t)}catch(e){console.debug("@checkAuth: error",e),g(null)}finally{N(!0),v(!1)}}}))})()}),[k,w]);const O=t.useMemo((()=>({user:h,isLoading:b||!j,error:x,isAuthenticated:!!h,login:S,logout:A,register:P,resetPassword:B,updateProfile:L,continueWithGoogle:E,api:k})),[h,j,b,x,S,A,P,B,L,E,k]);return console.debug("@altanlabs/auth: user:",h),console.debug("@altanlabs/auth: initialized:",j),console.debug("@altanlabs/auth: isLoading:",b),e.jsx(p.Provider,{value:O,children:r})},exports.AuthenticatedIframe=C,exports.GoogleAuth=function({onClick:t,label:r="Continue with Google",disabled:s=!1,appearance:a={theme:"light"}}){const{continueWithGoogle:n}=f(),{theme:o="light",customStyles:i={}}=a,l={googleButton:i.googleButton||M[o].googleButton,text:i.text||M[o].text},d=t||n;return e.jsx("button",{onClick:d,disabled:s,className:y("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",l.googleButton,s&&"opacity-50 cursor-not-allowed"),children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(v,{}),e.jsx("span",{className:"ml-2",children:r})]})})},exports.Logout=A,exports.ProtectedRoute=function({children:t,redirectTo:r="/login"}){const{isAuthenticated:a,isLoading:n}=f();return n?e.jsx("div",{children:"Loading..."}):a?e.jsx(e.Fragment,{children:t}):e.jsx(s.Navigate,{to:r,replace:!0})},exports.SignIn=function(r){var s,o,{appearance:i={theme:"light",customTheme:{}},companyName:l,signUpUrl:d="/sign-up",routing:c="path",withSignUp:u=!0,labels:h={}}=r,g=a(r,["appearance","companyName","signUpUrl","routing","withSignUp","labels"]);const{continueWithGoogle:m,login:x,isLoading:p,isAuthenticated:b,error:w}=f(),k=i.theme||"light",C=Object.assign(Object.assign({},j[k]),i.customTheme),A=Object.assign(Object.assign({},N),h);l&&(A.heading=`${A.heading} to ${l}`);const[S,P]=t.useState((null===(s=g.initialValues)||void 0===s?void 0:s.emailAddress)||""),[B,L]=t.useState((null===(o=g.initialValues)||void 0===o?void 0:o.password)||"");return b?null:e.jsx("div",{className:y("min-h-screen w-full flex items-center justify-center px-4 sm:px-6 lg:px-8",C.background,"transition-colors duration-500 ease-in-out"),children:e.jsxs("div",{className:y("max-w-md w-full space-y-8 p-6 rounded-2xl shadow-md","transform transition-all duration-300 hover:shadow-lg",C.card),children:[e.jsxs("div",{children:[e.jsx("h2",{className:y("text-center text-3xl font-bold",C.text),children:A.heading}),e.jsx("p",{className:y("mt-2 text-center text-sm",C.textMuted),children:A.subtitle})]}),e.jsxs("button",{onClick:()=>m(),className:y("w-full flex justify-center items-center py-2 px-4 text-sm font-medium rounded-md shadow-sm transition",C.googleButton),children:[e.jsx(v,{}),e.jsx("span",{className:"ml-2",children:A.googleButton})]}),e.jsxs("div",{className:"relative my-4",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:y("w-full border-t","dark"===k?"border-gray-700":"border-gray-300")})}),e.jsx("div",{className:"relative flex justify-center text-sm",children:e.jsx("span",{className:y("px-2",C.card,C.textMuted),children:A.orDivider})})]}),e.jsxs("form",{className:"space-y-5",onSubmit:e=>n(this,void 0,void 0,(function*(){e.preventDefault(),yield x({email:S,password:B})})),children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"email",className:y("block text-sm font-medium",C.text),children:A.emailLabel}),e.jsx("input",{id:"email",type:"email",required:!0,className:y("mt-1 block w-full rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-1 focus:ring-blue-500 transition",C.input),value:S,onChange:e=>P(e.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"password",className:y("block text-sm font-medium",C.text),children:A.passwordLabel}),e.jsx("input",{id:"password",type:"password",required:!0,className:y("mt-1 block w-full rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-1 focus:ring-blue-500 transition",C.input),value:B,onChange:e=>L(e.target.value)})]}),w&&e.jsxs("div",{className:y("rounded-md p-4 flex",C.errorBg,"shadow-sm"),children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("svg",{className:y("h-5 w-5",C.errorIcon),viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("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.jsx("div",{className:"ml-3",children:e.jsx("p",{className:y("text-sm font-medium",C.errorText),children:w.message})})]}),e.jsx("button",{type:"submit",className:y("w-full flex justify-center py-2 px-4 rounded-md shadow-sm text-sm font-medium transition-all duration-300",C.button,p&&"opacity-60 cursor-not-allowed"),disabled:p,children:p?A.submitButtonLoading:A.submitButton})]}),e.jsxs("div",{className:y("border-t pt-6","dark"===k?"border-gray-700":"border-gray-200"),children:[u&&e.jsxs("div",{className:"text-center mb-4",children:[e.jsx("span",{className:y(C.textMuted,"mr-1"),children:A.signupQuestion}),e.jsx("a",{href:d,onClick:e=>{e.preventDefault(),"hash"===c?window.location.hash=d:window.location.href=d},className:"text-blue-600 hover:text-blue-400 transition",children:A.signupLink})]}),e.jsxs("div",{className:y("flex items-center justify-center space-x-2 text-xs",C.textMuted),children:[e.jsx("span",{children:A.securedBy}),e.jsx("img",{src:"dark"===k?"https://altan.ai/logos/horizontalWhite.png":"https://altan.ai/logos/horizontalBlack.png",alt:"Altan",className:"h-3"})]})]})]})})},exports.SignUp=function(r){var s,o,{appearance:i={theme:"light"},companyName:l,signInUrl:d="/sign-in",routing:c="path",withSignIn:u=!0}=r,h=a(r,["appearance","companyName","signInUrl","routing","withSignIn"]);const{continueWithGoogle:g,register:m,isLoading:x,isAuthenticated:p,error:b}=f(),[w,j]=t.useState((null===(s=h.initialValues)||void 0===s?void 0:s.emailAddress)||""),[N,C]=t.useState((null===(o=h.initialValues)||void 0===o?void 0:o.password)||""),[A,S]=t.useState(""),[P,B]=t.useState(null),{background:L,card:E,text:O,textMuted:_,input:M,button:R,googleButton:U,errorBackground:z,errorText:I,errorIcon:T,divider:$}=k[i.theme||"light"];return p?null:e.jsx("div",{className:y("min-h-screen w-full flex flex-col justify-center items-center p-4","transition-colors duration-500 ease-in-out",L),children:e.jsxs("div",{className:y("max-w-md w-full space-y-8 p-6 rounded-2xl shadow-md","transform transition-all duration-300 hover:shadow-lg",E),children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:y("text-3xl font-bold",O),children:l?`Create your ${l} account`:"Create account"}),e.jsx("p",{className:y("mt-2 text-sm",_),children:"Get started by creating your account"})]}),e.jsx("button",{onClick:()=>g(),className:y("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",U),children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(v,{}),e.jsx("span",{className:"ml-2",children:"Continue with Google"})]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:y("w-full border-t",$)})}),e.jsx("div",{className:"relative flex justify-center text-sm",children:e.jsx("span",{className:y("px-2",E,_),children:"or"})})]}),e.jsxs("form",{className:"space-y-6",onSubmit:e=>n(this,void 0,void 0,(function*(){if(e.preventDefault(),B(null),N===A)try{yield m({email:w,password:N,displayName:""})}catch(e){}else B("Passwords don't match")})),children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"email",className:y("block text-sm font-medium",O),children:"Email address"}),e.jsx("input",{id:"email",type:"email",required:!0,className:y("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",M),value:w,onChange:e=>j(e.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"password",className:y("block text-sm font-medium",O),children:"Password"}),e.jsx("input",{id:"password",type:"password",required:!0,className:y("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",M),value:N,onChange:e=>C(e.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"confirmPassword",className:y("block text-sm font-medium",O),children:"Confirm Password"}),e.jsx("input",{id:"confirmPassword",type:"password",required:!0,className:y("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",M),value:A,onChange:e=>S(e.target.value)})]}),(b||P)&&e.jsx("div",{className:y("rounded-md p-4 mt-2",z),children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("svg",{className:y("h-5 w-5",T),viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("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.jsx("div",{className:"ml-3",children:e.jsx("p",{className:y("text-sm font-medium",I),children:P||(null==b?void 0:b.message)})})]})}),e.jsx("button",{type:"submit",className:y("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",R),disabled:x,children:x?"Creating account...":"Create account"})]}),e.jsxs("div",{className:y("mt-8 border-t pt-6",$),children:[u&&e.jsxs("div",{className:"text-center mb-4",children:[e.jsxs("span",{className:y("text-sm",_),children:["Already have an account?"," "]}),e.jsx("a",{href:d,onClick:e=>{e.preventDefault(),"hash"===c?window.location.hash=d:window.location.href=d},className:"text-blue-600 hover:text-blue-400 transition",children:"Sign in"})]}),e.jsxs("div",{className:y("flex items-center justify-center space-x-2 text-xs",_),children:[e.jsx("span",{children:"Secured by"}),e.jsx("img",{src:"dark"===i.theme?"https://altan.ai/logos/horizontalWhite.png":"https://altan.ai/logos/horizontalBlack.png",alt:"Altan",className:"h-3"})]})]})]})})},exports.UserProfile=function({appearance:r={},routing:s="path",path:a="/user-profile",showCustomFields:o=!0,editableFields:i=P,hiddenFields:l=[],customPages:d=[],fallback:c,children:u,labels:h={}}){const{user:g,updateProfile:m,isLoading:x,error:p}=f(),[b,v]=t.useState(!1),[w,j]=t.useState({});if(!g)return c||null;const{theme:N="light",customTheme:k={}}=r,C=Object.assign(Object.assign({},L[N]),k),A=Object.assign(Object.assign({},B),h);return e.jsxs("div",{className:y("w-full h-full flex flex-col",C.background),children:[e.jsx(E,{appearance:r,labels:A}),e.jsxs("main",{className:"flex-1 overflow-y-auto p-4",children:[e.jsx("section",{className:y("p-6 rounded-2xl transition-all duration-300",C.card),children:e.jsx(O,{user:g,updateProfile:m,theme:C,labels:A})}),e.jsxs("section",{className:y("p-6 rounded-2xl mt-4 transition-all duration-300",C.card),children:[e.jsx("div",{className:"flex justify-end space-x-3 mb-4",children:b?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{j({}),v(!1)},className:"px-4 py-2 text-sm rounded-md border transition",children:A.cancelButton}),e.jsx("button",{onClick:()=>n(this,void 0,void 0,(function*(){try{yield m(w),v(!1)}catch(e){}})),disabled:x,className:y("px-4 py-2 text-sm rounded-md font-medium transition",C.primary,C.buttonText,x&&"opacity-50 cursor-not-allowed"),children:x?A.savingButton:A.saveButton})]}):e.jsx("button",{onClick:()=>{j(g),v(!0)},className:y("px-4 py-2 text-sm rounded-md font-medium transition",C.primary,C.buttonText),children:A.editProfileButton})}),e.jsx(_,{user:g,isEditing:b,formData:w,setFormData:j,editableFields:i,theme:C,labels:A})]}),p&&e.jsx("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:p.message}),u]})]})},exports.createAuthenticatedApi=m,exports.useAuth=f,exports.useAuthAPI=function(e=!0){const r=t.useContext(p);if(!r){if(e)throw new Error("useAuth must be used within an AuthProvider");return null}return r.api},exports.useAuthActions=b,exports.useAuthError=function(){const{error:e}=f();return e},exports.useAuthLoading=function(){const{isLoading:e}=f();return e},exports.useAuthUser=function(){const{user:e,isAuthenticated:t}=f();return{user:e,isAuthenticated:t}};
//# sourceMappingURL=index.js.map