el.xwx.moe/layouts/AuthRedirect.tsx

75 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-04-30 15:54:40 -05:00
import { ReactNode } from "react";
2023-02-08 17:58:55 -06:00
import { useSession } from "next-auth/react";
2023-04-30 15:54:40 -05:00
import Loader from "../components/Loader";
2023-02-08 17:58:55 -06:00
import { useRouter } from "next/router";
2023-04-30 15:54:40 -05:00
import { useEffect, useState } from "react";
import useInitialData from "@/hooks/useInitialData";
2023-02-08 17:58:55 -06:00
2023-04-30 15:54:40 -05:00
interface Props {
children: ReactNode;
}
export default function AuthRedirect({ children }: Props) {
2023-02-08 17:58:55 -06:00
const router = useRouter();
const { status, data } = useSession();
2023-02-08 17:58:55 -06:00
const [redirect, setRedirect] = useState(true);
2023-07-19 15:39:59 -05:00
const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER;
useInitialData();
2023-04-30 15:54:40 -05:00
2023-02-08 17:58:55 -06:00
useEffect(() => {
2023-05-28 00:55:49 -05:00
if (!router.pathname.startsWith("/public")) {
2023-07-19 15:39:59 -05:00
if (
emailEnabled &&
status === "authenticated" &&
(data.user.isSubscriber === true ||
data.user.isSubscriber === undefined) &&
!data.user.username
) {
router.push("/choose-username").then(() => {
setRedirect(false);
});
} else if (
status === "authenticated" &&
data.user.isSubscriber === false
) {
router.push("/subscribe").then(() => {
setRedirect(false);
});
} else if (
2023-05-28 00:55:49 -05:00
status === "authenticated" &&
2023-07-12 15:34:05 -05:00
(router.pathname === "/login" ||
router.pathname === "/register" ||
router.pathname === "/confirmation" ||
router.pathname === "/subscribe" ||
2023-07-19 15:39:59 -05:00
router.pathname === "/choose-username" ||
2023-07-12 15:34:05 -05:00
router.pathname === "/forgot")
2023-05-28 00:55:49 -05:00
) {
router.push("/").then(() => {
setRedirect(false);
});
} else if (
status === "unauthenticated" &&
2023-07-12 15:34:05 -05:00
!(
router.pathname === "/login" ||
router.pathname === "/register" ||
router.pathname === "/confirmation" ||
router.pathname === "/forgot"
)
2023-05-28 00:55:49 -05:00
) {
router.push("/login").then(() => {
setRedirect(false);
});
} else if (status === "loading") setRedirect(true);
else setRedirect(false);
} else {
setRedirect(false);
}
2023-02-08 17:58:55 -06:00
}, [status]);
2023-07-12 13:26:34 -05:00
if (status !== "loading" && !redirect) return <>{children}</>;
else return <></>;
// return <>{children}</>;
2023-02-08 17:58:55 -06:00
}