UNPKG

vormiaguardjs

Version:

Vormia Guard JS - A npm package for authentication and guard management with VormiaPHP laravel Backend application

2 lines (1 loc) 4.67 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("vormiaqueryjs"),y=require("@tanstack/react-query"),u=require("react"),F=require("zustand"),c=require("vue"),d=require("svelte/store"),h=require("@builder.io/qwik"),M=require("solid-js");let f=null;class V{constructor(e){this.config={apiBaseUrl:"",mode:"spa",redirects:{onFail:"/login",onSuccess:"/"},...e},this.vormiaClient=e.vormiaClient||E.getGlobalVormiaClient(),this.user=null,this.isLoading=!1,this.error=null}async fetchUser(){this.isLoading=!0,this.error=null;try{const e=await this.vormiaClient.get("/api/user",{withCredentials:!0});return this.user=e.data,this.isLoading=!1,this.user}catch(e){return this.user=null,this.error=e,this.isLoading=!1,null}}async login(e){await this.vormiaClient.get("/sanctum/csrf-cookie",{withCredentials:!0});const r=await this.vormiaClient.post("/login",e,{withCredentials:!0});return await this.fetchUser(),r}async logout(){await this.vormiaClient.post("/logout",{},{withCredentials:!0}),this.user=null}isAuthenticated(){return!!this.user}hasRole(e){return!this.user||!this.user.roles?!1:e?Array.isArray(e)?e.some(r=>this.user.roles.includes(r)):this.user.roles.includes(e):!0}async canAccess(e,r=null){try{let n=`/api/can-access?route=${encodeURIComponent(e)}`;return r&&(n+=`&middleware=${encodeURIComponent(r)}`),(await this.vormiaClient.get(n,{withCredentials:!0})).data.allowed}catch{return!1}}}function $(t){return f=new V(t),f}function a(){if(!f)throw new Error("Guard client not initialized. Call createGuardClient first.");return f}function v(){const t=a(),{data:e,isLoading:r,error:n,refetch:s}=y.useQuery({queryKey:["vormiaguard","user"],queryFn:()=>t.fetchUser(),staleTime:1e3*60*5,retry:!1});return{user:e,isLoading:r,error:n,isAuthenticated:!!e,refetch:s}}function I({onSuccess:t,onError:e,redirectTo:r}={}){const n=a(),s=y.useMutation({mutationFn:i=>n.login(i),onSuccess:i=>{t&&t(i),r&&(n.config.mode==="spa"&&window.history.pushState?window.location.assign(r):window.location.href=r)},onError:e});return{login:s.mutateAsync,isLoading:s.isLoading,error:s.error}}function Q({onSuccess:t,onError:e,redirectTo:r}={}){const n=a(),s=y.useMutation({mutationFn:()=>n.logout(),onSuccess:()=>{t&&t(),r&&(n.config.mode==="spa"&&window.history.pushState?window.location.assign(r):window.location.href=r)},onError:e});return{logout:s.mutateAsync,isLoading:s.isLoading,error:s.error}}function j({children:t,roles:e,fallback:r=null,redirectTo:n,mode:s,backendCheck:i=!1,route:g=null,middleware:C=null}){const{user:l,isLoading:p,isAuthenticated:A}=v(),m=a(),L=s||(window.history.pushState?"spa":"mpa"),[S,U]=u.useState(!i),[q,G]=u.useState(i),R=e?l&&l.roles&&e.some(o=>l.roles.includes(o)):!!l;u.useEffect(()=>{let o=!0;return i&&(g||window.location.pathname)&&(G(!0),m.canAccess(g||window.location.pathname,C).then(b=>{o&&U(b)}).finally(()=>{o&&G(!1)})),()=>{o=!1}},[i,g,C,l]);const w=n||m.config.redirects&&m.config.redirects.onFail||"/login";if(p||q)return null;if(!A||!R||i&&!S){if(L==="spa")try{const{Navigate:o}=require("react-router-dom");return u.createElement(o,{to:w,replace:!0})}catch{return window.location.href=w,null}else return window.location.href=w,null;return r}return t}const z=F(t=>({user:null,setUser:e=>t({user:e}),clearUser:()=>t({user:null})}));function B(){const t=c.ref(null),e=c.ref(!0),r=c.ref(null);return a().fetchUser().then(s=>{t.value=s,e.value=!1}).catch(s=>{r.value=s,e.value=!1}),{user:t,isLoading:e,error:r,isAuthenticated:c.computed(()=>!!t.value)}}function J(){const t=d.writable(null),e=d.writable(!0),r=d.writable(null);a().fetchUser().then(s=>{t.set(s),e.set(!1)}).catch(s=>{r.set(s),e.set(!1)});const n=d.derived(t,s=>!!s);return{user:t,isLoading:e,error:r,isAuthenticated:n}}function K(){const t=h.useSignal(null),e=h.useSignal(!0),r=h.useSignal(null);return h.useTask$(async()=>{try{t.value=await a().fetchUser()}catch(n){r.value=n}finally{e.value=!1}}),{user:t,isLoading:e,error:r,isAuthenticated:()=>!!t.value}}function N(){const[t,e]=u.useState(null),[r,n]=u.useState(!0),[s,i]=u.useState(null);return u.useEffect(()=>{a().fetchUser().then(e).catch(i).finally(()=>n(!1))},[]),{user:t,isLoading:r,error:s,isAuthenticated:!!t}}function O(){const[t]=M.createResource(()=>a().fetchUser());return[t,{isAuthenticated:()=>!!t()}]}exports.VormiaGuardClient=V;exports.VrmGuard=j;exports.createGuardClient=$;exports.createVormiaGuardResource=O;exports.createVormiaGuardStore=J;exports.getGlobalGuardClient=a;exports.useVormiaGuardAstro=N;exports.useVormiaGuardQwik=K;exports.useVormiaGuardVue=B;exports.useVrmAuthStore=z;exports.useVrmGuard=v;exports.useVrmLogin=I;exports.useVrmLogout=Q;