2023-10-02 19:03:03 +00:00
|
|
|
import { FC, ReactNode } from "react";
|
2023-04-08 12:50:00 +00:00
|
|
|
import { useRouter } from "next/router";
|
2023-04-08 12:35:54 +00:00
|
|
|
import useSWR from "swr";
|
2023-04-08 12:50:00 +00:00
|
|
|
// services
|
2023-04-08 12:35:54 +00:00
|
|
|
import userService from "services/user.service";
|
2023-04-08 12:50:00 +00:00
|
|
|
// ui
|
|
|
|
import { Spinner } from "components/ui";
|
|
|
|
// fetch-keys
|
|
|
|
import { CURRENT_USER } from "constants/fetch-keys";
|
2023-04-08 12:35:54 +00:00
|
|
|
|
2023-10-02 19:03:03 +00:00
|
|
|
export interface IUserAuthWrapper {
|
|
|
|
children: ReactNode;
|
|
|
|
}
|
2023-04-08 12:35:54 +00:00
|
|
|
|
2023-10-02 19:03:03 +00:00
|
|
|
export const UserAuthWrapper: FC<IUserAuthWrapper> = (props) => {
|
|
|
|
const { children } = props;
|
|
|
|
// router
|
2023-04-08 12:35:54 +00:00
|
|
|
const router = useRouter();
|
2023-10-02 19:03:03 +00:00
|
|
|
// fetching user information
|
2023-04-08 12:35:54 +00:00
|
|
|
const { data: currentUser, error } = useSWR(CURRENT_USER, () => userService.currentUser());
|
|
|
|
|
|
|
|
if (!currentUser && !error) {
|
2023-04-08 12:50:00 +00:00
|
|
|
return (
|
|
|
|
<div className="h-screen grid place-items-center p-4">
|
|
|
|
<div className="flex flex-col items-center gap-3 text-center">
|
|
|
|
<Spinner />
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
);
|
2023-04-08 12:35:54 +00:00
|
|
|
}
|
|
|
|
|
2023-04-08 18:32:33 +00:00
|
|
|
if (error) {
|
2023-04-08 12:35:54 +00:00
|
|
|
const redirectTo = router.asPath;
|
2023-05-30 13:44:35 +00:00
|
|
|
router.push(`/?next=${redirectTo}`);
|
2023-04-08 12:35:54 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return <>{children}</>;
|
|
|
|
};
|