feat: implement auth flow and app initialization
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
import { authService } from '@/services/api/auth.service';
|
||||
import { initializeAuthenticatedApp } from '@/services/initializer.service';
|
||||
import { useAppStore } from '@/store/app.store';
|
||||
import { useAuthStore } from '@/store/auth.store';
|
||||
import type { LoginPayload, UserProfile } from '@/types';
|
||||
import type { LoginPayload } 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 setAccessToken = useAuthStore((state) => state.setAccessToken);
|
||||
const setLoading = useAppStore((state) => state.setLoading);
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
@@ -23,32 +26,26 @@ export const useLoginForm = () => {
|
||||
|
||||
const onSubmit = async (data: LoginPayload) => {
|
||||
try {
|
||||
const callbackUrl =
|
||||
new URLSearchParams(window.location.search).get('callbackUrl') ?? ROUTES.DASHBOARD;
|
||||
const result = await signIn('credentials', {
|
||||
console.debug('[auth] login:start');
|
||||
const loginResponse = await authService.login({
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
redirect: false,
|
||||
callbackUrl,
|
||||
});
|
||||
const accessToken = loginResponse.access_token;
|
||||
|
||||
if (result?.error) {
|
||||
toast.error(result.error);
|
||||
if (!accessToken) {
|
||||
toast.error('Login failed: no access token returned');
|
||||
return;
|
||||
}
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user) {
|
||||
setAuth(
|
||||
session.user as UserProfile,
|
||||
session.accessToken ?? null,
|
||||
session.refreshToken ?? null,
|
||||
);
|
||||
}
|
||||
setAccessToken(accessToken);
|
||||
setLoading();
|
||||
console.debug('[auth] login:token-stored');
|
||||
await initializeAuthenticatedApp();
|
||||
console.debug('[auth] login:initialized, redirecting', ROUTES.DASHBOARD);
|
||||
|
||||
toast.success('Login successful');
|
||||
router.push(result?.url ?? callbackUrl);
|
||||
router.refresh();
|
||||
router.push(ROUTES.DASHBOARD);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Unable to sign in');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user