mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 20:13:49 +00:00
Update: update confirm user, user account page
This commit is contained in:
69
src/hooks/auth/useConfirmUser.ts
Normal file
69
src/hooks/auth/useConfirmUser.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import UserContext from '@/contexts/UserContext';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useState, useContext, useEffect } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR from 'swr';
|
||||
|
||||
const useConfirmUser = () => {
|
||||
const router = useRouter();
|
||||
const { user, mutate } = useContext(UserContext);
|
||||
const token = router.query.token as string | undefined;
|
||||
const [needsToLogin, setNeedsToLogin] = useState(false);
|
||||
const [tokenInvalid, setTokenInvalid] = useState(false);
|
||||
|
||||
const fetcher = async <T extends string>(url: T) => {
|
||||
if (!token) {
|
||||
throw new Error('Token must be provided.');
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
const json = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
if (!parsed.success) {
|
||||
throw new Error('API response validation failed.');
|
||||
}
|
||||
|
||||
mutate!();
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
const { data, error } = useSWR(`/api/users/confirm?token=${token}`, fetcher);
|
||||
|
||||
useEffect(() => {
|
||||
const loadingToast = toast.loading('Attempting to confirm your account.');
|
||||
if (user && user.accountIsVerified) {
|
||||
toast.remove(loadingToast);
|
||||
router.replace('/users/current');
|
||||
toast('Your account is already verified.');
|
||||
}
|
||||
if (!token) {
|
||||
toast.remove(loadingToast);
|
||||
setTokenInvalid(true);
|
||||
setNeedsToLogin(false);
|
||||
}
|
||||
if (user && !user.accountIsVerified && !data) {
|
||||
toast.remove(loadingToast);
|
||||
setTokenInvalid(true);
|
||||
setNeedsToLogin(false);
|
||||
}
|
||||
|
||||
if (error instanceof Error && error.message === 'Unauthorized') {
|
||||
toast.remove(loadingToast);
|
||||
setTokenInvalid(false);
|
||||
setNeedsToLogin(true);
|
||||
}
|
||||
|
||||
return () => {
|
||||
toast.remove(loadingToast);
|
||||
};
|
||||
}, [error, data, router, user, token]);
|
||||
|
||||
return { needsToLogin, tokenInvalid };
|
||||
};
|
||||
|
||||
export default useConfirmUser;
|
||||
Reference in New Issue
Block a user