mirror of
https://github.com/AmanIbrash-brsh/finance-website.git
synced 2026-11-09 09:35:10 +00:00
70 lines
2.5 KiB
React
70 lines
2.5 KiB
React
import React, { useState } from 'react';
|
|
import { useNavigate } from 'react-router-dom';
|
|
|
|
export default function Auth() {
|
|
const [isLogin, setIsLogin] = useState(true);
|
|
const [email, setEmail] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [firstName, setFirstName] = useState('');
|
|
const [error, setError] = useState('');
|
|
const navigate = useNavigate();
|
|
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault();
|
|
setError('');
|
|
|
|
const url = isLogin ? '/api/auth/login' : '/api/auth/register';
|
|
const payload = isLogin ? { email, password } : { email, password, first_name: firstName };
|
|
|
|
try {
|
|
const res = await fetch(url, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(payload)
|
|
});
|
|
|
|
const data = await res.json();
|
|
if (!res.ok) {
|
|
throw new Error(data.error || 'Ошибка авторизации');
|
|
}
|
|
|
|
localStorage.setItem('token', data.token);
|
|
localStorage.setItem('user', JSON.stringify(data.user));
|
|
navigate('/');
|
|
} catch (err) {
|
|
setError(err.message);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="auth-container">
|
|
<div className="auth-box">
|
|
<h2>{isLogin ? 'Вход в систему' : 'Регистрация'}</h2>
|
|
{error && <div style={{ color: 'var(--danger)', marginBottom: '1rem', textAlign: 'center' }}>{error}</div>}
|
|
<form onSubmit={handleSubmit}>
|
|
{!isLogin && (
|
|
<div className="form-group">
|
|
<label>Имя</label>
|
|
<input type="text" value={firstName} onChange={e => setFirstName(e.target.value)} required />
|
|
</div>
|
|
)}
|
|
<div className="form-group">
|
|
<label>Email</label>
|
|
<input type="email" value={email} onChange={e => setEmail(e.target.value)} required />
|
|
</div>
|
|
<div className="form-group">
|
|
<label>Пароль</label>
|
|
<input type="password" value={password} onChange={e => setPassword(e.target.value)} required />
|
|
</div>
|
|
<button type="submit">{isLogin ? 'Войти' : 'Зарегистрироваться'}</button>
|
|
</form>
|
|
<div className="toggle-link">
|
|
<a href="#" onClick={(e) => { e.preventDefault(); setIsLogin(!isLogin); }}>
|
|
{isLogin ? 'Нет аккаунта? Зарегистрироваться' : 'Уже есть аккаунт? Войти'}
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|