Files
wedding-site/server/frontend/auth/login.js
MH.Dmitrii 0e2a17a3e3
All checks were successful
Build Docker / deploy (push) Successful in 38s
Build Docker / build (push) Successful in 39s
fix login.js 0.148
2026-03-19 02:00:48 +03:00

74 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
function getToken() {
return localStorage.getItem("token") || sessionStorage.getItem("token");
}
function tokenCheck(){
const token = getToken();
if (token) {
window.location.href = "https://ru.homyk.space/main";
}
}
document.getElementById('loginForm').addEventListener('submit', async function (e) {
e.preventDefault();
const password = document.getElementById('password').value;
const userData = {
password
};
try {
const response = await fetch("https://ru.homyk.space/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code: userData.password
}),
});
const data = await response.json(); // читаем только один раз
if (response.ok) { // сохраняем только при успехе
// в sessionstorage до перезахода в браузер(
sessionStorage.setItem("token", data.access_token);
window.location.href = 'https://ru.homyk.space/main';
} else { //парсинг и вывод ошибок, если есть
if (Array.isArray(data.detail)) {
const messages = data.detail.map(e => {
const field = e.loc.filter(locPart => locPart !== 'body').join(' -> ');
return `${field}: ${e.msg}`;
});
showError(messages);
} else if (typeof data.detail === 'string') {
showError([data.detail]);
} else {
showError(['Unknown error']);
}
}
} catch (err) {
showError(['Connection error: ' + err.message]);
}
});
function showError(messages){ //Добавление их на form со стилями
let errorElem = document.getElementById('formError');
let container = document.getElementById('glass-container');
if (!errorElem){
errorElem = document.createElement('div');
errorElem.style.transition="3s";
errorElem.id = 'formError';
errorElem.style.color = 'red';
errorElem.style.marginTop = '20px';
errorElem.style.fontSize = '14px';
errorElem.style.fontWeight = '100';
errorElem.style.marginBottom = '20px';
errorElem.style.lineHeight="120%";
errorElem.style.height = 'auto';
const form = document.getElementById('loginForm');
form.insertAdjacentElement('afterend', errorElem);
};
errorElem.innerHTML = '';
messages.forEach(msg => {
const li = document.createElement('li');
li.style.listStyleType="none";
li.textContent = msg;
errorElem.appendChild(li);
});
}