314 lines
11 KiB
JavaScript
314 lines
11 KiB
JavaScript
import React, { useState, useEffect } from 'react';
|
||
import axios from 'axios';
|
||
import { useNavigate } from 'react-router-dom';
|
||
import Header from './Header';
|
||
|
||
const Profile = () => {
|
||
const [user, setUser] = useState(null);
|
||
const [userName, setUserName] = useState(null);
|
||
const [error, setError] = useState('');
|
||
const [showConfirm, setShowConfirm] = useState(false); // Состояние для поп-апа
|
||
const [ShowConfirmUserName, setShowConfirmUserName] = useState(false);
|
||
const [new_username, setnew_username] = useState('');
|
||
const [ShowConfirmName, setShowConfirmName] = useState(false);
|
||
//const [display_name, setdisplay_name] = useState('');
|
||
const [new_display_name, setnew_display_name] = useState('');
|
||
const navigate = useNavigate();
|
||
const [showChangePassword, setShowChangePassword] = useState(false);
|
||
const [old_password, setold_password] = useState('');
|
||
const [new_password, setnew_password] = useState('');
|
||
const [new_password_confirm, setnew_password_confirm] = useState('');
|
||
const [passwordError, setPasswordError] = useState('');
|
||
useEffect(() => {
|
||
const checkSession = async () => {
|
||
try {
|
||
const response = await axios.get('/api/users/me');
|
||
setUser(response.data.display_name);
|
||
setUserName(response.data.username)
|
||
} catch (err) {
|
||
// Если нет сессии - редирект на логин
|
||
setError('Вы не авторизованы');
|
||
setTimeout(() => {
|
||
window.location.href = '/login';
|
||
}, 1500);
|
||
}
|
||
};
|
||
checkSession();
|
||
}, []);
|
||
|
||
const handleLogout = async () => {
|
||
try {
|
||
await axios.post('/api/users/logout');
|
||
setUser(null);
|
||
window.location.href = '/login'; // Редирект после выхода
|
||
} catch (err) {
|
||
setError('Ошибка');
|
||
}
|
||
};
|
||
const NewDisplayName = async (e) => {
|
||
e.preventDefault();
|
||
setError('');
|
||
try {
|
||
await axios.put('api/users/change_display_name', {new_display_name},
|
||
{
|
||
withCredentials: true
|
||
/*headers: {
|
||
'Content-Type': 'application/json'
|
||
}*/
|
||
}
|
||
);
|
||
setShowConfirmName(false);
|
||
try {
|
||
const response = await axios.get('/api/users/me');
|
||
setUser(response.data.display_name);
|
||
setUserName(response.data.username);
|
||
} catch (err) {
|
||
// Если нет сессии - редирект на логин
|
||
setError('Вы не авторизованы');
|
||
setTimeout(() => {
|
||
window.location.href = '/login';
|
||
}, 1500);
|
||
}
|
||
} catch (err) {
|
||
setError(err.response.data.detail || 'Ошибка входа');
|
||
}
|
||
};
|
||
|
||
const NewUserName = async (e) => {
|
||
e.preventDefault();
|
||
setError('');
|
||
try {
|
||
await axios.put('api/users/change_username', {new_username},
|
||
{
|
||
withCredentials: true
|
||
/*headers: {
|
||
'Content-Type': 'application/json'
|
||
}*/
|
||
}
|
||
);
|
||
setShowConfirmUserName(false);
|
||
try {
|
||
const response = await axios.get('/api/users/me');
|
||
setUserName(response.data.username);
|
||
setUser(response.data.display_name);
|
||
} catch (err) {
|
||
// Если нет сессии - редирект на логин
|
||
setError('Вы не авторизованы');
|
||
}
|
||
} catch (err) {
|
||
setError(err.response.data.detail || 'Ошибка входа');
|
||
}
|
||
};
|
||
|
||
const changePassword = async (e) => {
|
||
e.preventDefault();
|
||
setPasswordError('');
|
||
|
||
try {
|
||
const NewPassword = {old_password, new_password, new_password_confirm}
|
||
await axios.put('/api/users/change_password',
|
||
NewPassword
|
||
, {
|
||
withCredentials: true
|
||
});
|
||
|
||
alert('Пароль успешно изменён!');
|
||
setShowChangePassword(false);
|
||
setold_password('');
|
||
setnew_password('');
|
||
setnew_password_confirm('');
|
||
} catch (err) {
|
||
setPasswordError(
|
||
err.response?.data?.detail || 'Ошибка при смене пароля'
|
||
);
|
||
}
|
||
};
|
||
|
||
|
||
const OpenWindowDelete = () => {
|
||
setShowConfirm(true); // Показываем окно подтверждения
|
||
};
|
||
|
||
const closeWindowDelete = () => {
|
||
setShowConfirm(false);
|
||
};
|
||
|
||
const OpenWindowName = () => {
|
||
setShowConfirmName(true); // Показываем окно подтверждения
|
||
};
|
||
|
||
const closeWindowName = () => {
|
||
setShowConfirmName(false);
|
||
};
|
||
|
||
const OpenWindowUserName = () => {
|
||
setShowConfirmUserName(true); // Показываем окно подтверждения
|
||
};
|
||
|
||
const closeWindowUserName = () => {
|
||
setShowConfirmUserName(false); // Показываем окно подтверждения
|
||
};
|
||
|
||
const deleteAccount = async () => {
|
||
try {
|
||
await axios.delete('/api/users/me', {
|
||
withCredentials: true
|
||
});
|
||
setUser(null);
|
||
window.location.href = '/login';
|
||
setShowConfirm(false); // Закрываем окно после удаления
|
||
} catch (err) {
|
||
setError('Ошибка удаления');
|
||
setShowConfirm(false); // Закрываем окно при ошибке
|
||
}
|
||
};
|
||
|
||
return (
|
||
<><Header />
|
||
<div className="profile-page">
|
||
|
||
{
|
||
error && <div className="error">{error}</div>
|
||
}
|
||
|
||
{user && (
|
||
<div className="user-info">
|
||
<p><strong>Привет, {user}! Добро пожаловать в личный кабинет.</strong></p>
|
||
<div className="text-block">Здесь ты сможешь управлять данными своей учётной записи.</div>
|
||
<p>Информация об учётной записи</p>
|
||
<div className="com">Отображаемое имя</div>
|
||
<div className="buttonName">
|
||
<div className="frame"><p>{user}</p></div>
|
||
<button onClick={OpenWindowName}>✎</button>
|
||
</div>
|
||
<div className="com">Логин</div>
|
||
<div className="buttonName">
|
||
<div className="frame"><p>{userName}</p></div>
|
||
<button onClick={OpenWindowUserName}>✎</button>
|
||
</div>
|
||
<p>Изменить пароль</p>
|
||
<div className="com">В целях безопасности мы рекомендуем выбрать пароль, который ещё не использовался вами в других учётных записях.</div>
|
||
<button onClick={() => setShowChangePassword(true)}
|
||
className="button-small">Изменить пароль</button>
|
||
<button onClick={handleLogout}>Выйти из аккаунта</button>
|
||
<button onClick={OpenWindowDelete}>Удалить аккаунт</button>
|
||
</div>
|
||
)}
|
||
|
||
{ShowConfirmUserName && (
|
||
<div className="confirm-modal">
|
||
<div className="modal-content">
|
||
<div><h3>Обновите логин</h3></div>
|
||
<div><p>Текущий логин: {userName}</p></div>
|
||
<div className="com">Новый логин</div>
|
||
<form onSubmit={NewUserName}>
|
||
<div>
|
||
<input
|
||
type="text"
|
||
value={new_username}
|
||
onChange={(e) => setnew_username(e.target.value)}
|
||
required
|
||
/>
|
||
</div>
|
||
<button type="submit">Подтвердить</button>
|
||
</form>
|
||
<button onClick={closeWindowUserName}>Отменить</button>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{ShowConfirmName && (
|
||
<div className="confirm-modal">
|
||
<div className="modal-content">
|
||
<div><h3>Обновите отображаемое имя</h3></div>
|
||
<div><p>Текущее отображаемое имя: {user}</p></div>
|
||
<div className="com">Новое отображаемое имя</div>
|
||
<form onSubmit={NewDisplayName}>
|
||
<div>
|
||
<input
|
||
type="text"
|
||
value={new_display_name}
|
||
onChange={(e) => setnew_display_name(e.target.value)}
|
||
required
|
||
/>
|
||
</div>
|
||
<button type="submit">Подтвердить</button>
|
||
</form>
|
||
<button onClick={closeWindowName}>Отменить</button>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{showChangePassword && (
|
||
<div className="confirm-modal">
|
||
<div className="modal-content">
|
||
<h3>Изменить пароль</h3>
|
||
|
||
{passwordError && (
|
||
<div className="error" style={{ color: 'red' }}>
|
||
{passwordError}
|
||
</div>
|
||
)}
|
||
|
||
<form onSubmit={changePassword}>
|
||
<div className="form-group">
|
||
<label>Текущий пароль:</label>
|
||
<input
|
||
type="password"
|
||
value={old_password}
|
||
onChange={(e) => setold_password(e.target.value)}
|
||
required
|
||
/>
|
||
</div>
|
||
|
||
<div className="form-group">
|
||
<label>Новый пароль:</label>
|
||
<input
|
||
type="password"
|
||
value={new_password}
|
||
onChange={(e) => setnew_password(e.target.value)}
|
||
required
|
||
/>
|
||
</div>
|
||
|
||
<div className="form-group">
|
||
<label>Повторите новый пароль:</label>
|
||
<input
|
||
type="password"
|
||
value={new_password_confirm}
|
||
onChange={(e) => setnew_password_confirm(e.target.value)}
|
||
required
|
||
/>
|
||
</div>
|
||
|
||
<div className="modal-buttons">
|
||
<button type="submit">Изменить пароль</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => setShowChangePassword(false)}
|
||
>
|
||
Отменить
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{/* Всплывающее окно подтверждения */}
|
||
{showConfirm && (
|
||
<div className="confirm-modal">
|
||
<div className="modal-content">
|
||
<p><strong>Вы действительно хотите удалить аккаунта?</strong></p>
|
||
<div className="modal-buttons">
|
||
<button onClick={deleteAccount}>Подтвердить</button>
|
||
<button onClick={closeWindowDelete}>Отменить</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div></>
|
||
);
|
||
};
|
||
|
||
export default Profile; |