analytica-frontend-lib
Version:
Repositório público dos componentes utilizados nas plataformas da Analytica Ensino
215 lines (189 loc) • 7.75 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
var _chunkZE5JXJ4Yjs = require('./chunk-ZE5JXJ4Y.js');
// src/components/Auth/Auth.tsx
var _react = require('react');
var _reactrouterdom = require('react-router-dom');
// src/components/Auth/useTokenInUrl.ts
function useTokenInUrl() {
const location = _reactrouterdom.useLocation.call(void 0, );
const hasTokenInUrl = _react.useMemo.call(void 0, () => {
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
var _jsxruntime = require('react/jsx-runtime');
var AuthContext = _react.createContext.call(void 0, void 0);
var AuthProvider = ({
children,
checkAuthFn,
signOutFn,
initialAuthState = {},
getUserFn,
getSessionFn,
getTokensFn
}) => {
const [authState, setAuthState] = _react.useState.call(void 0, {
isAuthenticated: false,
isLoading: true,
...initialAuthState
});
const checkAuth = _react.useCallback.call(void 0, 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 = _react.useCallback.call(void 0, () => {
if (signOutFn) {
signOutFn();
}
setAuthState((prev) => ({
...prev,
isAuthenticated: false,
user: void 0,
sessionInfo: void 0,
tokens: void 0
}));
}, [signOutFn]);
_react.useEffect.call(void 0, () => {
checkAuth();
}, [checkAuth]);
const contextValue = _react.useMemo.call(void 0,
() => ({
...authState,
checkAuth,
signOut
}),
[authState, checkAuth, signOut]
);
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AuthContext.Provider, { value: contextValue, children });
};
var useAuth = () => {
const context = _react.useContext.call(void 0, 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__ */ _jsxruntime.jsx.call(void 0, "div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
if (isLoading) {
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children: loadingComponent || defaultLoadingComponent });
}
if (!isAuthenticated && hasTokenInUrl) {
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.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 = _chunkZE5JXJ4Yjs.buildLoginUrlWithReturnTo.call(void 0, rootDomain);
return null;
}
}
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate, { to: redirectTo, replace: true });
}
if (additionalCheck && !additionalCheck({ isAuthenticated, isLoading, ...authState })) {
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate, { to: redirectTo, replace: true });
}
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children });
};
var PublicRoute = ({
children,
redirectTo = "/painel",
redirectIfAuthenticated = false,
checkAuthBeforeRender = false,
tokenValidationComponent
}) => {
const { isAuthenticated, isLoading } = useAuth();
const { hasTokenInUrl } = useTokenInUrl();
if (hasTokenInUrl && tokenValidationComponent) {
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children: tokenValidationComponent });
}
if (checkAuthBeforeRender && isLoading) {
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "flex items-center justify-center min-h-screen", children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { className: "text-text-950 text-lg", children: "Carregando..." }) });
}
if (isAuthenticated && redirectIfAuthenticated) {
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate, { to: redirectTo, replace: true });
}
return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children });
};
var withAuth = (Component, options = {}) => {
return (props) => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, ProtectedRoute, { ...options, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 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 = _reactrouterdom.useLocation.call(void 0, );
const redirectToLogin = () => /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactrouterdom.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 = _nullishCoalesce(_chunkZE5JXJ4Yjs.resolveRootHostname.call(void 0, hostname), () => ( hostname));
return `${protocol}//${root}${portStr}`;
};
var Auth_default = {
AuthProvider,
ProtectedRoute,
PublicRoute,
withAuth,
useAuth,
useAuthGuard,
useRouteAuth
};
exports.useTokenInUrl = useTokenInUrl; exports.AuthProvider = AuthProvider; exports.useAuth = useAuth; exports.ProtectedRoute = ProtectedRoute; exports.PublicRoute = PublicRoute; exports.withAuth = withAuth; exports.useAuthGuard = useAuthGuard; exports.useRouteAuth = useRouteAuth; exports.getRootDomain = getRootDomain; exports.Auth_default = Auth_default;
//# sourceMappingURL=chunk-VDLACBCF.js.map