Skip to content

Commit

Permalink
Reloading issue and tenant filter and cohort filter issue fix
Browse files Browse the repository at this point in the history
  • Loading branch information
chaitanyakole committed Feb 19, 2025
1 parent bfe61e0 commit 1311ea5
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 68 deletions.
2 changes: 1 addition & 1 deletion next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const nextConfig = {
ignoreDuringBuilds: true,
},
trailingSlash: false,
reactStrictMode: true,
reactStrictMode: false,
i18n: nextI18nextConfig.i18n,
// async rewrites() {
// return [
Expand Down
68 changes: 56 additions & 12 deletions src/components/ProtectedRoute.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,75 @@
import { useRouter } from "next/router";
import { useEffect } from "react";
import { useEffect, useRef, useState } from "react";
import { useAuth } from "../context/AuthContext";
import { useTranslation } from "next-i18next";

const ProtectedRoute = ({ children }) => {
const { t } = useTranslation();
let user;
const router = useRouter();
const { loading } = useAuth();
const authCheckAttempts = useRef(0);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const maxAttempts = 5;
const checkInterval = 300;

useEffect(() => {
let user;
if (typeof window !== "undefined" && window.localStorage) {
user = localStorage.getItem("token");
if (
router.pathname === "/login" ||
router.pathname === "/super-admin-login"
) {
setIsAuthenticated(true);
return;
}
//Need to updated
setTimeout(() => {
if (!loading && !user) {

if (isAuthenticated) {
return;
}
if (loading) {
return;
}

const checkAuthentication = () => {
const token = localStorage.getItem("token");
const isSuperAdmin =
localStorage.getItem("superAdminLoggedIn") === "true";
const userId = localStorage.getItem("userId");

authCheckAttempts.current += 1;

if (token || isSuperAdmin || userId) {
setIsAuthenticated(true);
return true;
}

if (authCheckAttempts.current >= maxAttempts) {
router.push("/login");
return true;
}
}, 1000);
}, [loading, router]);

if (loading) {
return false;
};

if (checkAuthentication()) {
return;
}

const intervalId = setInterval(() => {
if (checkAuthentication()) {
clearInterval(intervalId);
}
}, checkInterval);

return () => clearInterval(intervalId);
}, [loading, router.pathname, router, isAuthenticated]);

if (
loading ||
(!isAuthenticated &&
router.pathname !== "/login" &&
router.pathname !== "/super-admin-login")
) {
return <p>{t("COMMON.LOADING")}</p>;
}

return children;
};

Expand Down
30 changes: 18 additions & 12 deletions src/components/UserTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -684,18 +684,19 @@ const UserTable: React.FC<UserTableProps> = ({
const tenantId = selectedCodes.join(",");
setSelectedTenant(selectedNames);

if (selectedNames?.[0] === "All") {
setFilters((prevFilter) => {
const newFilters = { ...prevFilter };
setSelectedCohort([]);
setFilters((prevFilter) => {
const newFilters = { ...prevFilter };

if (selectedNames?.[0] === "All") {
delete newFilters.tenantId;
return newFilters;
});
} else {
setFilters((prevFilter) => ({
...prevFilter,
tenantId: tenantId,
}));
}
} else {
newFilters.tenantId = tenantId;
}
delete newFilters.cohortId;

return newFilters;
});
} else {
console.log("No valid tenants selected");
}
Expand Down Expand Up @@ -847,10 +848,15 @@ const UserTable: React.FC<UserTableProps> = ({
setSelectedCohort(selectedNames);
setFilters((prevFilter) => ({
...prevFilter,
cohortId: cohortId,
cohortId: selectedNames?.[0] === "All" ? undefined : cohortId,
}));
} else {
console.log("No valid cohort selected");
setFilters((prevFilter) => {
const newFilters = { ...prevFilter };
delete newFilters.cohortId;
return newFilters;
});
}
};

Expand Down
62 changes: 35 additions & 27 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,35 +21,44 @@ import { useRouter } from "next/router";

function App({ Component, pageProps }: AppProps) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const hasFetchedUserDetails = useRef(false);
const authInitialized = useRef(false);
const userDetailsFetched = useRef(false);
const router = useRouter();

// Analytics initialization
useEffect(() => {
telemetryFactory.init();
// Analytics initialization would go here too if needed
// if (!window.GA_INITIALIZED) {
// initGA(`G-6NVMB20J4Z`);
// window.GA_INITIALIZED = true;
// }
}, []);

// useEffect(() => {
// if (!window.GA_INITIALIZED) {
// initGA(`G-6NVMB20J4Z`);
// window.GA_INITIALIZED = true;
// }
// }, []);

// Keycloak initialization
useEffect(() => {
const initializeKeycloak = async () => {
try {
if (router.pathname === "/super-admin-login")
return localStorage.setItem("superAdminLoggedIn", "true");
const superAdminLoggedIn =
localStorage.getItem("superAdminLoggedIn") === "true";
if (superAdminLoggedIn) {
setIsAuthenticated(false);
return;
}
if (!keycloak || keycloak.authenticated) return;
if (authInitialized.current) return;

const handleAuth = async () => {
authInitialized.current = true;
if (router.pathname === "/super-admin-login") {
localStorage.setItem("superAdminLoggedIn", "true");
return;
}
const superAdminLoggedIn =
localStorage.getItem("superAdminLoggedIn") === "true";
if (superAdminLoggedIn) {
setIsAuthenticated(false);
return;
}

if (!keycloak) {
console.log("Keycloak instance not available");
return;
}

if (keycloak.authenticated) {
setIsAuthenticated(true);
return;
}
try {
const redirectUri = `${window.location.origin}/tenant`;
const authenticated = await keycloak.init({
onLoad: "login-required",
Expand All @@ -71,14 +80,15 @@ function App({ Component, pageProps }: AppProps) {
}
};

initializeKeycloak();
}, [router.pathname, keycloak]);
handleAuth();
}, [router.isReady]);

useEffect(() => {
if (!isAuthenticated || hasFetchedUserDetails.current) return;
if (!isAuthenticated || userDetailsFetched.current) return;

const fetchUserDetails = async () => {
try {
userDetailsFetched.current = true;
const userResponse = await getUserId();
if (!userResponse) return;
localStorage.setItem("userId", userResponse.userId || "");
Expand All @@ -91,8 +101,6 @@ function App({ Component, pageProps }: AppProps) {
const response = await getUserDetailsInfo(userResponse.userId, true);
localStorage.setItem("adminInfo", JSON.stringify(response?.userData));
}

hasFetchedUserDetails.current = true;
} catch (error) {
console.error("Error fetching user details:", error);
}
Expand Down
15 changes: 12 additions & 3 deletions src/pages/login.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Box } from "@mui/material";
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import Loader from "../components/Loader";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useRouter } from "next/router";
Expand All @@ -8,19 +8,28 @@ import { useTranslation } from "next-i18next";
const LoginPage = () => {
const { t } = useTranslation();
const router = useRouter();
const [isRedirecting, setIsRedirecting] = useState(false);

useEffect(() => {
if (typeof window !== "undefined" && window.localStorage) {
const token = localStorage.getItem("token");
if (token) {
setIsRedirecting(true);
router.push("/tenant");
}
}
}, []);

return (
<Box sx={{ backgroundColor: "white", height: "100vh" }}>
<Loader showBackdrop={true} loadingText={t("COMMON.LOADING")} />
<Box
display="flex"
justifyContent="center"
alignItems="center"
height="100vh"
>
{isRedirecting && (
<Loader showBackdrop={false} loadingText={t("COMMON.LOADING")} />
)}
</Box>
);
};
Expand Down
13 changes: 6 additions & 7 deletions src/pages/tenant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ const Tenant: React.FC = () => {
const [confirmButtonDisable, setConfirmButtonDisable] =
React.useState<boolean>(false);
const [inputName, setInputName] = React.useState<string>("");
const [loading, setLoading] = useState<boolean | undefined>(undefined);
const [loading, setLoading] = useState<boolean>(true);
const [dataFetched, setDataFetched] = useState<boolean>(false);
const [userId, setUserId] = useState("");
const [schema] = React.useState(tenantSchema);
const [cohortSchema] = React.useState(cohortSchemajson);
Expand Down Expand Up @@ -330,23 +331,21 @@ const Tenant: React.FC = () => {
setCohortData([]);
}

setDataFetched(true);
setLoading(false);
} catch (error) {
setCohortData([]);
setDataFetched(true);
setLoading(false);
console.error("Error fetching tenant list:", error);
}
};

useEffect(() => {
const timeoutId = setTimeout(() => {
// Your function logic here

fetchTenantList();
}, 1000);
// get form data for center create
// getAddCenterFormData();
// getCohortMemberlistData();

return () => {
clearTimeout(timeoutId);
};
Expand Down Expand Up @@ -1132,7 +1131,7 @@ const Tenant: React.FC = () => {
>
<Loader showBackdrop={false} loadingText={t("COMMON.LOADING")} />
</Box>
) : cohortData?.length > 0 ? (
) : dataFetched && cohortData?.length > 0 ? (
<Box
sx={{
backgroundColor: "white",
Expand Down
13 changes: 7 additions & 6 deletions src/utils/keycloak.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Keycloak from "keycloak-js";


const keycloakInstance =
typeof window !== "undefined"
? new Keycloak({
Expand All @@ -10,17 +9,19 @@ const keycloakInstance =
})
: null;
export const logout = async () => {
try {
if (keycloakInstance) {
try {
if (keycloakInstance) {
await keycloakInstance.logout({
redirectUri: window.location.origin + "/login",
});
localStorage.clear();
sessionStorage.clear();
document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });

document.cookie.split(";").forEach(function (c) {
document.cookie = c
.replace(/^ +/, "")
.replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
}

} catch (error) {
console.error("Logout failed:", error);
}
Expand Down

0 comments on commit 1311ea5

Please sign in to comment.