'use client'; import { useState } from 'react'; import { Button } from '@/components/ui/button'; import GoogleIcon from '../../../../public/icons/google.svg'; import { InputField } from '@/components/ui/inputfield'; import { useAuthContext } from '@/lib/contexts/Auth.context'; export default function LoginForm() { const [errors, setErrors] = useState({}); const [loading, setLoading] = useState(false); const { setUser } = useAuthContext(); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setErrors({}); const formData = new FormData(e.currentTarget); const emailOrUsername = formData.get('emailOrUsername')?.toString() || ''; const password = formData.get('password')?.toString() || ''; const newErrors: any = {}; if (!emailOrUsername) newErrors.emailOrUsername = 'Введите никнейм или email'; if (!password) newErrors.password = 'Введите пароль'; if (Object.keys(newErrors).length > 0) { setErrors(newErrors); setLoading(false); return; } const body = new URLSearchParams(); body.append('username', emailOrUsername); body.append('password', password); try { const res = await fetch('http://localhost:8000/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: body.toString(), }); const data = await res.json(); if (!res.ok) { setErrors({ general: 'Неверный логин или пароль' }); } else if (data.access_token) { localStorage.setItem('token', data.access_token); const meRes = await fetch('http://localhost:8000/api/me', { headers: { Authorization: `Bearer ${data.access_token}` }, }); const meData = await meRes.json(); setUser(meData); } } finally { setLoading(false); } }; return (
{errors.emailOrUsername && (

{errors.emailOrUsername}

)}
{errors.password && (

{errors.password}

)} {!errors.password && errors.general && (

{errors.general}

)}
); }