el.xwx.moe/layouts/AuthRedirect.tsx

85 lines
2.6 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-11-02 13:59:31 -05:00
import useAccountStore from "@/store/account";
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-11-02 13:59:31 -05:00
const { account } = useAccountStore();
2023-02-08 17:58:55 -06:00
const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true";
const stripeEnabled = process.env.NEXT_PUBLIC_STRIPE === "true";
2023-07-19 15:39:59 -05:00
useInitialData();
2023-04-30 15:54:40 -05:00
2023-07-19 23:46:49 -05:00
useEffect(() => {
if (!router.pathname.startsWith("/public")) {
if (
status === "authenticated" &&
2023-11-02 13:59:31 -05:00
account.id &&
!account.subscription?.active &&
stripeEnabled
2023-07-19 23:46:49 -05:00
) {
router.push("/subscribe").then(() => {
2023-07-19 23:46:49 -05:00
setRedirect(false);
});
}
// Redirect to "/choose-username" if user is authenticated and is either a subscriber OR subscription is undefiend, and doesn't have a username
else if (
emailEnabled &&
2023-07-19 23:46:49 -05:00
status === "authenticated" &&
account.subscription?.active &&
stripeEnabled &&
account.id &&
!account.username
2023-07-19 23:46:49 -05:00
) {
router.push("/choose-username").then(() => {
2023-07-19 23:46:49 -05:00
setRedirect(false);
});
} else if (
status === "authenticated" &&
account.id &&
2023-07-19 23:46:49 -05:00
(router.pathname === "/login" ||
router.pathname === "/register" ||
router.pathname === "/confirmation" ||
router.pathname === "/subscribe" ||
router.pathname === "/choose-username" ||
router.pathname === "/forgot" ||
router.pathname === "/")
2023-07-19 23:46:49 -05:00
) {
router.push("/dashboard").then(() => {
2023-07-19 23:46:49 -05:00
setRedirect(false);
});
} else if (
status === "unauthenticated" &&
!(
router.pathname === "/login" ||
router.pathname === "/register" ||
router.pathname === "/confirmation" ||
router.pathname === "/forgot"
)
) {
router.push("/login").then(() => {
setRedirect(false);
});
} else if (status === "loading") setRedirect(true);
else setRedirect(false);
} else {
setRedirect(false);
}
}, [status, account, router.pathname]);
2023-02-08 17:58:55 -06:00
2023-07-19 23:46:49 -05:00
if (status !== "loading" && !redirect) return <>{children}</>;
else return <></>;
// return <>{children}</>;
2023-02-08 17:58:55 -06:00
}