UNPKG

analytica-frontend-lib

Version:

Repositório público dos componentes utilizados nas plataformas da Analytica Ensino

225 lines (224 loc) 8.04 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/components/Auth/Auth.tsx var Auth_exports = {}; __export(Auth_exports, { AuthProvider: () => AuthProvider, ProtectedRoute: () => ProtectedRoute, PublicRoute: () => PublicRoute, default: () => Auth_default, getRootDomain: () => getRootDomain, useAuth: () => useAuth, useAuthGuard: () => useAuthGuard, useRouteAuth: () => useRouteAuth, withAuth: () => withAuth }); module.exports = __toCommonJS(Auth_exports); var import_react = require("react"); var import_react_router_dom = require("react-router-dom"); var import_jsx_runtime = require("react/jsx-runtime"); var AuthContext = (0, import_react.createContext)(void 0); var AuthProvider = ({ children, checkAuthFn, signOutFn, initialAuthState = {}, getUserFn, getSessionFn, getTokensFn }) => { const [authState, setAuthState] = (0, import_react.useState)({ isAuthenticated: false, isLoading: true, ...initialAuthState }); const checkAuth = (0, import_react.useCallback)(async () => { try { setAuthState((prev) => ({ ...prev, isLoading: true })); if (!checkAuthFn) { setAuthState((prev) => ({ ...prev, isAuthenticated: false, isLoading: false })); return false; } const isAuth = await checkAuthFn(); setAuthState((prev) => ({ ...prev, isAuthenticated: isAuth, isLoading: false, user: getUserFn ? getUserFn() : prev.user, sessionInfo: getSessionFn ? getSessionFn() : prev.sessionInfo, tokens: getTokensFn ? getTokensFn() : prev.tokens })); return isAuth; } catch (error) { console.error("Erro ao verificar autentica\xE7\xE3o:", error); setAuthState((prev) => ({ ...prev, isAuthenticated: false, isLoading: false })); return false; } }, [checkAuthFn, getUserFn, getSessionFn, getTokensFn]); const signOut = (0, import_react.useCallback)(() => { if (signOutFn) { signOutFn(); } setAuthState((prev) => ({ ...prev, isAuthenticated: false, user: void 0, sessionInfo: void 0, tokens: void 0 })); }, [signOutFn]); (0, import_react.useEffect)(() => { checkAuth(); }, [checkAuth]); const contextValue = (0, import_react.useMemo)( () => ({ ...authState, checkAuth, signOut }), [authState, checkAuth, signOut] ); return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthContext.Provider, { value: contextValue, children }); }; var useAuth = () => { const context = (0, import_react.useContext)(AuthContext); if (context === void 0) { throw new Error("useAuth deve ser usado dentro de um AuthProvider"); } return context; }; var ProtectedRoute = ({ children, redirectTo = "/", loadingComponent, additionalCheck }) => { const { isAuthenticated, isLoading, ...authState } = useAuth(); const defaultLoadingComponent = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "text-text-950 text-lg", children: "Carregando..." }) }); if (isLoading) { return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: loadingComponent || defaultLoadingComponent }); } if (!isAuthenticated) { if (typeof window !== "undefined") { const rootDomain = getRootDomain(); const currentLocation = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ":" + window.location.port : ""}`; if (rootDomain !== currentLocation) { window.location.href = rootDomain; return null; } } return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom.Navigate, { to: redirectTo, replace: true }); } if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) { return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom.Navigate, { to: redirectTo, replace: true }); } return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children }); }; var PublicRoute = ({ children, redirectTo = "/painel", redirectIfAuthenticated = false, checkAuthBeforeRender = false }) => { const { isAuthenticated, isLoading } = useAuth(); if (checkAuthBeforeRender && isLoading) { return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "text-text-950 text-lg", children: "Carregando..." }) }); } if (isAuthenticated && redirectIfAuthenticated) { return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom.Navigate, { to: redirectTo, replace: true }); } return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children }); }; var withAuth = (Component, options = {}) => { return (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ProtectedRoute, { ...options, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, { ...props }) }); }; var useAuthGuard = (options = {}) => { const authState = useAuth(); const { requireAuth = true, customCheck } = options; const canAccess = !authState.isLoading && (requireAuth ? authState.isAuthenticated && (!customCheck || customCheck(authState)) : !authState.isAuthenticated || !customCheck || customCheck(authState)); return { canAccess, isLoading: authState.isLoading, authState }; }; var useRouteAuth = (fallbackPath = "/") => { const { isAuthenticated, isLoading } = useAuth(); const location = (0, import_react_router_dom.useLocation)(); const redirectToLogin = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_router_dom.Navigate, { to: fallbackPath, state: { from: location }, replace: true }); return { isAuthenticated, isLoading, redirectToLogin }; }; var getRootDomain = () => { const { hostname, protocol, port } = window.location; const portStr = port ? ":" + port : ""; if (hostname === "localhost") { return `${protocol}//${hostname}${portStr}`; } const isIPv4 = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname); const isIPv6 = hostname.includes(":"); if (isIPv4 || isIPv6) { return `${protocol}//${hostname}${portStr}`; } const parts = hostname.split("."); if (parts.length >= 3 && parts[parts.length - 2] === "com" && parts[parts.length - 1] === "br") { if (parts.length === 3) { return `${protocol}//${hostname}${portStr}`; } const base = parts.slice(-3).join("."); return `${protocol}//${base}${portStr}`; } if (parts.length > 2) { const base = parts.slice(-2).join("."); return `${protocol}//${base}${portStr}`; } return `${protocol}//${hostname}${portStr}`; }; var Auth_default = { AuthProvider, ProtectedRoute, PublicRoute, withAuth, useAuth, useAuthGuard, useRouteAuth }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { AuthProvider, ProtectedRoute, PublicRoute, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth }); //# sourceMappingURL=index.js.map