remake apis 0.151
All checks were successful
Build Docker / deploy (push) Successful in 44s
Build Docker / build (push) Successful in 34s

This commit is contained in:
2026-03-19 02:41:39 +03:00
parent a13b88bd32
commit 62d58e30cd
4 changed files with 101 additions and 92 deletions

View File

@@ -1,73 +1,64 @@
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
}),
});
document.addEventListener('DOMContentLoaded', () => {
fetch('/api/verify', { credentials: 'include' })
.then(r => { if (r.ok) window.location.href = '/main/'; })
.catch(() => {});
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]);
document.getElementById('loginForm').addEventListener('submit', async function(e) {
e.preventDefault();
const code = document.getElementById('password').value;
try {
const response = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // ← чтобы браузер принял cookie
body: JSON.stringify({ code })
});
const data = await response.json();
if (response.ok) {
window.location.href = '/main/';
} else {
showError(['Unknown error']);
if (Array.isArray(data.detail)) {
const messages = data.detail.map(e => {
const field = e.loc.filter(p => p !== '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]);
}
} catch (err) {
showError(['Connection error: ' + err.message]);
}
});
});
function showError(messages){ //Добавление их на form со стилями
function showError(messages) {
let errorElem = document.getElementById('formError');
let container = document.getElementById('glass-container');
if (!errorElem){
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.style.cssText = `
color: red;
margin-top: 20px;
margin-bottom: 20px;
font-size: 14px;
font-weight: 100;
line-height: 120%;
transition: 3s;
`;
document.getElementById('loginForm').insertAdjacentElement('afterend', errorElem);
}
errorElem.innerHTML = '';
messages.forEach(msg => {
const li = document.createElement('li');
li.style.listStyleType="none";
li.style.listStyleType = 'none';
li.textContent = msg;
errorElem.appendChild(li);
});

View File

@@ -1,29 +1,23 @@
function getToken() {
return localStorage.getItem("token") || sessionStorage.getItem("token");
}
function tokenCheck() {
const token = getToken();
if (!token) {
window.location.href = "https://ru.homyk.space";
}
}
document.addEventListener("DOMContentLoaded", () => {
tokenCheck();
document.getElementById('logoutForm').addEventListener('submit', function(e) {
// Проверка авторизации через cookie
fetch('/api/verify', { credentials: 'include' })
.then(r => { if (!r.ok) window.location.href = '/'; })
.catch(() => { window.location.href = '/'; });
// Logout — удаляем cookie на бэкенде
document.getElementById('logoutForm').addEventListener('submit', async function(e) {
e.preventDefault();
localStorage.removeItem("token");
sessionStorage.removeItem("token");
tokenCheck();
await fetch('/api/logout', {
method: 'POST',
credentials: 'include'
});
window.location.href = '/';
});
document.querySelector(".form-info").addEventListener("submit", async (e) => {
e.preventDefault();
const token = getToken();
const guestData = {
name: document.getElementById('ffname').value || "",
middlename: document.getElementById('fmname').value || "",
@@ -36,15 +30,11 @@ document.addEventListener("DOMContentLoaded", () => {
.join(', ')
};
console.log(guestData);
try {
const response = await fetch('/api/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // ← токен идёт через cookie
body: JSON.stringify(guestData)
});