Files
nahodka-front/src/components/AuthModal.jsx
2026-08-03 02:44:57 +03:00

296 lines
9.8 KiB
JavaScript

import { useState, useCallback } from "react";
import { useTranslation } from 'react-i18next';
import CloseIcon from "./icons/CloseIcon";
import { useAuthContext } from "../context/AuthContext";
import { API_URL } from "../config/authConstants";
import { saveTokens } from "../api/apiClient";
/**
* AuthModal — модальное окно входа и регистрации прямо на странице ленты.
* Открывается когда неавторизованный пользователь пытается создать объявление.
*/
export default function AuthModal({ onClose }) {
const { t } = useTranslation();
const [mode, setMode] = useState("login"); // "login" | "register"
const { login: saveAuth } = useAuthContext();
return (
<div className="f-modal-bg" onClick={e => e.target === e.currentTarget && onClose()}>
<div className="f-modal" style={{ width: 420 }}>
{/* Header */}
<div className="f-modal-head">
<span className="f-modal-title">
{mode === "login" ? t('auth.loginModalTitle') : t('auth.registerModalTitle')}
</span>
<button className="f-close-btn" onClick={onClose}>
<CloseIcon />
</button>
</div>
{mode === "login"
? <LoginFormInline
saveAuth={saveAuth}
onClose={onClose}
onSwitch={() => setMode("register")}
/>
: <RegisterFormInline
saveAuth={saveAuth}
onClose={onClose}
onSwitch={() => setMode("login")}
/>
}
</div>
</div>
);
}
// ─── Login form (inline modal) ──────────────────────────────────────────────
function LoginFormInline({ saveAuth, onClose, onSwitch }) {
const { t } = useTranslation();
const [login, setLogin] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const handleSubmit = async () => {
if (!login || !password) { setError(t('auth.enterLoginPassword')); return; }
setLoading(true); setError("");
try {
const res = await fetch(`${API_URL}/api/v1/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ login, password }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.message || t('auth.invalidCredentials'));
}
const { token, refreshToken, user } = await res.json();
saveTokens(token, refreshToken);
saveAuth(user, token);
onClose();
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<>
<div className="f-m-group">
<label className="f-m-label">{t('auth.loginLabel')}</label>
<input
className="f-m-field"
type="text"
placeholder={t('auth.yourLogin')}
value={login}
onChange={e => { setLogin(e.target.value); setError(""); }}
autoComplete="off"
/>
</div>
<div className="f-m-group">
<label className="f-m-label">{t('auth.passwordLabel')}</label>
<input
className="f-m-field"
type="password"
placeholder={t('auth.yourPassword')}
value={password}
onChange={e => { setPassword(e.target.value); setError(""); }}
onKeyDown={e => e.key === "Enter" && handleSubmit()}
/>
</div>
{error && <p className="f-err-msg" style={{ marginBottom: 10 }}>{error}</p>}
<SubmitButton
loading={loading}
label={t('auth.login')}
onClick={handleSubmit}
/>
<p style={{
textAlign: "center", marginTop: 14,
color: "rgba(255,255,255,.45)", fontSize: ".85rem"
}}>
{t('auth.noAccount')}{" "}
<button
onClick={onSwitch}
style={{
background: "none", border: "none", color: "#2de0c8",
cursor: "pointer", fontWeight: 700, fontSize: ".85rem",
fontFamily: "var(--font)",
}}
>
{t('auth.register')}
</button>
</p>
</>
);
}
// ─── Register form (inline modal) ──────────────────────────────────────────
function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
const { t } = useTranslation();
const [form, setForm] = useState({
name: "", login: "", password: "", password2: "",
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [errors, setErrors] = useState({});
const setField = useCallback((key, val) => {
setForm(p => ({ ...p, [key]: val }));
setErrors(p => ({ ...p, [key]: "" }));
}, []);
const validate = () => {
const e = {};
if (!form.name.trim()) e.name = t('auth.validateNameRequired');
if (!form.login.trim()) e.login = t('auth.validateLoginRequired');
else if (form.login.length < 3) e.login = t('auth.loginMinChars');
if (form.password.length < 6) e.password = t('auth.validatePasswordMin');
if (form.password !== form.password2) e.password2 = t('auth.validatePasswordMatch');
setErrors(e);
return !Object.keys(e).length;
};
const handleSubmit = async () => {
if (!validate()) return;
setLoading(true); setError("");
try {
// 1. Регистрация
const regRes = await fetch(`${API_URL}/api/v1/auth/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: form.name,
login: form.login,
password: form.password,
}),
});
const regData = await regRes.json();
if (!regRes.ok) throw new Error(regData.message || t('auth.registrationError'));
// 2. Автоматический вход после регистрации
const loginRes = await fetch(`${API_URL}/api/v1/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ login: form.login, password: form.password }),
});
if (!loginRes.ok) throw new Error("Аккаунт создан. Войдите вручную.");
const { token, refreshToken, user } = await loginRes.json();
saveTokens(token, refreshToken);
saveAuth(user, token);
onClose();
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<>
<div className="f-m-group">
<label className="f-m-label">{t('auth.nameLabel')}</label>
<input
className={`f-m-field${errors.name ? " err" : ""}`}
type="text"
placeholder={t('auth.namePlaceholder')}
value={form.name}
onChange={e => setField("name", e.target.value)}
/>
{errors.name && <p className="f-err-msg">{errors.name}</p>}
</div>
<div className="f-m-group">
<label className="f-m-label">{t('auth.loginLabel')}</label>
<input
className={`f-m-field${errors.login ? " err" : ""}`}
type="text"
placeholder={t('auth.loginPlaceholder')}
value={form.login}
onChange={e => setField("login", e.target.value)}
/>
{errors.login && <p className="f-err-msg">{errors.login}</p>}
</div>
<div className="f-m-row">
<div className="f-m-group">
<label className="f-m-label">{t('auth.passwordLabel')}</label>
<input
className={`f-m-field${errors.password ? " err" : ""}`}
type="password"
placeholder={t('auth.passwordMinShort')}
value={form.password}
onChange={e => setField("password", e.target.value)}
/>
{errors.password && <p className="f-err-msg">{errors.password}</p>}
</div>
<div className="f-m-group">
<label className="f-m-label">{t('auth.repeatLabel')}</label>
<input
className={`f-m-field${errors.password2 ? " err" : ""}`}
type="password"
placeholder={t('auth.repeatPlaceholder')}
value={form.password2}
onChange={e => setField("password2", e.target.value)}
/>
{errors.password2 && <p className="f-err-msg">{errors.password2}</p>}
</div>
</div>
{error && <p className="f-err-msg" style={{ marginBottom: 10 }}>{error}</p>}
<SubmitButton
loading={loading}
label={t('auth.createAccountBtn').replace(' ✓', '')}
onClick={handleSubmit}
/>
<p style={{
textAlign: "center", marginTop: 14,
color: "rgba(255,255,255,.45)", fontSize: ".85rem"
}}>
{t('auth.hasAccount')}{" "}
<button
onClick={onSwitch}
style={{
background: "none", border: "none", color: "#2de0c8",
cursor: "pointer", fontWeight: 700, fontSize: ".85rem",
fontFamily: "var(--font)",
}}
>
{t('auth.loginLink')}
</button>
</p>
</>
);
}
// ─── Shared submit button ──────────────────────────────────────────────────
function SubmitButton({ loading, label, onClick }) {
return (
<button
className="f-m-submit"
onClick={onClick}
disabled={loading}
style={{ marginTop: 6 }}
>
<div className="f-m-submit-row">
{loading && <div className="f-m-spinner" />}
{label}
</div>
</button>
);
}