feat: add auth setup and login flow

This commit is contained in:
2026-06-15 15:56:35 +05:30
parent 134e2d1bb8
commit 9de65d0ce6
18 changed files with 664 additions and 19 deletions

63
src/hooks/useLoginForm.ts Normal file
View 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,
};
};