feat: add frontend authentication flow
This commit is contained in:
+13
-13
@@ -1,29 +1,29 @@
|
|||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
|
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
|
||||||
|
import { AuthGuard } from '@/components/auth-guard';
|
||||||
import { DashboardPage } from '@/pages/dashboard-page';
|
import { DashboardPage } from '@/pages/dashboard-page';
|
||||||
import { LandingPage } from '@/pages/landing-page';
|
import { LandingPage } from '@/pages/landing-page';
|
||||||
import { CatalogPage } from '@/pages/catalog-page';
|
import { CatalogPage } from '@/pages/catalog-page';
|
||||||
import { DiseaseDetailPage } from '@/pages/disease-detail-page';
|
import { DiseaseDetailPage } from '@/pages/disease-detail-page';
|
||||||
|
import { LoginPage } from '@/pages/login-page';
|
||||||
|
import { RegisterPage } from '@/pages/register-page';
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
const router = createBrowserRouter([
|
const router = createBrowserRouter([
|
||||||
{
|
{ path: '/', element: <LandingPage /> },
|
||||||
path: '/',
|
{ path: '/login', element: <LoginPage /> },
|
||||||
element: <LandingPage />,
|
{ path: '/register', element: <RegisterPage /> },
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: '/dashboard',
|
path: '/dashboard',
|
||||||
element: <DashboardPage />,
|
element: (
|
||||||
},
|
<AuthGuard>
|
||||||
{
|
<DashboardPage />
|
||||||
path: '/catalog',
|
</AuthGuard>
|
||||||
element: <CatalogPage />,
|
),
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/catalog/:slug',
|
|
||||||
element: <DiseaseDetailPage />,
|
|
||||||
},
|
},
|
||||||
|
{ path: '/catalog', element: <CatalogPage /> },
|
||||||
|
{ path: '/catalog/:slug', element: <DiseaseDetailPage /> },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { FormEvent, useState } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
|
||||||
|
type AuthFormProps = {
|
||||||
|
mode: 'login' | 'register';
|
||||||
|
isSubmitting: boolean;
|
||||||
|
error: string | null;
|
||||||
|
googleOAuthEnabled: boolean;
|
||||||
|
onSubmit: (payload: { name?: string; email: string; password: string }) => Promise<unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AuthForm({ mode, isSubmitting, error, googleOAuthEnabled, onSubmit }: AuthFormProps) {
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [email, setEmail] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
|
||||||
|
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
await onSubmit({ name, email, password });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="mx-auto w-full max-w-md">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{mode === 'login' ? 'Masuk ke ZeaVis Edu' : 'Buat akun ZeaVis Edu'}</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{mode === 'login'
|
||||||
|
? 'Masuk untuk melihat riwayat diagnosis daun jagung Anda.'
|
||||||
|
: 'Daftar untuk menyimpan diagnosis dan mengikuti review pakar.'}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form className="space-y-4" onSubmit={handleSubmit}>
|
||||||
|
{mode === 'register' && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Nama</Label>
|
||||||
|
<Input id="name" value={name} onChange={(event) => setName(event.target.value)} required />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input id="email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} required />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input id="password" type="password" minLength={8} value={password} onChange={(event) => setPassword(event.target.value)} required />
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||||
|
<Button className="w-full" type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting ? 'Memproses...' : mode === 'login' ? 'Masuk' : 'Daftar'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
{googleOAuthEnabled && (
|
||||||
|
<Button className="mt-3 w-full" variant="outline" asChild>
|
||||||
|
<a href="/api/v1/auth/google">Masuk dengan Google</a>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { ReactNode, useEffect } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { Navigate } from 'react-router-dom';
|
||||||
|
import { apiClient } from '@/lib/api-client';
|
||||||
|
import { useAuthStore } from '@/store/auth-store';
|
||||||
|
|
||||||
|
type AuthGuardProps = {
|
||||||
|
children: ReactNode;
|
||||||
|
requireExpert?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function AuthGuard({ children, requireExpert = false }: AuthGuardProps) {
|
||||||
|
const setUser = useAuthStore((state) => state.setUser);
|
||||||
|
const query = useQuery({
|
||||||
|
queryKey: ['auth', 'me'],
|
||||||
|
queryFn: () => apiClient.getMe(),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (query.data) {
|
||||||
|
setUser(query.data.user);
|
||||||
|
}
|
||||||
|
}, [query.data, setUser]);
|
||||||
|
|
||||||
|
if (query.isLoading) {
|
||||||
|
return <main className="min-h-screen p-8 text-center text-muted-foreground">Memeriksa sesi...</main>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!query.data?.user) {
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requireExpert && query.data.user.role !== 'expert') {
|
||||||
|
return <Navigate to="/dashboard" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { InputHTMLAttributes } from 'react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
className={cn(
|
||||||
|
'flex h-10 w-full rounded-md border border-border bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { LabelHTMLAttributes } from 'react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
export function Label({ className, ...props }: LabelHTMLAttributes<HTMLLabelElement>) {
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
className={cn('text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70', className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { AuthForm } from '@/components/auth-form';
|
||||||
|
import { apiClient } from '@/lib/api-client';
|
||||||
|
import { useAuthStore } from '@/store/auth-store';
|
||||||
|
|
||||||
|
export function LoginPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const setUser = useAuthStore((state) => state.setUser);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const meQuery = useQuery({ queryKey: ['auth', 'me'], queryFn: () => apiClient.getMe() });
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: apiClient.login,
|
||||||
|
onSuccess: (response) => {
|
||||||
|
setUser(response.user);
|
||||||
|
queryClient.setQueryData(['auth', 'me'], response);
|
||||||
|
navigate('/dashboard');
|
||||||
|
},
|
||||||
|
onError: (err) => setError(err instanceof Error ? err.message : 'Login gagal'),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex min-h-screen items-center justify-center px-6 py-12">
|
||||||
|
<div className="w-full space-y-4">
|
||||||
|
<AuthForm
|
||||||
|
mode="login"
|
||||||
|
isSubmitting={mutation.isPending}
|
||||||
|
error={error}
|
||||||
|
googleOAuthEnabled={Boolean(meQuery.data?.features.googleOAuthEnabled)}
|
||||||
|
onSubmit={async ({ email, password }) => mutation.mutateAsync({ email, password })}
|
||||||
|
/>
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
Belum punya akun? <Link className="text-primary" to="/register">Daftar</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { AuthForm } from '@/components/auth-form';
|
||||||
|
import { apiClient } from '@/lib/api-client';
|
||||||
|
import { useAuthStore } from '@/store/auth-store';
|
||||||
|
|
||||||
|
export function RegisterPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const setUser = useAuthStore((state) => state.setUser);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const meQuery = useQuery({ queryKey: ['auth', 'me'], queryFn: () => apiClient.getMe() });
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: apiClient.register,
|
||||||
|
onSuccess: (response) => {
|
||||||
|
setUser(response.user);
|
||||||
|
queryClient.setQueryData(['auth', 'me'], response);
|
||||||
|
navigate('/dashboard');
|
||||||
|
},
|
||||||
|
onError: (err) => setError(err instanceof Error ? err.message : 'Registrasi gagal'),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex min-h-screen items-center justify-center px-6 py-12">
|
||||||
|
<div className="w-full space-y-4">
|
||||||
|
<AuthForm
|
||||||
|
mode="register"
|
||||||
|
isSubmitting={mutation.isPending}
|
||||||
|
error={error}
|
||||||
|
googleOAuthEnabled={Boolean(meQuery.data?.features.googleOAuthEnabled)}
|
||||||
|
onSubmit={async ({ name, email, password }) => mutation.mutateAsync({ name: name ?? '', email, password })}
|
||||||
|
/>
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
Sudah punya akun? <Link className="text-primary" to="/login">Masuk</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user