added files in git
This commit is contained in:
288
src/components/AuthModal.jsx
Normal file
288
src/components/AuthModal.jsx
Normal file
@@ -0,0 +1,288 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
/**
|
||||
* AuthModal — модальное окно входа и регистрации прямо на странице ленты.
|
||||
* Открывается когда неавторизованный пользователь пытается создать объявление.
|
||||
*/
|
||||
export default function AuthModal({ onClose }) {
|
||||
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" ? "Вход в аккаунт" : "Регистрация"}
|
||||
</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 [login, setLogin] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!login || !password) { setError("Введите логин и пароль"); 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 || "Неверный логин или пароль");
|
||||
}
|
||||
|
||||
const { token, user } = await res.json();
|
||||
saveAuth(user, token);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">Логин</label>
|
||||
<input
|
||||
className="f-m-field"
|
||||
type="text"
|
||||
placeholder="Ваш логин"
|
||||
value={login}
|
||||
onChange={e => { setLogin(e.target.value); setError(""); }}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">Пароль</label>
|
||||
<input
|
||||
className="f-m-field"
|
||||
type="password"
|
||||
placeholder="Ваш пароль"
|
||||
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="Войти"
|
||||
onClick={handleSubmit}
|
||||
/>
|
||||
|
||||
<p style={{
|
||||
textAlign: "center", marginTop: 14,
|
||||
color: "rgba(255,255,255,.45)", fontSize: ".85rem"
|
||||
}}>
|
||||
Нет аккаунта?{" "}
|
||||
<button
|
||||
onClick={onSwitch}
|
||||
style={{
|
||||
background: "none", border: "none", color: "#2de0c8",
|
||||
cursor: "pointer", fontWeight: 700, fontSize: ".85rem",
|
||||
fontFamily: "var(--font)",
|
||||
}}
|
||||
>
|
||||
Зарегистрироваться
|
||||
</button>
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Register form (inline modal) ──────────────────────────────────────────
|
||||
function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
|
||||
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 = "Введите имя";
|
||||
if (!form.login.trim()) e.login = "Введите логин";
|
||||
else if (form.login.length < 3) e.login = "Минимум 3 символа";
|
||||
if (form.password.length < 6) e.password = "Минимум 6 символов";
|
||||
if (form.password !== form.password2) e.password2 = "Пароли не совпадают";
|
||||
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 || "Ошибка регистрации");
|
||||
|
||||
// 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, user } = await loginRes.json();
|
||||
saveAuth(user, token);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">Имя</label>
|
||||
<input
|
||||
className={`f-m-field${errors.name ? " err" : ""}`}
|
||||
type="text"
|
||||
placeholder="Как вас зовут?"
|
||||
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">Логин</label>
|
||||
<input
|
||||
className={`f-m-field${errors.login ? " err" : ""}`}
|
||||
type="text"
|
||||
placeholder="Придумайте логин"
|
||||
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">Пароль</label>
|
||||
<input
|
||||
className={`f-m-field${errors.password ? " err" : ""}`}
|
||||
type="password"
|
||||
placeholder="Мин. 6 символов"
|
||||
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">Повторите</label>
|
||||
<input
|
||||
className={`f-m-field${errors.password2 ? " err" : ""}`}
|
||||
type="password"
|
||||
placeholder="Ещё раз"
|
||||
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="Создать аккаунт"
|
||||
onClick={handleSubmit}
|
||||
/>
|
||||
|
||||
<p style={{
|
||||
textAlign: "center", marginTop: 14,
|
||||
color: "rgba(255,255,255,.45)", fontSize: ".85rem"
|
||||
}}>
|
||||
Уже есть аккаунт?{" "}
|
||||
<button
|
||||
onClick={onSwitch}
|
||||
style={{
|
||||
background: "none", border: "none", color: "#2de0c8",
|
||||
cursor: "pointer", fontWeight: 700, fontSize: ".85rem",
|
||||
fontFamily: "var(--font)",
|
||||
}}
|
||||
>
|
||||
Войти
|
||||
</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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user