Регистрация

This commit is contained in:
Lev 2025-11-28 11:57:43 +03:00
parent 58d934884e
commit e288aa9fa8
4 changed files with 162 additions and 9 deletions

View file

@ -62,4 +62,5 @@ class DataBase :
if data["id"] == {} : if data["id"] == {} :
return {"code": 1} return {"code": 1}
else : else :
return {"code": 0, "data": {"id": data["id"]["0"], "email": email, "urls": data["urls"]["0"], "payment": data["payment"]["0"]}} return {"code": 0, "data": {"id": data["id"]["0"], "email": email, "urls": data["urls"]["0"], "payment": data["payment"]["0"]}}

View file

@ -0,0 +1,137 @@
const API_URL = "https://spectralvpn.ru:{port}";
async function sha256(text) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const hash = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
function clearErrors() {
document.querySelectorAll('.error').forEach(el => {
el.textContent = '';
el.classList.remove('active');
});
document.querySelectorAll('.input, .checkbox').forEach(el => {
el.classList.remove('invalid');
});
}
function showError(fieldId, message) {
const errorEl = document.getElementById(fieldId);
errorEl.textContent = message;
errorEl.classList.add('active');
const input = document.getElementById(fieldId.replace('Error', ''));
if (input) input.classList.add('invalid');
}
async function registration(e) {
e.preventDefault();
clearErrors();
const email = document.getElementById("email").value.trim();
const password = document.getElementById("password").value;
const passwordReply = document.getElementById("password_reply").value;
const terms = document.getElementById("terms").checked;
let hasError = false;
if (!email) {
showError("emailError", "Введите email");
hasError = true;
} else if (!/^\S+@\S+\.\S+$/.test(email)) {
showError("emailError", "Некорректный email");
hasError = true;
}
if (!password) {
showError("passwordError", "Введите пароль");
hasError = true;
} else if (password.length < 6) {
showError("passwordError", "Пароль должен быть не менее 6 символов");
hasError = true;
}
if (password !== passwordReply) {
showError("passwordReplyError", "Пароли не совпадают");
hasError = true;
}
if (!terms) {
showError("termsError", "Необходимо принять пользовательское соглашение");
document.getElementById("terms").classList.add('invalid');
hasError = true;
}
if (hasError) return;
const submitBtn = e.target.querySelector("button[type='submit']");
const originalText = submitBtn.textContent;
submitBtn.disabled = true;
submitBtn.textContent = "Создаём аккаунт...";
try {
const hashedPassword = await sha256(password);
const response = await fetch(`${API_URL}/registration`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
email: email,
password: hashedPassword
})
});
const data = await response.json();
if (response.ok) {
alert("Аккаунт успешно создан! Перенаправляем в личный кабинет...");
localStorage.setItem("user", JSON.stringify({
id: data.id,
email: data.email,
loggedIn: true,
loginTime: Date.now()
}));
window.location.href = "control-panel.html";
} else {
if (data.detail === "Email is busy.") {
showError("emailError", "Этот email уже зарегистрирован");
} else {
alert("Ошибка регистрации: " + (data.detail || "Попробуйте позже"));
}
}
} catch (err) {
console.error("Registration error:", err);
alert("Нет соединения с сервером. Проверьте интернет или попробуйте позже.");
} finally {
submitBtn.disabled = false;
submitBtn.textContent = originalText;
}
}
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("registerForm");
if (form) {
form.addEventListener("submit", registration);
}
// Подсветка полей при фокусе
document.querySelectorAll('.input').forEach(input => {
input.addEventListener('focus', () => {
input.classList.remove('invalid');
const errorId = input.id + "Error";
const errorEl = document.getElementById(errorId);
if (errorEl) {
errorEl.textContent = '';
errorEl.classList.remove('active');
}
});
});
});

View file

@ -6,6 +6,7 @@
<title>Регистрация - SpectralVPN</title> <title>Регистрация - SpectralVPN</title>
<link rel="stylesheet" href="../Styles/register.css"> <link rel="stylesheet" href="../Styles/register.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="../JS/register.js"></script>
</head> </head>
<body> <body>
<form id="registerForm" novalidate> <form id="registerForm" novalidate>
@ -14,22 +15,18 @@
<input type="email" id="email" class="input" placeholder="example@domain.com" required autocomplete="email"> <input type="email" id="email" class="input" placeholder="example@domain.com" required autocomplete="email">
<div class="error" id="emailError"></div> <div class="error" id="emailError"></div>
<label for="password">Пароль</label> <label for="password">Пароль</label>
<input type="password" id="password" class="input" placeholder="Минимум 8 символов" required minlength="8" autocomplete="new-password"> <input type="password" id="password" class="input" placeholder="Введите пароль">
<div class="error" id="passwordError"></div> <div class="error" id="passwordError"></div>
<label for="password_reply">Повторите пароль</label> <label for="password_reply">Повторите пароль</label>
<input type="password" id="password_reply" class="input" placeholder="Повторите пароль" required autocomplete="new-password"> <input type="password" id="password_reply" class="input" placeholder="Повторите пароль">
<div class="error" id="passwordReplyError"></div> <div class="error" id="passwordReplyError"></div>
<div class="checkbox-container"> <div class="checkbox-container">
<input type="checkbox" id="terms" class="checkbox" required> <input type="checkbox" id="terms" class="checkbox" required>
<label for="terms">Я прочитал и согласен с <a href="offer.html" target="_blank">пользовательским соглашением</a> и <a href="privacy.html" target="_blank">политикой конфиденциальности</a>.</label> <label for="terms">Я прочитал и согласен с <a href="offer.html" target="_blank">пользовательским соглашением</a> и <a href="privacy.html" target="_blank">политикой конфиденциальности</a>.</label>
</div> </div>
<div class="error" id="termsError"></div> <div class="error" id="termsError"></div>
<div class="checkbox-container">
<input type="checkbox" id="newsletter" class="checkbox">
<label for="newsletter">Я хочу получать новости об SpectralVPN на свою электронную почту.</label>
</div>
<button type="submit">Зарегистрироваться</button> <button type="submit">Зарегистрироваться</button>
<p>Уже есть аккаунт? <a href="control-panel.html">Войти</a></p> <p>Уже есть аккаунт? <a href="control-panel.html">Войти</a></p>
</form> </form>
</body> </body>
</html> </html>

View file

@ -125,9 +125,27 @@ p{
font-size: 0.85rem; font-size: 0.85rem;
margin-top: 6px; margin-top: 6px;
min-height: 20px; min-height: 20px;
opacity: 0;
transition: opacity 0.2s ease;
} }
@media (max-width: 480px) { .error.active{
opacity: 1;
}
.input.invalid,
.checkbox.invalid{
border-color: #ff6b6b !important;
box-shadow: 0 0 8px rgba(255, 107, 107, 0.3);
}
button:disabled{
opacity: 0.7;
cursor: not-allowed;
transform: none !important;
}
@media (max-width: 480px){
form{ form{
padding: 25px 20px; padding: 25px 20px;
} }