analytica-frontend-lib
Version:
Repositório público dos componentes utilizados nas plataformas da Analytica Ensino
215 lines (211 loc) • 6.77 kB
JavaScript
import {
buildLoginUrlWithReturnTo,
resolveRootHostname
} from "./chunk-RLGKQUBF.mjs";
// src/components/Auth/Auth.tsx
import {
createContext,
useContext,
useEffect,
useState,
useCallback,
useMemo as useMemo2
} from "react";
import { useLocation as useLocation2, Navigate } from "react-router-dom";
// src/components/Auth/useTokenInUrl.ts
import { useMemo } from "react";
import { useLocation } from "react-router-dom";
function useTokenInUrl() {
const location = useLocation();
const hasTokenInUrl = useMemo(() => {
const searchParams = new URLSearchParams(location.search);
const token = searchParams.get("token");
const refreshToken = searchParams.get("refreshToken");
const sessionId = searchParams.get("sessionId");
return !!(token && refreshToken && sessionId);
}, [location.search]);
return { hasTokenInUrl };
}
// src/components/Auth/Auth.tsx
import { Fragment, jsx } from "react/jsx-runtime";
var AuthContext = createContext(void 0);
var AuthProvider = ({
children,
checkAuthFn,
signOutFn,
initialAuthState = {},
getUserFn,
getSessionFn,
getTokensFn
}) => {
const [authState, setAuthState] = useState({
isAuthenticated: false,
isLoading: true,
...initialAuthState
});
const checkAuth = 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 = useCallback(() => {
if (signOutFn) {
signOutFn();
}
setAuthState((prev) => ({
...prev,
isAuthenticated: false,
user: void 0,
sessionInfo: void 0,
tokens: void 0
}));
}, [signOutFn]);
useEffect(() => {
checkAuth();
}, [checkAuth]);
const contextValue = useMemo2(
() => ({
...authState,
checkAuth,
signOut
}),
[authState, checkAuth, signOut]
);
return /* @__PURE__ */ jsx(AuthContext.Provider, { value: contextValue, children });
};
var useAuth = () => {
const context = 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,
tokenValidationComponent
}) => {
const { isAuthenticated, isLoading, ...authState } = useAuth();
const { hasTokenInUrl } = useTokenInUrl();
const defaultLoadingComponent = /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ jsx("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
if (isLoading) {
return /* @__PURE__ */ jsx(Fragment, { children: loadingComponent || defaultLoadingComponent });
}
if (!isAuthenticated && hasTokenInUrl) {
return /* @__PURE__ */ jsx(Fragment, { children: tokenValidationComponent || 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 = buildLoginUrlWithReturnTo(rootDomain);
return null;
}
}
return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
}
if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
}
return /* @__PURE__ */ jsx(Fragment, { children });
};
var PublicRoute = ({
children,
redirectTo = "/painel",
redirectIfAuthenticated = false,
checkAuthBeforeRender = false,
tokenValidationComponent
}) => {
const { isAuthenticated, isLoading } = useAuth();
const { hasTokenInUrl } = useTokenInUrl();
if (hasTokenInUrl && tokenValidationComponent) {
return /* @__PURE__ */ jsx(Fragment, { children: tokenValidationComponent });
}
if (checkAuthBeforeRender && isLoading) {
return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ jsx("div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
}
if (isAuthenticated && redirectIfAuthenticated) {
return /* @__PURE__ */ jsx(Navigate, { to: redirectTo, replace: true });
}
return /* @__PURE__ */ jsx(Fragment, { children });
};
var withAuth = (Component, options = {}) => {
return (props) => /* @__PURE__ */ jsx(ProtectedRoute, { ...options, children: /* @__PURE__ */ 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 = useLocation2();
const redirectToLogin = () => /* @__PURE__ */ jsx(Navigate, { to: fallbackPath, state: { from: location }, replace: true });
return {
isAuthenticated,
isLoading,
redirectToLogin
};
};
var getRootDomain = () => {
const { hostname, protocol, port } = window.location;
const portStr = port ? ":" + port : "";
const root = resolveRootHostname(hostname) ?? hostname;
return `${protocol}//${root}${portStr}`;
};
var Auth_default = {
AuthProvider,
ProtectedRoute,
PublicRoute,
withAuth,
useAuth,
useAuthGuard,
useRouteAuth
};
export {
useTokenInUrl,
AuthProvider,
useAuth,
ProtectedRoute,
PublicRoute,
withAuth,
useAuthGuard,
useRouteAuth,
getRootDomain,
Auth_default
};
//# sourceMappingURL=chunk-VQTRDBGR.mjs.map