@mhiliger/auth-fe 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ (function(v,F){typeof exports=="object"&&typeof module<"u"?F(exports,require("react"),require("@tanstack/react-query"),require("react-router-dom"),require("react-hook-form"),require("jwt-decode"),require("@mui/material"),require("@hookform/resolvers"),require("yup")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","react-router-dom","react-hook-form","jwt-decode","@mui/material","@hookform/resolvers","yup"],F):(v=typeof globalThis<"u"?globalThis:v||self,F(v.AuthFE={},v.React,v.ReactQuery,v.reactRouterDom,v.reactHookForm,v.jwt_decode,v.MaterialUI,v.resolvers,v.Yup))})(this,function(v,F,D,j,M,Ge,t,ye,Je){"use strict";function Xe(n){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const c in n)if(c!=="default"){const u=Object.getOwnPropertyDescriptor(n,c);Object.defineProperty(a,c,u.get?u:{enumerable:!0,get:()=>n[c]})}}return a.default=n,Object.freeze(a)}const A=Xe(Je);var ae={exports:{}},X={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.min.js
4
+ *
5
+ * Copyright (c) Facebook, Inc. and its affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var ve;function Ze(){if(ve)return X;ve=1;var n=F,a=Symbol.for("react.element"),c=Symbol.for("react.fragment"),u=Object.prototype.hasOwnProperty,h=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};function x(i,l,g){var d,T={},S=null,R=null;g!==void 0&&(S=""+g),l.key!==void 0&&(S=""+l.key),l.ref!==void 0&&(R=l.ref);for(d in l)u.call(l,d)&&!p.hasOwnProperty(d)&&(T[d]=l[d]);if(i&&i.defaultProps)for(d in l=i.defaultProps,l)T[d]===void 0&&(T[d]=l[d]);return{$$typeof:a,type:i,key:S,ref:R,props:T,_owner:h.current}}return X.Fragment=c,X.jsx=x,X.jsxs=x,X}var Z={};/**
10
+ * @license React
11
+ * react-jsx-runtime.development.js
12
+ *
13
+ * Copyright (c) Facebook, Inc. and its affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var me;function He(){return me||(me=1,process.env.NODE_ENV!=="production"&&function(){var n=F,a=Symbol.for("react.element"),c=Symbol.for("react.portal"),u=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),p=Symbol.for("react.profiler"),x=Symbol.for("react.provider"),i=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),R=Symbol.for("react.offscreen"),P=Symbol.iterator,q="@@iterator";function L(e){if(e===null||typeof e!="object")return null;var s=P&&e[P]||e[q];return typeof s=="function"?s:null}var B=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(e){{for(var s=arguments.length,o=new Array(s>1?s-1:0),f=1;f<s;f++)o[f-1]=arguments[f];Y("error",e,o)}}function Y(e,s,o){{var f=B.ReactDebugCurrentFrame,b=f.getStackAddendum();b!==""&&(s+="%s",o=o.concat([b]));var E=o.map(function(m){return String(m)});E.unshift("Warning: "+s),Function.prototype.apply.call(console[e],console,E)}}var V=!1,O=!1,z=!1,te=!1,H=!1,Te;Te=Symbol.for("react.module.reference");function gr(e){return!!(typeof e=="string"||typeof e=="function"||e===u||e===p||H||e===h||e===g||e===d||te||e===R||V||O||z||typeof e=="object"&&e!==null&&(e.$$typeof===S||e.$$typeof===T||e.$$typeof===x||e.$$typeof===i||e.$$typeof===l||e.$$typeof===Te||e.getModuleId!==void 0))}function yr(e,s,o){var f=e.displayName;if(f)return f;var b=s.displayName||s.name||"";return b!==""?o+"("+b+")":o}function Ee(e){return e.displayName||"Context"}function W(e){if(e==null)return null;if(typeof e.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case u:return"Fragment";case c:return"Portal";case p:return"Profiler";case h:return"StrictMode";case g:return"Suspense";case d:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case i:var s=e;return Ee(s)+".Consumer";case x:var o=e;return Ee(o._context)+".Provider";case l:return yr(e,e.render,"ForwardRef");case T:var f=e.displayName||null;return f!==null?f:W(e.type)||"Memo";case S:{var b=e,E=b._payload,m=b._init;try{return W(m(E))}catch{return null}}}return null}var $=Object.assign,Q=0,Se,Re,Pe,_e,ke,Ae,Oe;function Ce(){}Ce.__reactDisabledLog=!0;function vr(){{if(Q===0){Se=console.log,Re=console.info,Pe=console.warn,_e=console.error,ke=console.group,Ae=console.groupCollapsed,Oe=console.groupEnd;var e={configurable:!0,enumerable:!0,value:Ce,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}Q++}}function mr(){{if(Q--,Q===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:$({},e,{value:Se}),info:$({},e,{value:Re}),warn:$({},e,{value:Pe}),error:$({},e,{value:_e}),group:$({},e,{value:ke}),groupCollapsed:$({},e,{value:Ae}),groupEnd:$({},e,{value:Oe})})}Q<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ce=B.ReactCurrentDispatcher,le;function se(e,s,o){{if(le===void 0)try{throw Error()}catch(b){var f=b.stack.trim().match(/\n( *(at )?)/);le=f&&f[1]||""}return`
18
+ `+le+e}}var de=!1,ne;{var jr=typeof WeakMap=="function"?WeakMap:Map;ne=new jr}function Fe(e,s){if(!e||de)return"";{var o=ne.get(e);if(o!==void 0)return o}var f;de=!0;var b=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var E;E=ce.current,ce.current=null,vr();try{if(s){var m=function(){throw Error()};if(Object.defineProperty(m.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(m,[])}catch(N){f=N}Reflect.construct(e,[],m)}else{try{m.call()}catch(N){f=N}e.call(m.prototype)}}else{try{throw Error()}catch(N){f=N}e()}}catch(N){if(N&&f&&typeof N.stack=="string"){for(var y=N.stack.split(`
19
+ `),C=f.stack.split(`
20
+ `),_=y.length-1,k=C.length-1;_>=1&&k>=0&&y[_]!==C[k];)k--;for(;_>=1&&k>=0;_--,k--)if(y[_]!==C[k]){if(_!==1||k!==1)do if(_--,k--,k<0||y[_]!==C[k]){var I=`
21
+ `+y[_].replace(" at new "," at ");return e.displayName&&I.includes("<anonymous>")&&(I=I.replace("<anonymous>",e.displayName)),typeof e=="function"&&ne.set(e,I),I}while(_>=1&&k>=0);break}}}finally{de=!1,ce.current=E,mr(),Error.prepareStackTrace=b}var J=e?e.displayName||e.name:"",U=J?se(J):"";return typeof e=="function"&&ne.set(e,U),U}function br(e,s,o){return Fe(e,!1)}function wr(e){var s=e.prototype;return!!(s&&s.isReactComponent)}function ie(e,s,o){if(e==null)return"";if(typeof e=="function")return Fe(e,wr(e));if(typeof e=="string")return se(e);switch(e){case g:return se("Suspense");case d:return se("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case l:return br(e.render);case T:return ie(e.type,s,o);case S:{var f=e,b=f._payload,E=f._init;try{return ie(E(b),s,o)}catch{}}}return""}var ee=Object.prototype.hasOwnProperty,qe={},Be=B.ReactDebugCurrentFrame;function oe(e){if(e){var s=e._owner,o=ie(e.type,e._source,s?s.type:null);Be.setExtraStackFrame(o)}else Be.setExtraStackFrame(null)}function Tr(e,s,o,f,b){{var E=Function.call.bind(ee);for(var m in e)if(E(e,m)){var y=void 0;try{if(typeof e[m]!="function"){var C=Error((f||"React class")+": "+o+" type `"+m+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[m]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw C.name="Invariant Violation",C}y=e[m](s,m,f,o,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(_){y=_}y&&!(y instanceof Error)&&(oe(b),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",f||"React class",o,m,typeof y),oe(null)),y instanceof Error&&!(y.message in qe)&&(qe[y.message]=!0,oe(b),w("Failed %s type: %s",o,y.message),oe(null))}}}var Er=Array.isArray;function fe(e){return Er(e)}function Sr(e){{var s=typeof Symbol=="function"&&Symbol.toStringTag,o=s&&e[Symbol.toStringTag]||e.constructor.name||"Object";return o}}function Rr(e){try{return Ne(e),!1}catch{return!0}}function Ne(e){return""+e}function Le(e){if(Rr(e))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Sr(e)),Ne(e)}var Ve=B.ReactCurrentOwner,Pr={key:!0,ref:!0,__self:!0,__source:!0},Ie,Ye;function _r(e){if(ee.call(e,"ref")){var s=Object.getOwnPropertyDescriptor(e,"ref").get;if(s&&s.isReactWarning)return!1}return e.ref!==void 0}function kr(e){if(ee.call(e,"key")){var s=Object.getOwnPropertyDescriptor(e,"key").get;if(s&&s.isReactWarning)return!1}return e.key!==void 0}function Ar(e,s){typeof e.ref=="string"&&Ve.current}function Or(e,s){{var o=function(){Ie||(Ie=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",s))};o.isReactWarning=!0,Object.defineProperty(e,"key",{get:o,configurable:!0})}}function Cr(e,s){{var o=function(){Ye||(Ye=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",s))};o.isReactWarning=!0,Object.defineProperty(e,"ref",{get:o,configurable:!0})}}var Fr=function(e,s,o,f,b,E,m){var y={$$typeof:a,type:e,key:s,ref:o,props:m,_owner:E};return y._store={},Object.defineProperty(y._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(y,"_self",{configurable:!1,enumerable:!1,writable:!1,value:f}),Object.defineProperty(y,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(y.props),Object.freeze(y)),y};function qr(e,s,o,f,b){{var E,m={},y=null,C=null;o!==void 0&&(Le(o),y=""+o),kr(s)&&(Le(s.key),y=""+s.key),_r(s)&&(C=s.ref,Ar(s,b));for(E in s)ee.call(s,E)&&!Pr.hasOwnProperty(E)&&(m[E]=s[E]);if(e&&e.defaultProps){var _=e.defaultProps;for(E in _)m[E]===void 0&&(m[E]=_[E])}if(y||C){var k=typeof e=="function"?e.displayName||e.name||"Unknown":e;y&&Or(m,k),C&&Cr(m,k)}return Fr(e,y,C,b,f,Ve.current,m)}}var pe=B.ReactCurrentOwner,ze=B.ReactDebugCurrentFrame;function G(e){if(e){var s=e._owner,o=ie(e.type,e._source,s?s.type:null);ze.setExtraStackFrame(o)}else ze.setExtraStackFrame(null)}var he;he=!1;function xe(e){return typeof e=="object"&&e!==null&&e.$$typeof===a}function We(){{if(pe.current){var e=W(pe.current.type);if(e)return`
22
+
23
+ Check the render method of \``+e+"`."}return""}}function Br(e){return""}var De={};function Nr(e){{var s=We();if(!s){var o=typeof e=="string"?e:e.displayName||e.name;o&&(s=`
24
+
25
+ Check the top-level render call using <`+o+">.")}return s}}function $e(e,s){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var o=Nr(s);if(De[o])return;De[o]=!0;var f="";e&&e._owner&&e._owner!==pe.current&&(f=" It was passed a child from "+W(e._owner.type)+"."),G(e),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',o,f),G(null)}}function Ue(e,s){{if(typeof e!="object")return;if(fe(e))for(var o=0;o<e.length;o++){var f=e[o];xe(f)&&$e(f,s)}else if(xe(e))e._store&&(e._store.validated=!0);else if(e){var b=L(e);if(typeof b=="function"&&b!==e.entries)for(var E=b.call(e),m;!(m=E.next()).done;)xe(m.value)&&$e(m.value,s)}}}function Lr(e){{var s=e.type;if(s==null||typeof s=="string")return;var o;if(typeof s=="function")o=s.propTypes;else if(typeof s=="object"&&(s.$$typeof===l||s.$$typeof===T))o=s.propTypes;else return;if(o){var f=W(s);Tr(o,e.props,"prop",f,e)}else if(s.PropTypes!==void 0&&!he){he=!0;var b=W(s);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof s.getDefaultProps=="function"&&!s.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Vr(e){{for(var s=Object.keys(e.props),o=0;o<s.length;o++){var f=s[o];if(f!=="children"&&f!=="key"){G(e),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",f),G(null);break}}e.ref!==null&&(G(e),w("Invalid attribute `ref` supplied to `React.Fragment`."),G(null))}}var Me={};function Ke(e,s,o,f,b,E){{var m=gr(e);if(!m){var y="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(y+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var C=Br();C?y+=C:y+=We();var _;e===null?_="null":fe(e)?_="array":e!==void 0&&e.$$typeof===a?(_="<"+(W(e.type)||"Unknown")+" />",y=" Did you accidentally export a JSX literal instead of a component?"):_=typeof e,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",_,y)}var k=qr(e,s,o,b,E);if(k==null)return k;if(m){var I=s.children;if(I!==void 0)if(f)if(fe(I)){for(var J=0;J<I.length;J++)Ue(I[J],e);Object.freeze&&Object.freeze(I)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Ue(I,e)}if(ee.call(s,"key")){var U=W(e),N=Object.keys(s).filter(function($r){return $r!=="key"}),ge=N.length>0?"{key: someKey, "+N.join(": ..., ")+": ...}":"{key: someKey}";if(!Me[U+ge]){var Dr=N.length>0?"{"+N.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
26
+ let props = %s;
27
+ <%s {...props} />
28
+ React keys must be passed directly to JSX without using spread:
29
+ let props = %s;
30
+ <%s key={someKey} {...props} />`,ge,U,Dr,U),Me[U+ge]=!0}}return e===u?Vr(k):Lr(k),k}}function Ir(e,s,o){return Ke(e,s,o,!0)}function Yr(e,s,o){return Ke(e,s,o,!1)}var zr=Yr,Wr=Ir;Z.Fragment=u,Z.jsx=zr,Z.jsxs=Wr}()),Z}process.env.NODE_ENV==="production"?ae.exports=Ze():ae.exports=He();var r=ae.exports;const ue=F.createContext({}),Qe=({children:n})=>{const[a,c]=F.useState({}),[u,h]=F.useState(void 0);return r.jsx(ue.Provider,{value:{auth:a,setAuth:c,user:u,setUser:h},children:n})},K=()=>{const n=F.useContext(ue);if(!n)throw new Error("useAuth must be used within an AuthProvider");return n},je=(n,a="refresh")=>{const{setAuth:c}=K(),u=()=>n({method:"GET",url:a}),{refetch:h}=D.useQuery({queryKey:["refresh"],queryFn:u,onSuccess:p=>{c(x=>{var i;return{...x,accessToken:(i=p==null?void 0:p.data)==null?void 0:i.accessToken}})},onError:p=>{console.log("Refresh Failed",p)},enabled:!1,retry:!1});return h},er=(n,a="refresh")=>{const{auth:c,setAuth:u}=K(),h=je(n,a);return F.useEffect(()=>{const p=n.interceptors.request.use(i=>(i.headers.authorization||(i.headers.authorization=`Bearer ${c==null?void 0:c.accessToken}`),i),i=>Promise.reject(i)),x=n.interceptors.response.use(i=>i,async i=>{var g,d,T,S,R;const l=i==null?void 0:i.config;if((d=(g=i==null?void 0:i.response)==null?void 0:g.data)!=null&&d.error&&(i.message=`${i.response.data.error} (${i.response.status})`),l.url===a)return Promise.reject(i);if(((T=i==null?void 0:i.response)==null?void 0:T.status)===403&&!(l!=null&&l.sent)){l.sent=!0;try{const P=await h(),q=(R=(S=P==null?void 0:P.data)==null?void 0:S.data)==null?void 0:R.accessToken;return q?(l.headers.authorization=`Bearer ${q}`,n(l)):(u({message:"Session expired. Please login again."}),Promise.reject(i))}catch(P){return u({message:"Session expired. Please login again."}),Promise.reject(P)}}return Promise.reject(i)});return()=>{n.interceptors.request.eject(p),n.interceptors.response.eject(x)}},[c,h,n,a,u]),n},rr=(n,a="auth")=>D.useMutation({mutationFn:c=>n({url:a,method:"POST",data:c}),mutationKey:["login"]}),tr=({allowedPerms:n,unauthorizedPath:a="/unauthorized",loginPath:c="/"})=>{var x;const{auth:u}=K(),h=j.useLocation();return((x=u==null?void 0:u.permissions)==null?void 0:x.some(i=>n==null?void 0:n.includes(i.perm_key)))?r.jsx(j.Outlet,{}):u!=null&&u.email?r.jsx(j.Navigate,{to:a,state:{from:h},replace:!0}):r.jsx(j.Navigate,{to:c,state:{from:h},replace:!0})},sr=({LoginComponent:n,RegisterComponent:a,UnauthorizedComponent:c,LayoutComponent:u=({children:i})=>r.jsx(r.Fragment,{children:i}),postLoginRedirect:h="/",children:p,publicRoutes:x=[]})=>{const{auth:i}=K(),l=!!i.email;return r.jsxs(j.Routes,{children:[x.map(({path:g,element:d})=>r.jsx(j.Route,{element:r.jsx(u,{}),children:r.jsx(j.Route,{path:g,element:d})},g)),l?r.jsxs(j.Route,{element:r.jsx(u,{}),children:[p,r.jsx(j.Route,{path:"/unauthorized",element:r.jsx(c,{})}),r.jsx(j.Route,{path:"*",element:r.jsx(j.Navigate,{to:h,replace:!0})})]}):r.jsxs(j.Route,{element:r.jsx(u,{}),children:[r.jsx(j.Route,{path:"/login",element:r.jsx(n,{successRoute:h})}),r.jsx(j.Route,{path:"/register",element:r.jsx(a,{})}),r.jsx(j.Route,{path:"*",element:r.jsx(j.Navigate,{to:"/login",replace:!0})})]})]})},nr=({loginMutation:n,successRoute:a="/",registerPath:c="/register",resetPath:u="/forgot-password",allowStay:h=!1,onLoginSuccess:p})=>{var L,B;const[x,i]=F.useState(""),{auth:l,setAuth:g}=K(),d=j.useNavigate(),T=M.useForm({defaultValues:{email:"",password:"",stayLoggedIn:!1}}),{handleSubmit:S,register:R,formState:{errors:P}}=T,q=w=>{i(""),n.mutate(w)};return F.useEffect(()=>{var w,Y;if(n.isSuccess){i("");try{const V=(Y=(w=n.data)==null?void 0:w.data)==null?void 0:Y.accessToken,O=Ge(V);if(O.status!=="ACTIVE"){i("Successful login... but user is not Active. See system administrator");return}const z={userId:O.userId,email:O.email,first:O.first,last:O.last,status:O.status,permissions:O.permissions,accessToken:V};g(z),p&&p(z),d(a)}catch(V){console.error("Token decoding error:",V),i("Error processing login response")}}},[n.isSuccess,n.data,d,g,a,p]),F.useEffect(()=>{var w,Y,V,O;if(n.isError){const z=((V=(Y=(w=n.error)==null?void 0:w.response)==null?void 0:Y.data)==null?void 0:V.error)||((O=n.error)==null?void 0:O.message);i(z)}},[n.isError,n.error]),r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"33%"},margin:"auto",padding:"20px"},children:[n.isLoading&&r.jsx(t.Alert,{severity:"info",children:"Logging on to system..."}),x&&r.jsx(t.Alert,{severity:"error",children:x}),r.jsx(t.Typography,{variant:"h5",children:"Login"}),r.jsx("form",{onSubmit:S(q),noValidate:!0,children:r.jsxs(t.Stack,{spacing:2,children:[r.jsx(t.TextField,{...R("email"),label:"Email",type:"email",placeholder:"Enter email",margin:"normal",size:"small",error:!!P.email,helperText:(L=P.email)==null?void 0:L.message}),r.jsx(t.TextField,{...R("password"),label:"Password",type:"password",placeholder:"Enter password",margin:"normal",size:"small",error:!!P.password,helperText:(B=P.password)==null?void 0:B.message}),r.jsx(t.Box,{sx:{mt:2},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:u,children:"Reset Password"})}),r.jsx(t.Button,{sx:{margin:"10px"},variant:"outlined",type:"submit",children:"Submit"})]})}),r.jsx(t.Box,{sx:{mt:2},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:c,children:"Register to Login"})})]})};function re(n,a,c){return a===void 0&&(a={}),c===void 0&&(c={}),function(u,h,p){try{return Promise.resolve(function(x,i){try{var l=(a.context&&process.env.NODE_ENV==="development"&&console.warn("You should not used the yup options context. Please, use the 'useForm' context object instead"),Promise.resolve(n[c.mode==="sync"?"validateSync":"validate"](u,Object.assign({abortEarly:!1},a,{context:h}))).then(function(g){return p.shouldUseNativeValidation&&ye.validateFieldsNatively({},p),{values:c.raw?u:g,errors:{}}}))}catch(g){return i(g)}return l&&l.then?l.then(void 0,i):l}(0,function(x){if(!x.inner)throw x;return{values:{},errors:ye.toNestErrors((i=x,l=!p.shouldUseNativeValidation&&p.criteriaMode==="all",(i.inner||[]).reduce(function(g,d){if(g[d.path]||(g[d.path]={message:d.message,type:d.type}),l){var T=g[d.path].types,S=T&&T[d.type];g[d.path]=M.appendErrors(d.path,l,g,d.type,S?[].concat(S,d.message):d.message)}return g},{})),p)};var i,l}))}catch(x){return Promise.reject(x)}}}const ir=({onSubmit:n,loginPath:a="/login"})=>{var d,T,S;j.useNavigate();const c=/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%]).{8,24}$/,h=A.object().shape({email:A.string().email("Invalid email").required("Required"),password:A.string().matches(c,"8 - 24 characters, must include uppercase and lowercase letters, a number and a special character").required("Required"),confirmPwd:A.string().oneOf([A.ref("password"),null],"Passwords must match").required("Required")}),p=M.useForm({defaultValues:{email:"",password:"",confirmPwd:""},resolver:re(h)}),{handleSubmit:x,register:i,formState:{errors:l}}=p,g=R=>{n?n(R):console.log("Registration submitted:",R)};return r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"33%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",children:"Register"}),r.jsx("form",{onSubmit:x(g),noValidate:!0,children:r.jsxs(t.Stack,{spacing:2,children:[r.jsx(t.TextField,{...i("email"),label:"Email",type:"email",placeholder:"Enter email",margin:"normal",size:"small",error:!!l.email,helperText:(d=l.email)==null?void 0:d.message}),r.jsx(t.TextField,{...i("password"),label:"Password",type:"password",placeholder:"Enter password",margin:"normal",size:"small",error:!!l.password,helperText:(T=l.password)==null?void 0:T.message}),r.jsx(t.TextField,{...i("confirmPwd"),label:"Confirm Password",type:"password",placeholder:"Re-enter Password",margin:"normal",size:"small",error:!!l.confirmPwd,helperText:(S=l.confirmPwd)==null?void 0:S.message}),r.jsx(t.Button,{sx:{margin:"10px"},variant:"outlined",type:"submit",children:"Submit"})]})}),r.jsx(t.Box,{sx:{mt:2},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:a,children:"Login if already a user"})})]})},or=()=>r.jsxs(t.Stack,{sx:{margin:"10vh",alignItems:"center"},children:[r.jsx(t.Typography,{variant:"h4",children:"You are not authorized to access this page."}),r.jsx("br",{}),r.jsx("br",{}),r.jsx(t.Typography,{variant:"h5",children:"Contact your system administrator for access rights."})]}),ar=({onSubmit:n,isLoading:a=!1,isSuccess:c=!1,successMessage:u="If this email is not already registered, you will receive a verification email shortly.",error:h,loginPath:p="/login"})=>{var S,R,P,q,L,B;const x=A.object().shape({email:A.string().email("Invalid email").required("Email is required"),first:A.string().required("First name is required"),last:A.string().required("Last name is required"),requestNote:A.string().max(256,"Request note must be 256 characters or less")}),i=M.useForm({defaultValues:{email:"",first:"",last:"",requestNote:""},resolver:re(x)}),{handleSubmit:l,register:g,formState:{errors:d}}=i,T=w=>{n&&n(w)};return c?r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Registration Submitted"}),r.jsx(t.Alert,{severity:"success",sx:{mb:2},children:u}),r.jsx(t.Typography,{variant:"body1",paragraph:!0,children:"Please check your email for a verification link. The link will expire in 24 hours."}),r.jsx(t.Typography,{variant:"body2",color:"text.secondary",children:"If you don't receive an email within a few minutes, check your spam folder."}),r.jsx(t.Box,{sx:{mt:3},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:p,children:"Return to Login"})})]}):r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Request Access"}),r.jsx(t.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Fill out this form to request access. An administrator will review your request after you verify your email."}),h&&r.jsx(t.Alert,{severity:"error",sx:{mb:2},children:((R=(S=h.response)==null?void 0:S.data)==null?void 0:R.error)||h.message||"An error occurred"}),r.jsx("form",{onSubmit:l(T),noValidate:!0,children:r.jsxs(t.Stack,{spacing:2,children:[r.jsx(t.TextField,{...g("email"),label:"Email",type:"email",placeholder:"Enter your email",margin:"normal",size:"small",required:!0,error:!!d.email,helperText:(P=d.email)==null?void 0:P.message}),r.jsx(t.TextField,{...g("first"),label:"First Name",type:"text",placeholder:"Enter your first name",margin:"normal",size:"small",required:!0,error:!!d.first,helperText:(q=d.first)==null?void 0:q.message}),r.jsx(t.TextField,{...g("last"),label:"Last Name",type:"text",placeholder:"Enter your last name",margin:"normal",size:"small",required:!0,error:!!d.last,helperText:(L=d.last)==null?void 0:L.message}),r.jsx(t.TextField,{...g("requestNote"),label:"Request Note (Optional)",type:"text",placeholder:"Why do you need access?",margin:"normal",size:"small",multiline:!0,rows:3,error:!!d.requestNote,helperText:((B=d.requestNote)==null?void 0:B.message)||"Max 256 characters"}),r.jsx(t.Button,{sx:{margin:"10px"},variant:"contained",type:"submit",disabled:a,children:a?r.jsx(t.CircularProgress,{size:24}):"Submit Request"})]})}),r.jsx(t.Box,{sx:{mt:2},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:p,children:"Already have an account? Login"})})]})},ur=({isLoading:n=!1,isSuccess:a=!1,isError:c=!1,error:u,data:h,loginPath:p="/login"})=>{var x,i;if(n)return r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px",textAlign:"center"},children:[r.jsx(t.CircularProgress,{size:48,sx:{mb:2}}),r.jsx(t.Typography,{variant:"h6",children:"Verifying your email..."})]});if(c){const l=((i=(x=u==null?void 0:u.response)==null?void 0:x.data)==null?void 0:i.error)||(u==null?void 0:u.message)||"Verification failed";return r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Verification Failed"}),r.jsx(t.Alert,{severity:"error",sx:{mb:2},children:l}),r.jsx(t.Typography,{variant:"body1",paragraph:!0,children:"The verification link may have expired or already been used."}),r.jsx(t.Typography,{variant:"body2",color:"text.secondary",children:"If you need a new verification link, please submit a new registration request."}),r.jsxs(t.Box,{sx:{mt:3},children:[r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:"/register",children:"Submit New Request"}),r.jsx(t.Box,{component:"span",sx:{mx:2},children:"|"}),r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:p,children:"Return to Login"})]})]})}return a?r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Email Verified"}),r.jsx(t.Alert,{severity:"success",sx:{mb:2},children:(h==null?void 0:h.message)||"Your email has been verified successfully."}),r.jsx(t.Typography,{variant:"body1",paragraph:!0,children:"Your request is now pending administrator review."}),r.jsx(t.Typography,{variant:"body2",color:"text.secondary",children:"You will receive an email when your request has been reviewed. This typically takes 1-2 business days."}),r.jsx(t.Box,{sx:{mt:3},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:p,children:"Return to Login"})})]}):r.jsx(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px",textAlign:"center"},children:r.jsx(t.Typography,{variant:"h6",children:"Processing verification..."})})},cr=({isValidating:n=!1,isValidToken:a=!1,validationError:c,userEmail:u,userFirst:h,onSubmit:p,isSubmitting:x=!1,isSuccess:i=!1,submitError:l,loginPath:g="/login",passwordRegex:d=/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%]).{8,24}$/,passwordMessage:T="8-24 characters, must include uppercase and lowercase letters, a number and a special character (!@#$%)"})=>{var w,Y,V,O,z,te;const S=A.object().shape({password:A.string().matches(d,T).required("Password is required"),confirmPassword:A.string().oneOf([A.ref("password"),null],"Passwords must match").required("Please confirm your password")}),R=M.useForm({defaultValues:{password:"",confirmPassword:""},resolver:re(S)}),{handleSubmit:P,register:q,formState:{errors:L}}=R,B=H=>{p&&p({password:H.password})};if(n)return r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px",textAlign:"center"},children:[r.jsx(t.CircularProgress,{size:48,sx:{mb:2}}),r.jsx(t.Typography,{variant:"h6",children:"Validating your link..."})]});if(!a&&!n){const H=((Y=(w=c==null?void 0:c.response)==null?void 0:w.data)==null?void 0:Y.error)||(c==null?void 0:c.message)||"Invalid or expired link";return r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Invalid Link"}),r.jsx(t.Alert,{severity:"error",sx:{mb:2},children:H}),r.jsx(t.Typography,{variant:"body1",paragraph:!0,children:"This password setup link is invalid or has expired."}),r.jsx(t.Typography,{variant:"body2",color:"text.secondary",children:"If you believe this is an error, please contact an administrator."}),r.jsx(t.Box,{sx:{mt:3},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:g,children:"Return to Login"})})]})}return i?r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Password Set Successfully"}),r.jsx(t.Alert,{severity:"success",sx:{mb:2},children:"Your password has been set. You can now log in to your account."}),r.jsx(t.Box,{sx:{mt:3},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:g,children:"Go to Login"})})]}):r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Set Your Password"}),h&&r.jsxs(t.Typography,{variant:"body1",sx:{mb:1},children:["Welcome, ",h,"!"]}),u&&r.jsxs(t.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["Setting password for: ",u]}),l&&r.jsx(t.Alert,{severity:"error",sx:{mb:2},children:((O=(V=l.response)==null?void 0:V.data)==null?void 0:O.error)||l.message||"An error occurred"}),r.jsx("form",{onSubmit:P(B),noValidate:!0,children:r.jsxs(t.Stack,{spacing:2,children:[r.jsx(t.TextField,{...q("password"),label:"Password",type:"password",placeholder:"Enter your password",margin:"normal",size:"small",required:!0,error:!!L.password,helperText:(z=L.password)==null?void 0:z.message}),r.jsx(t.Typography,{variant:"caption",color:"text.secondary",children:T}),r.jsx(t.TextField,{...q("confirmPassword"),label:"Confirm Password",type:"password",placeholder:"Re-enter your password",margin:"normal",size:"small",required:!0,error:!!L.confirmPassword,helperText:(te=L.confirmPassword)==null?void 0:te.message}),r.jsx(t.Button,{sx:{margin:"10px"},variant:"contained",type:"submit",disabled:x,children:x?r.jsx(t.CircularProgress,{size:24}):"Set Password"})]})})]})},lr=({title:n="Registration Complete",message:a="Your account is now active. You can log in with your credentials.",loginPath:c="/login"})=>r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:n}),r.jsx(t.Alert,{severity:"success",sx:{mb:2},children:a}),r.jsx(t.Box,{sx:{mt:3},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:c,children:"Go to Login"})})]}),dr=({onSubmit:n,isLoading:a=!1,isSuccess:c=!1,successMessage:u="If an account exists for this email, you will receive a password reset link shortly.",error:h,loginPath:p="/login"})=>{var S,R,P;const x=A.object().shape({email:A.string().email("Invalid email").required("Email is required")}),i=M.useForm({defaultValues:{email:""},resolver:re(x)}),{handleSubmit:l,register:g,formState:{errors:d}}=i,T=q=>{n&&n(q)};return c?r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Reset Link Sent"}),r.jsx(t.Alert,{severity:"success",sx:{mb:2},children:u}),r.jsx(t.Typography,{variant:"body1",paragraph:!0,children:"Please check your email for a link to reset your password."}),r.jsx(t.Box,{sx:{mt:3},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:p,children:"Return to Login"})})]}):r.jsxs(t.Box,{sx:{width:{xs:"90%",md:"50%"},margin:"auto",padding:"20px"},children:[r.jsx(t.Typography,{variant:"h5",gutterBottom:!0,children:"Reset Password"}),r.jsx(t.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"Enter your email address below and we'll send you a link to reset your password."}),h&&r.jsx(t.Alert,{severity:"error",sx:{mb:2},children:((R=(S=h.response)==null?void 0:S.data)==null?void 0:R.error)||h.message||"An error occurred"}),r.jsx("form",{onSubmit:l(T),noValidate:!0,children:r.jsxs(t.Stack,{spacing:2,children:[r.jsx(t.TextField,{...g("email"),label:"Email",type:"email",placeholder:"Enter your email",margin:"normal",size:"small",required:!0,error:!!d.email,helperText:(P=d.email)==null?void 0:P.message}),r.jsx(t.Button,{sx:{margin:"10px"},variant:"contained",type:"submit",disabled:a,children:a?r.jsx(t.CircularProgress,{size:24}):"Send Reset Link"})]})}),r.jsx(t.Box,{sx:{mt:2},children:r.jsx(j.NavLink,{style:{textDecoration:"underline"},to:p,children:"Back to Login"})})]})},fr=(n,a="/register/submit")=>D.useMutation({mutationFn:async({email:c,first:u,last:h,requestNote:p})=>(await n.post(a,{email:c,first:u,last:h,requestNote:p})).data}),pr=(n,a,c="/register/verify")=>D.useQuery({queryKey:["emailVerification",a],queryFn:async()=>{if(!a)throw new Error("No verification token provided");return(await n.get(`${c}/${a}`)).data},enabled:!!a,retry:!1,refetchOnWindowFocus:!1}),be=(n,a,c="/register/setup")=>D.useQuery({queryKey:["validateSetupToken",a],queryFn:async()=>{if(!a)throw new Error("No setup token provided");return(await n.get(`${c}/${a}`)).data},enabled:!!a,retry:!1,refetchOnWindowFocus:!1}),we=(n,a="/register/setup")=>D.useMutation({mutationFn:async({token:c,password:u})=>(await n.post(`${a}/${c}`,{password:u})).data}),hr=(n,a="/register/forgot-password")=>D.useMutation({mutationFn:async({email:c})=>(await n.post(a,{email:c})).data}),xr=(n,a,c="/register/setup")=>{var p,x,i;const u=be(n,a,c),h=we(n,c);return{validation:u,setPassword:h,isValidToken:u.isSuccess&&((p=u.data)==null?void 0:p.valid),userEmail:(x=u.data)==null?void 0:x.email,userFirst:(i=u.data)==null?void 0:i.first}};v.AuthContext=ue,v.AuthProvider=Qe,v.EmailVerification=ur,v.Login=nr,v.PasswordResetRequest=dr,v.PasswordSetup=cr,v.Register=ir,v.RegistrationRequest=ar,v.RegistrationSuccess=lr,v.RequireAuth=tr,v.StandardAuthRoutes=sr,v.Unauthorized=or,v.useAuth=K,v.useEmailVerification=pr,v.useLogin=rr,v.usePasswordSetup=xr,v.useRefreshToken=je,v.useRegistrationSubmit=fr,v.useRequestPasswordReset=hr,v.useSecureAxios=er,v.useSetPassword=we,v.useValidateSetupToken=be,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@mhiliger/auth-fe",
3
+ "version": "1.0.0",
4
+ "description": "Shared authentication and JWT management for React",
5
+ "main": "dist/auth-fe.umd.js",
6
+ "module": "dist/auth-fe.es.js",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/auth-fe.es.js",
10
+ "require": "./dist/auth-fe.umd.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "scripts": {
17
+ "build": "vite build",
18
+ "test": "echo \"Error: no test specified\" && exit 1"
19
+ },
20
+ "peerDependencies": {
21
+ "@emotion/react": "^11.0.0",
22
+ "@emotion/styled": "^11.0.0",
23
+ "@hookform/resolvers": "^2.0.0 || ^3.0.0",
24
+ "@mui/material": "^5.0.0",
25
+ "@tanstack/react-query": "^4.0.0 || ^5.0.0",
26
+ "axios": "^0.27.0 || ^1.0.0",
27
+ "jwt-decode": "^3.0.0 || ^4.0.0",
28
+ "react": "^18.0.0",
29
+ "react-dom": "^18.0.0",
30
+ "react-hook-form": "^7.0.0",
31
+ "react-router-dom": "^6.0.0",
32
+ "yup": "^0.32.0 || ^1.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "@vitejs/plugin-react": "^4.2.0",
36
+ "vite": "^5.0.0",
37
+ "react": "^18.2.0",
38
+ "react-dom": "^18.2.0"
39
+ }
40
+ }