added security and fix edit profile

This commit is contained in:
SlimusMinus
2026-06-18 00:25:13 +03:00
parent a6a0896fe6
commit adeab4d718
9 changed files with 259 additions and 76 deletions

View File

@@ -1,14 +1,16 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { API_URL } from "../config/authConstants";
import { useAuthContext } from "../context/AuthContext";
export function useAuth() {
const navigate = useNavigate();
const { login: saveAuth } = useAuthContext();
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const login = async (login, password) => {
if (!login || !password) { setError("Введи login и пароль"); return; }
if (!login || !password) { setError("Введите логин и пароль"); return; }
setLoading(true); setError("");
try {
@@ -20,13 +22,15 @@ export function useAuth() {
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.message || "Неверный login или пароль");
throw new Error(data.message || "Неверный логин или пароль");
}
const { token, user } = await res.json();
localStorage.setItem("token", token);
localStorage.setItem("user", JSON.stringify(user));
navigate("/dashboard");
// Сохраняем в глобальный контекст + localStorage
saveAuth(user, token);
navigate("/feed");
} catch (err) {
setError(err.message);
} finally {
@@ -34,6 +38,5 @@ export function useAuth() {
}
};
return { login, loading, error };
}
}

View File

@@ -9,6 +9,8 @@ import { API_URL } from "../config/authConstants";
* id передан → PUT /api/v1/posts/:id (обновление)
* id не передан → POST /api/v1/posts (создание)
*
* Автоматически добавляет заголовок Authorization с JWT-токеном.
*
* @returns {{
* save: (id: string|null, data: FormData) => Promise<object|null>,
* loading: boolean,
@@ -28,9 +30,21 @@ export function usePostMutation() {
setLoading(true);
setError("");
try {
const token = localStorage.getItem("token");
const url = id ? `${API_URL}/api/v1/posts/${id}` : `${API_URL}/api/v1/posts`;
const method = id ? "PUT" : "POST";
const res = await fetch(url, { method, body: data });
const res = await fetch(url, {
method,
headers: {
"Authorization": `Bearer ${token}`,
},
body: data,
});
if (res.status === 401 || res.status === 403) {
throw new Error("Требуется авторизация. Войдите в аккаунт.");
}
if (!res.ok) throw new Error(`Ошибка сервера: ${res.status}`);
return await res.json();
} catch (e) {