thecore-auth 0.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(C,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("react"),require("react-router-dom"),require("axios")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom","axios"],c):(C=typeof globalThis<"u"?globalThis:C||self,c(C["thecore-auth"]={},C.React,C.ReactRouterDOM,C.axios))})(this,function(C,c,V,ft){"use strict";var oe={exports:{}},H={};/**
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 _e;function dt(){if(_e)return H;_e=1;var t=c,n=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,u=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,f={key:!0,ref:!0,__self:!0,__source:!0};function v(p,d,w){var E,b={},S=null,P=null;w!==void 0&&(S=""+w),d.key!==void 0&&(S=""+d.key),d.ref!==void 0&&(P=d.ref);for(E in d)a.call(d,E)&&!f.hasOwnProperty(E)&&(b[E]=d[E]);if(p&&p.defaultProps)for(E in d=p.defaultProps,d)b[E]===void 0&&(b[E]=d[E]);return{$$typeof:n,type:p,key:S,ref:P,props:b,_owner:u.current}}return H.Fragment=o,H.jsx=v,H.jsxs=v,H}var X={};/**
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 Pe;function gt(){return Pe||(Pe=1,process.env.NODE_ENV!=="production"&&function(){var t=c,n=Symbol.for("react.element"),o=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),u=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),v=Symbol.for("react.provider"),p=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),b=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),P=Symbol.for("react.offscreen"),$=Symbol.iterator,F="@@iterator";function A(e){if(e===null||typeof e!="object")return null;var r=$&&e[$]||e[F];return typeof r=="function"?r:null}var y=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function j(e){{for(var r=arguments.length,s=new Array(r>1?r-1:0),l=1;l<r;l++)s[l-1]=arguments[l];D("error",e,s)}}function D(e,r,s){{var l=y.ReactDebugCurrentFrame,m=l.getStackAddendum();m!==""&&(r+="%s",s=s.concat([m]));var x=s.map(function(h){return String(h)});x.unshift("Warning: "+r),Function.prototype.apply.call(console[e],console,x)}}var N=!1,ee=!1,te=!1,O=!1,I=!1,z;z=Symbol.for("react.module.reference");function M(e){return!!(typeof e=="string"||typeof e=="function"||e===a||e===f||I||e===u||e===w||e===E||O||e===P||N||ee||te||typeof e=="object"&&e!==null&&(e.$$typeof===S||e.$$typeof===b||e.$$typeof===v||e.$$typeof===p||e.$$typeof===d||e.$$typeof===z||e.getModuleId!==void 0))}function ue(e,r,s){var l=e.displayName;if(l)return l;var m=r.displayName||r.name||"";return m!==""?s+"("+m+")":s}function J(e){return e.displayName||"Context"}function W(e){if(e==null)return null;if(typeof e.tag=="number"&&j("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 a:return"Fragment";case o:return"Portal";case f:return"Profiler";case u:return"StrictMode";case w:return"Suspense";case E:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case p:var r=e;return J(r)+".Consumer";case v:var s=e;return J(s._context)+".Provider";case d:return ue(e,e.render,"ForwardRef");case b:var l=e.displayName||null;return l!==null?l:W(e.type)||"Memo";case S:{var m=e,x=m._payload,h=m._init;try{return W(h(x))}catch{return null}}}return null}var B=Object.assign,re=0,Be,Ue,Ve,Ye,qe,Je,Ke;function Ge(){}Ge.__reactDisabledLog=!0;function Dt(){{if(re===0){Be=console.log,Ue=console.info,Ve=console.warn,Ye=console.error,qe=console.group,Je=console.groupCollapsed,Ke=console.groupEnd;var e={configurable:!0,enumerable:!0,value:Ge,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}re++}}function Ft(){{if(re--,re===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:B({},e,{value:Be}),info:B({},e,{value:Ue}),warn:B({},e,{value:Ve}),error:B({},e,{value:Ye}),group:B({},e,{value:qe}),groupCollapsed:B({},e,{value:Je}),groupEnd:B({},e,{value:Ke})})}re<0&&j("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ye=y.ReactCurrentDispatcher,xe;function ce(e,r,s){{if(xe===void 0)try{throw Error()}catch(m){var l=m.stack.trim().match(/\n( *(at )?)/);xe=l&&l[1]||""}return`
18
+ `+xe+e}}var we=!1,fe;{var Mt=typeof WeakMap=="function"?WeakMap:Map;fe=new Mt}function He(e,r){if(!e||we)return"";{var s=fe.get(e);if(s!==void 0)return s}var l;we=!0;var m=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var x;x=ye.current,ye.current=null,Dt();try{if(r){var h=function(){throw Error()};if(Object.defineProperty(h.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(h,[])}catch(R){l=R}Reflect.construct(e,[],h)}else{try{h.call()}catch(R){l=R}e.call(h.prototype)}}else{try{throw Error()}catch(R){l=R}e()}}catch(R){if(R&&l&&typeof R.stack=="string"){for(var g=R.stack.split(`
19
+ `),k=l.stack.split(`
20
+ `),T=g.length-1,_=k.length-1;T>=1&&_>=0&&g[T]!==k[_];)_--;for(;T>=1&&_>=0;T--,_--)if(g[T]!==k[_]){if(T!==1||_!==1)do if(T--,_--,_<0||g[T]!==k[_]){var L=`
21
+ `+g[T].replace(" at new "," at ");return e.displayName&&L.includes("<anonymous>")&&(L=L.replace("<anonymous>",e.displayName)),typeof e=="function"&&fe.set(e,L),L}while(T>=1&&_>=0);break}}}finally{we=!1,ye.current=x,Ft(),Error.prepareStackTrace=m}var G=e?e.displayName||e.name:"",U=G?ce(G):"";return typeof e=="function"&&fe.set(e,U),U}function zt(e,r,s){return He(e,!1)}function Wt(e){var r=e.prototype;return!!(r&&r.isReactComponent)}function de(e,r,s){if(e==null)return"";if(typeof e=="function")return He(e,Wt(e));if(typeof e=="string")return ce(e);switch(e){case w:return ce("Suspense");case E:return ce("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case d:return zt(e.render);case b:return de(e.type,r,s);case S:{var l=e,m=l._payload,x=l._init;try{return de(x(m),r,s)}catch{}}}return""}var ne=Object.prototype.hasOwnProperty,Xe={},Ze=y.ReactDebugCurrentFrame;function ge(e){if(e){var r=e._owner,s=de(e.type,e._source,r?r.type:null);Ze.setExtraStackFrame(s)}else Ze.setExtraStackFrame(null)}function Bt(e,r,s,l,m){{var x=Function.call.bind(ne);for(var h in e)if(x(e,h)){var g=void 0;try{if(typeof e[h]!="function"){var k=Error((l||"React class")+": "+s+" type `"+h+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[h]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw k.name="Invariant Violation",k}g=e[h](r,h,l,s,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(T){g=T}g&&!(g instanceof Error)&&(ge(m),j("%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).",l||"React class",s,h,typeof g),ge(null)),g instanceof Error&&!(g.message in Xe)&&(Xe[g.message]=!0,ge(m),j("Failed %s type: %s",s,g.message),ge(null))}}}var Ut=Array.isArray;function Ee(e){return Ut(e)}function Vt(e){{var r=typeof Symbol=="function"&&Symbol.toStringTag,s=r&&e[Symbol.toStringTag]||e.constructor.name||"Object";return s}}function Yt(e){try{return Qe(e),!1}catch{return!0}}function Qe(e){return""+e}function et(e){if(Yt(e))return j("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Vt(e)),Qe(e)}var tt=y.ReactCurrentOwner,qt={key:!0,ref:!0,__self:!0,__source:!0},rt,nt;function Jt(e){if(ne.call(e,"ref")){var r=Object.getOwnPropertyDescriptor(e,"ref").get;if(r&&r.isReactWarning)return!1}return e.ref!==void 0}function Kt(e){if(ne.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function Gt(e,r){typeof e.ref=="string"&&tt.current}function Ht(e,r){{var s=function(){rt||(rt=!0,j("%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)",r))};s.isReactWarning=!0,Object.defineProperty(e,"key",{get:s,configurable:!0})}}function Xt(e,r){{var s=function(){nt||(nt=!0,j("%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)",r))};s.isReactWarning=!0,Object.defineProperty(e,"ref",{get:s,configurable:!0})}}var Zt=function(e,r,s,l,m,x,h){var g={$$typeof:n,type:e,key:r,ref:s,props:h,_owner:x};return g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(g,"_self",{configurable:!1,enumerable:!1,writable:!1,value:l}),Object.defineProperty(g,"_source",{configurable:!1,enumerable:!1,writable:!1,value:m}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g};function Qt(e,r,s,l,m){{var x,h={},g=null,k=null;s!==void 0&&(et(s),g=""+s),Kt(r)&&(et(r.key),g=""+r.key),Jt(r)&&(k=r.ref,Gt(r,m));for(x in r)ne.call(r,x)&&!qt.hasOwnProperty(x)&&(h[x]=r[x]);if(e&&e.defaultProps){var T=e.defaultProps;for(x in T)h[x]===void 0&&(h[x]=T[x])}if(g||k){var _=typeof e=="function"?e.displayName||e.name||"Unknown":e;g&&Ht(h,_),k&&Xt(h,_)}return Zt(e,g,k,m,l,tt.current,h)}}var je=y.ReactCurrentOwner,ot=y.ReactDebugCurrentFrame;function K(e){if(e){var r=e._owner,s=de(e.type,e._source,r?r.type:null);ot.setExtraStackFrame(s)}else ot.setExtraStackFrame(null)}var Ce;Ce=!1;function Se(e){return typeof e=="object"&&e!==null&&e.$$typeof===n}function at(){{if(je.current){var e=W(je.current.type);if(e)return`
22
+
23
+ Check the render method of \``+e+"`."}return""}}function er(e){return""}var st={};function tr(e){{var r=at();if(!r){var s=typeof e=="string"?e:e.displayName||e.name;s&&(r=`
24
+
25
+ Check the top-level render call using <`+s+">.")}return r}}function it(e,r){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var s=tr(r);if(st[s])return;st[s]=!0;var l="";e&&e._owner&&e._owner!==je.current&&(l=" It was passed a child from "+W(e._owner.type)+"."),K(e),j('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',s,l),K(null)}}function lt(e,r){{if(typeof e!="object")return;if(Ee(e))for(var s=0;s<e.length;s++){var l=e[s];Se(l)&&it(l,r)}else if(Se(e))e._store&&(e._store.validated=!0);else if(e){var m=A(e);if(typeof m=="function"&&m!==e.entries)for(var x=m.call(e),h;!(h=x.next()).done;)Se(h.value)&&it(h.value,r)}}}function rr(e){{var r=e.type;if(r==null||typeof r=="string")return;var s;if(typeof r=="function")s=r.propTypes;else if(typeof r=="object"&&(r.$$typeof===d||r.$$typeof===b))s=r.propTypes;else return;if(s){var l=W(r);Bt(s,e.props,"prop",l,e)}else if(r.PropTypes!==void 0&&!Ce){Ce=!0;var m=W(r);j("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",m||"Unknown")}typeof r.getDefaultProps=="function"&&!r.getDefaultProps.isReactClassApproved&&j("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function nr(e){{for(var r=Object.keys(e.props),s=0;s<r.length;s++){var l=r[s];if(l!=="children"&&l!=="key"){K(e),j("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",l),K(null);break}}e.ref!==null&&(K(e),j("Invalid attribute `ref` supplied to `React.Fragment`."),K(null))}}var ut={};function ct(e,r,s,l,m,x){{var h=M(e);if(!h){var g="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(g+=" 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 k=er();k?g+=k:g+=at();var T;e===null?T="null":Ee(e)?T="array":e!==void 0&&e.$$typeof===n?(T="<"+(W(e.type)||"Unknown")+" />",g=" Did you accidentally export a JSX literal instead of a component?"):T=typeof e,j("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",T,g)}var _=Qt(e,r,s,m,x);if(_==null)return _;if(h){var L=r.children;if(L!==void 0)if(l)if(Ee(L)){for(var G=0;G<L.length;G++)lt(L[G],e);Object.freeze&&Object.freeze(L)}else j("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 lt(L,e)}if(ne.call(r,"key")){var U=W(e),R=Object.keys(r).filter(function(ur){return ur!=="key"}),Te=R.length>0?"{key: someKey, "+R.join(": ..., ")+": ...}":"{key: someKey}";if(!ut[U+Te]){var lr=R.length>0?"{"+R.join(": ..., ")+": ...}":"{}";j(`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} />`,Te,U,lr,U),ut[U+Te]=!0}}return e===a?nr(_):rr(_),_}}function or(e,r,s){return ct(e,r,s,!0)}function ar(e,r,s){return ct(e,r,s,!1)}var sr=ar,ir=or;X.Fragment=a,X.jsx=sr,X.jsxs=ir}()),X}var Oe;function vt(){return Oe||(Oe=1,process.env.NODE_ENV==="production"?oe.exports=dt():oe.exports=gt()),oe.exports}var i=vt();const ke=c.createContext(),ht=({children:t})=>{const[n,o]=c.useState(!1);return i.jsx(ke.Provider,{value:{isLoading:n,setIsLoading:o},children:t})},ve=()=>{const t=c.useContext(ke);if(t===void 0)throw new Error("Non puoi settare il loading");return t},Ae=c.createContext(),pt=({children:t})=>{const[n,o]=c.useState({}),a=async()=>{try{const f=await(await fetch("/config.json")).json();o(f)}catch(u){console.error(u)}};return c.useEffect(()=>{a()},[]),Object.keys(n).length===0?null:i.jsx(Ae.Provider,{value:n,children:t})},ae=()=>{const t=c.useContext(Ae);if(t===void 0)throw new Error("Non puoi leggere i config");return t},Ie=c.createContext(),mt=({children:t})=>{const[n,o]=c.useState(!1),[a,u]=c.useState(),[f,v]=c.useState(),p={showAlert:n,setShowAlert:o,typeAlert:a,setTypeAlert:u,messageAlert:f,setMessageAlert:v};return i.jsx(Ie.Provider,{value:p,children:t})},Y=()=>{const t=c.useContext(Ie);if(t===void 0)throw new Error("Non puoi modificare l'alert");return t};function he(t){this.message=t}he.prototype=new Error,he.prototype.name="InvalidCharacterError";var Re=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new he("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,a,u=0,f=0,v="";a=n.charAt(f++);~a&&(o=u%4?64*o+a:a,u++%4)?v+=String.fromCharCode(255&o>>(-2*u&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return v};function bt(t){var n=t.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(o){return decodeURIComponent(Re(o).replace(/(.)/g,function(a,u){var f=u.charCodeAt(0).toString(16).toUpperCase();return f.length<2&&(f="0"+f),"%"+f}))}(n)}catch{return Re(n)}}function se(t){this.message=t}function yt(t,n){if(typeof t!="string")throw new se("Invalid token specified");var o=(n=n||{}).header===!0?0:1;try{return JSON.parse(bt(t.split(".")[o]))}catch(a){throw new se("Invalid token specified: "+a.message)}}se.prototype=new Error,se.prototype.name="InvalidTokenError";let q;const Z=async(t,n,o)=>{if(q)return q;try{const u=await(await fetch("/config.json")).json(),f=u.baseUri,{unauthorized:v,notFound:p,defaultMessage:d}=u.axiosErrors;return q=ft.create({baseURL:f,timeout:3e3}),q.interceptors.request.use(w=>w),q.interceptors.response.use(w=>w,w=>{if(w.response)switch(t(!0),n("danger"),w.response.status){case 401:localStorage.removeItem("accessToken"),o(v);break;case 404:o(p);break;default:o(`${d} ${w.response.status} ${w.response.data.error}`)}return Promise.reject(w)}),q}catch(a){console.error(a)}},Ne=c.createContext(),xt=({children:t})=>{const{heartbeatEndpoint:n,infiniteSession:o,timeDeducted:a,authenticatedEndpoint:u}=ae(),{setIsLoading:f}=ve(),{setShowAlert:v,setMessageAlert:p,setTypeAlert:d}=Y(),w=V.useNavigate(),[E,b]=c.useState(null),[S,P]=c.useState(),[$,F]=c.useState(),[A,y]=c.useState(),j=async(O,I)=>{O.preventDefault();try{f(!0),v(!1);const M=await(await Z(v,d,p)).post(u,{auth:I}),ue=M.data.id,J=M.headers.token;J&&(localStorage.setItem("accessToken",J),localStorage.setItem("id",ue),b(!0),P(J),w(`/dashboard/${ue}`))}catch(z){console.error(z),f(!1)}},D=()=>{localStorage.removeItem("accessToken"),localStorage.removeItem("id"),b(!1),P(null)},N=async()=>{try{const O=localStorage.getItem("accessToken"),M=(await(await Z(v,d,p)).get(`${n}`,{headers:{Authorization:O}})).headers.token;localStorage.setItem("accessToken",M),P(M)}catch(O){console.error(O),D()}},ee=()=>{if(!S)return;const I=yt(S).exp,z=Math.floor(Date.now()/1e3),M=(I-z)*1e3;y(M),F(M-a)};c.useEffect(()=>{if(localStorage.getItem("accessToken"))b(!0);else{b(!1);return}},[]),c.useEffect(()=>{ee();let O;o&&S&&$&&(O=setInterval(()=>{N()},$));let I;return!o&&S&&A&&(I=setTimeout(()=>{D(),v(!0),d("danger"),p("Sessione scaduta")},A)),()=>{O&&clearInterval(O),I&&clearTimeout(I)}},[S,$]);const te={isAuthenticated:E,setIsAuthenticated:b,login:j,logout:D,setCurrentToken:P};return i.jsx(Ne.Provider,{value:te,children:t})},pe=()=>{const t=c.useContext(Ne);if(t===void 0)throw new Error("Non sei dentro al Auth Provider");return t},wt=()=>{const{isAuthenticated:t}=pe(),{setShowAlert:n,setTypeAlert:o,setMessageAlert:a}=Y(),u=localStorage.getItem("accessToken");return c.useEffect(()=>{!t&&!u&&(n(!0),o("danger"),a("Non sei autorizzato"))},[]),t===null?null:t?i.jsx(V.Outlet,{}):i.jsx(V.Navigate,{to:"/"})};var $e={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Le=c.createContext&&c.createContext($e),Et=["attr","size","title"];function jt(t,n){if(t==null)return{};var o=Ct(t,n),a,u;if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(t);for(u=0;u<f.length;u++)a=f[u],!(n.indexOf(a)>=0)&&Object.prototype.propertyIsEnumerable.call(t,a)&&(o[a]=t[a])}return o}function Ct(t,n){if(t==null)return{};var o={};for(var a in t)if(Object.prototype.hasOwnProperty.call(t,a)){if(n.indexOf(a)>=0)continue;o[a]=t[a]}return o}function ie(){return ie=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var o=arguments[n];for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(t[a]=o[a])}return t},ie.apply(this,arguments)}function De(t,n){var o=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);n&&(a=a.filter(function(u){return Object.getOwnPropertyDescriptor(t,u).enumerable})),o.push.apply(o,a)}return o}function le(t){for(var n=1;n<arguments.length;n++){var o=arguments[n]!=null?arguments[n]:{};n%2?De(Object(o),!0).forEach(function(a){St(t,a,o[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):De(Object(o)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(o,a))})}return t}function St(t,n,o){return n=Tt(n),n in t?Object.defineProperty(t,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[n]=o,t}function Tt(t){var n=_t(t,"string");return typeof n=="symbol"?n:n+""}function _t(t,n){if(typeof t!="object"||!t)return t;var o=t[Symbol.toPrimitive];if(o!==void 0){var a=o.call(t,n||"default");if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(t)}function Fe(t){return t&&t.map((n,o)=>c.createElement(n.tag,le({key:o},n.attr),Fe(n.child)))}function Q(t){return n=>c.createElement(Pt,ie({attr:le({},t.attr)},n),Fe(t.child))}function Pt(t){var n=o=>{var{attr:a,size:u,title:f}=t,v=jt(t,Et),p=u||o.size||"1em",d;return o.className&&(d=o.className),t.className&&(d=(d?d+" ":"")+t.className),c.createElement("svg",ie({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},o.attr,a,v,{className:d,style:le(le({color:t.color||o.color},o.style),t.style),height:p,width:p,xmlns:"http://www.w3.org/2000/svg"}),f&&c.createElement("title",null,f),t.children)};return Le!==void 0?c.createElement(Le.Consumer,null,o=>n(o)):n($e)}function Ot(t){return Q({tag:"svg",attr:{version:"1.1",viewBox:"0 0 16 16"},child:[{tag:"path",attr:{d:"M8 0c-4.355 0-7.898 3.481-7.998 7.812 0.092-3.779 2.966-6.812 6.498-6.812 3.59 0 6.5 3.134 6.5 7 0 0.828 0.672 1.5 1.5 1.5s1.5-0.672 1.5-1.5c0-4.418-3.582-8-8-8zM8 16c4.355 0 7.898-3.481 7.998-7.812-0.092 3.779-2.966 6.812-6.498 6.812-3.59 0-6.5-3.134-6.5-7 0-0.828-0.672-1.5-1.5-1.5s-1.5 0.672-1.5 1.5c0 4.418 3.582 8 8 8z"},child:[]}]})(t)}const Me=()=>i.jsxs("div",{className:"fixed top-0 bottom-0 left-0 right-0 flex items-center justify-center bg-[#00000080]",children:[i.jsx(Ot,{className:"text-[20rem] relative animate-spin text-white"}),i.jsx("p",{className:"text-white text-2xl select-none absolute",children:"Loading..."})]});function kt(t){return Q({tag:"svg",attr:{viewBox:"0 0 15 15",fill:"none"},child:[{tag:"path",attr:{fillRule:"evenodd",clipRule:"evenodd",d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:"currentColor"},child:[]}]})(t)}function At(t){return Q({tag:"svg",attr:{viewBox:"0 0 1024 1024"},child:[{tag:"path",attr:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 0 1 0-96 48.01 48.01 0 0 1 0 96z"},child:[]}]})(t)}function It(t){return Q({tag:"svg",attr:{viewBox:"0 0 1024 1024"},child:[{tag:"path",attr:{d:"M955.7 856l-416-720c-6.2-10.7-16.9-16-27.7-16s-21.6 5.3-27.7 16l-416 720C56 877.4 71.4 904 96 904h832c24.6 0 40-26.6 27.7-48zM480 416c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v184c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V416zm32 352a48.01 48.01 0 0 1 0-96 48.01 48.01 0 0 1 0 96z"},child:[]}]})(t)}function Rt(t){return Q({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M17.47 250.9C88.82 328.1 158 397.6 224.5 485.5c72.3-143.8 146.3-288.1 268.4-444.37L460 26.06C356.9 135.4 276.8 238.9 207.2 361.9c-48.4-43.6-126.62-105.3-174.38-137z"},child:[]}]})(t)}const ze=()=>{const{showAlert:t,setShowAlert:n,messageAlert:o,typeAlert:a}=Y(),{alertTimeout:u}=ae(),[f,v]=c.useState(0),p={danger:{bgColor:"bg-red-50",textColor:"text-red-700",buttonBg:"bg-red-50",hoverBg:"hover:bg-red-200",focusRing:"focus:ring-red-400",progressColor:"bg-red-400"},info:{bgColor:"bg-blue-50",textColor:"text-blue-700",buttonBg:"bg-blue-50",hoverBg:"hover:bg-blue-200",focusRing:"focus:ring-blue-400",progressColor:"bg-blue-400"},success:{bgColor:"bg-green-50",textColor:"text-green-700",buttonBg:"bg-green-50",hoverBg:"hover:bg-green-200",focusRing:"focus:ring-green-400",progressColor:"bg-green-400"}},{bgColor:d,textColor:w,buttonBg:E,hoverBg:b,focusRing:S,progressColor:P}=p[a],$=A=>{switch(A){case"danger":return i.jsx(It,{className:"text-xl"});case"info":return i.jsx(At,{className:"text-xl"});case"success":return i.jsx(Rt,{className:"text-xl"})}},F=()=>{n(!t)};return c.useEffect(()=>{let A;const j=100/(u/100);A=setInterval(()=>{v(N=>N>=100?(clearInterval(A),100):N+j)},100);const D=setTimeout(()=>{F()},u);return()=>{clearTimeout(D),clearInterval(A)}},[]),i.jsxs("div",{className:`flex items-center p-4 pt-6 ${w} rounded-lg ${d} mx-auto fixed top-[calc(100vh-100px)] right-10`,role:"alert",children:[i.jsx("div",{className:"w-full bg-gray-200 rounded-t-lg overflow-hidden h-2.5 dark:bg-gray-700 absolute top-0 left-0 right-0",children:i.jsx("div",{className:`${P} h-2.5 rounded-t-lg`,style:{width:`${f}%`}})}),$(a),i.jsx("div",{className:"px-4 text-sm font-medium",children:o}),i.jsx("button",{type:"button",className:`ms-auto ${E} rounded-lg focus:ring-2 ${S} p-1.5 ${b} inline-flex items-center justify-center h-8 w-8`,title:"Close",onClick:F,children:i.jsx(kt,{className:"text-xl"})})]})},Nt=()=>{const{isLoading:t}=ve(),{showAlert:n}=Y();return i.jsxs(i.Fragment,{children:[t&&i.jsx(Me,{}),i.jsxs("main",{className:t?"hidden":"",children:[n&&i.jsx(ze,{}),i.jsx(V.Outlet,{})]})]})},me=t=>{const{inputType:n,inputId:o,inputPlaceholder:a,inputRequired:u,inputValue:f,inputChange:v}=t,d=["text","email","password","search","tel","url"].includes(n)?n:"text";return i.jsx("input",{type:d,id:o,className:"bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5",placeholder:a,required:u??!0,value:f,onChange:v})},be=({label:t,labelId:n,labelStyle:o})=>i.jsx("label",{htmlFor:n,className:`${o??"block mb-2 text-sm font-medium text-gray-900"}`,children:t}),We=t=>{const{submitForm:n,formData:o,changeValue:a,formSize:u="w-[800px]",formBgColor:f="bg-slate-50",formRounded:v="rounded-lg",formShadow:p="shadow-lg",userData:d,userLabel:w="Email",userType:E="email",userPlaceholder:b="email@email.it",formTitle:S="Login",titleSize:P="text-4xl",titlePosition:$="text-center",titleSpacing:F="my-12",buttonPosition:A="justify-center",buttonSpacing:y="my-12",buttonColor:j="bg-blue-500",buttonHoverColor:D="hoverbg-blue-700",buttonTextColor:N="text-white",buttonSize:ee="py-2 px-4",buttonRounded:te="rounded-full",buttonText:O="Login"}=t;return i.jsxs("form",{onSubmit:n,className:`${u} ${v} ${p} ${f}`,children:[i.jsx("h1",{className:`${P} ${$} ${F}`,children:S}),i.jsxs("div",{className:"flex justify-center flex-col gap-1 my-4 w-1/2 mx-auto",children:[i.jsx(be,{labelId:"user-email",label:w}),i.jsx(me,{inputType:E,inputId:"user-email",inputPlaceholder:b,inputValue:d?o[d]:o.email,inputChange:I=>{a(d||"email",I.target.value)}})]}),i.jsxs("div",{className:"flex justify-center flex-col gap-1 my-4 w-1/2 mx-auto",children:[i.jsx(be,{labelId:"password",label:"Password"}),i.jsx(me,{inputType:"password",inputId:"password",inputPlaceholder:"Password",inputValue:o.password,inputChange:I=>{a("password",I.target.value)}})]}),i.jsx("div",{className:`flex ${A} items-center ${y}`,children:i.jsx("button",{className:`${j} ${D} ${N} font-bold ${ee} ${te}`,children:O})})]})},$t=()=>{const{login:t}=pe(),{setShowAlert:n,setTypeAlert:o,setMessageAlert:a}=Y(),{clearLoginFormOnError:u}=ae(),f=V.useNavigate(),v={email:"",password:""},[p,d]=c.useState(v),w=(b,S)=>{d(P=>({...P,[b]:S}))},E=b=>{t(b,p),u&&d(v)};return c.useEffect(()=>{const b=localStorage.getItem("id");localStorage.getItem("accessToken")&&b&&(f(`/dashboard/${b}`),n(!0),o("info"),a("Sei già loggato"))},[]),i.jsx("section",{children:i.jsx("div",{className:"container mx-auto flex items-center justify-center h-screen",children:i.jsx(We,{submitForm:E,formData:p,changeValue:w})})})},Lt=()=>{const{id:t}=V.useParams(),{logout:n,setCurrentToken:o}=pe(),{usersEndpoint:a}=ae(),{setIsLoading:u}=ve(),{setShowAlert:f,setTypeAlert:v,setMessageAlert:p}=Y(),[d,w]=c.useState({}),[E,b]=c.useState(null),[S,P]=c.useState(!1),$=async()=>{try{u(!0);const y=localStorage.getItem("accessToken");if(!y){n(),f(!0),v("danger"),p("Sessione scaduta");return}o(y);const N=(await(await Z(f,v,p)).get(`${a}${t}`,{headers:{Authorization:y}})).data;w(N),u(!1)}catch(y){console.error(y),u(!1),n()}},F=async()=>{try{P(!0);const y=localStorage.getItem("accessToken");if(!y){n(),f(!0),v("danger"),p("Sessione scaduta");return}const N=(await(await Z(f,v,p)).get(`${a}`,{headers:{Authorization:y}})).data;b(N),N&&P(!1)}catch(y){console.error(y),u(!1),y.status===401&&n(),P(!1)}},A=()=>{n(),f(!0),v("info"),p("Hai effettuato il logout")};return c.useEffect(()=>{$()},[]),i.jsx("section",{children:i.jsxs("div",{className:"container mx-auto py-8",children:[i.jsxs("div",{className:"flex items-center justify-center gap-8 h-20",children:[i.jsxs("h1",{className:"text-4xl text-center text-slate-800",children:["Email: ",d.email]}),i.jsx("button",{onClick:A,className:"bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-full",children:"Logout"})]}),i.jsx("div",{className:"flex justify-center items-center my-12",children:i.jsx("button",{onClick:F,className:"bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full disabled:bg-blue-300 disabled:text-gray-500 disabled:cursor-not-allowed",disabled:S,children:"Lista degli utenti"})}),i.jsx("div",{className:"flex justify-center items-center",children:E&&i.jsx("ul",{children:E.map(y=>i.jsxs("li",{className:"text-xl my-4",children:[y.id," - ",y.email]},`user-${y.id}`))})})]})})};C.Alert=ze,C.AlertProvider=mt,C.AuthPage=wt,C.AuthProvider=xt,C.ConfigProvider=pt,C.Dashboard=Lt,C.DefaultLayout=Nt,C.Input=me,C.InputLabel=be,C.Loading=Me,C.LoadingProvider=ht,C.Login=$t,C.LoginForm=We,C.fetchAxiosConfig=Z,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "thecore-auth",
3
+ "private": false,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "main": "dist/thecore-auth.csj.js",
7
+ "module": "dist/thecore-auth.esm.js",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/thecore-auth.esm.js",
11
+ "require": "./dist/thecore-auth.cjs.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "dev": "vite --host",
16
+ "build": "vite build",
17
+ "lint": "eslint .",
18
+ "preview": "vite preview"
19
+ },
20
+ "dependencies": {
21
+ "axios": "^1.7.9",
22
+ "jwt-decode": "^3.1.2",
23
+ "react": "^18.3.1",
24
+ "react-dom": "^18.3.1",
25
+ "react-icons": "^5.4.0",
26
+ "react-router-dom": "^7.1.3"
27
+ },
28
+ "devDependencies": {
29
+ "@eslint/js": "^9.17.0",
30
+ "@types/react": "^18.3.18",
31
+ "@types/react-dom": "^18.3.5",
32
+ "@vitejs/plugin-react": "^4.3.4",
33
+ "autoprefixer": "^10.4.20",
34
+ "eslint": "^9.17.0",
35
+ "eslint-plugin-react": "^7.37.2",
36
+ "eslint-plugin-react-hooks": "^5.0.0",
37
+ "eslint-plugin-react-refresh": "^0.4.16",
38
+ "globals": "^15.14.0",
39
+ "postcss": "^8.5.1",
40
+ "tailwindcss": "^3.4.17",
41
+ "vite": "^6.0.5"
42
+ },
43
+ "peerDependencies": {
44
+ "react": "^18.0.0",
45
+ "react-dom": "^18.0.0"
46
+ },
47
+ "files": [
48
+ "dist",
49
+ "README.md"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "https://github.com/SantiGalvan/thecore-auth"
54
+ },
55
+ "keywords": [
56
+ "react",
57
+ "authentication",
58
+ "jwt",
59
+ "react-router"
60
+ ],
61
+ "author": "Santiago Galvan<santiagogalvancolorado@gmail.com>",
62
+ "license": "MIT",
63
+ "description": "Un pacchetto per l'autenticazione in React utilizzando JWT nell'accezione implementata in thecore e React Router"
64
+ }