feat: add auth setup and login flow
This commit is contained in:
63
src/hooks/useLoginForm.ts
Normal file
63
src/hooks/useLoginForm.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useAuthStore } from '@/store/auth.store';
|
||||
import type { LoginPayload, UserProfile } from '@/types';
|
||||
import { ROUTES } from '@/utils/routes';
|
||||
import { getSession, signIn } from 'next-auth/react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export const useLoginForm = () => {
|
||||
const router = useRouter();
|
||||
const setAuth = useAuthStore((state) => state.setAuth);
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<LoginPayload>({
|
||||
defaultValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
rememberMe: false,
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: LoginPayload) => {
|
||||
try {
|
||||
const callbackUrl =
|
||||
new URLSearchParams(window.location.search).get('callbackUrl') ?? ROUTES.DASHBOARD;
|
||||
const result = await signIn('credentials', {
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
redirect: false,
|
||||
callbackUrl,
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user) {
|
||||
setAuth(
|
||||
session.user as UserProfile,
|
||||
session.accessToken ?? null,
|
||||
session.refreshToken ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
toast.success('Login successful');
|
||||
router.push(result?.url ?? callbackUrl);
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Unable to sign in');
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
register,
|
||||
handleSubmit: handleSubmit(onSubmit),
|
||||
errors,
|
||||
isLoading: isSubmitting,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user