front
This commit is contained in:
@@ -1,120 +1,33 @@
|
|||||||
body {
|
body {font-family: system-ui, sans-serif; margin: 0; display: flex; flex-direction: column; min-height: 100vh;}
|
||||||
font-family: system-ui, sans-serif;
|
header {display: flex; align-items: center; justify-content: space-between; background: #333; color: white; padding: 10px 15px; position: relative;}
|
||||||
margin: 0;
|
footer {background: #333; color: white; text-align: center; padding: 10px;}
|
||||||
display: flex;
|
main {flex: 1; padding: 20px; max-width: 1000px; margin: 0 auto;}
|
||||||
flex-direction: column;
|
button {cursor:pointer; border-radius: 8px; border: 1px solid #ccc; background:#e4e4e4; padding: 10px 12px; font-size: 16px;}
|
||||||
min-height: 100vh;
|
button:hover {background: #aa92f8;}
|
||||||
}
|
input {background: #ffffff; padding: 10px 12px; font-size: 15px; border-radius: 8px; border: 1px solid #ccc; transition: border 0.2s, box-shadow 0.2s; width:200px;}
|
||||||
|
input:focus {border-color: #7f57ff; box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2); outline: none;}
|
||||||
header {
|
select{background: #ffffff; padding: 10px 12px; font-size: 15px; border-radius: 8px; border: 1px solid #ccc; transition: border 0.2s, box-shadow 0.2s; width:225px;}
|
||||||
display: flex;
|
select:focus {border-color: #7f57ff; box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2); outline: none;}
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
background: #333;
|
|
||||||
color: white;
|
|
||||||
padding: 10px 15px;
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
footer {
|
|
||||||
background: #333;
|
|
||||||
color: white;
|
|
||||||
text-align: center;
|
|
||||||
padding: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
main {
|
|
||||||
flex: 1;
|
|
||||||
padding: 20px;
|
|
||||||
max-width: 1000px;
|
|
||||||
margin: 0 auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* навигация */
|
/* навигация */
|
||||||
nav ul {
|
nav ul {list-style: none; display: flex; gap: 20px; margin: 0; padding: 0;}
|
||||||
list-style: none;
|
nav a {color: white; text-decoration: none; font-weight: 500;}
|
||||||
display: flex;
|
nav a:hover {text-decoration: underline;}
|
||||||
gap: 20px;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav a {
|
|
||||||
color: white;
|
|
||||||
text-decoration: none;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav a:hover {
|
|
||||||
text-decoration: underline;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* бургер */
|
/* бургер */
|
||||||
.burger {
|
.burger {display: none; flex-direction: column; justify-content: center; gap: 5px; width: 30px; height: 25px; background: none; border: none; cursor: pointer;}
|
||||||
display: none;
|
.burger span {display: block; height: 3px; width: 100%; background: white; border-radius: 2px; transition: 0.3s;}
|
||||||
flex-direction: column;
|
.burger.active span:nth-child(1) {transform: translateY(8px) rotate(45deg);}
|
||||||
justify-content: center;
|
.burger.active span:nth-child(2) {opacity: 0;}
|
||||||
gap: 5px;
|
.burger.active span:nth-child(3) {transform: translateY(-8px) rotate(-45deg);}
|
||||||
width: 30px;
|
|
||||||
height: 25px;
|
|
||||||
background: none;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger span {
|
|
||||||
display: block;
|
|
||||||
height: 3px;
|
|
||||||
width: 100%;
|
|
||||||
background: white;
|
|
||||||
border-radius: 2px;
|
|
||||||
transition: 0.3s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger.active span:nth-child(1) {
|
|
||||||
transform: translateY(8px) rotate(45deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger.active span:nth-child(2) {
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger.active span:nth-child(3) {
|
|
||||||
transform: translateY(-8px) rotate(-45deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* сетка */
|
/* сетка */
|
||||||
.grid-3 {
|
.grid-3 {display: grid; grid-template-columns: 15% 70% 15%; gap: 20px; margin-top: 20px;}
|
||||||
display: grid;
|
.grid-block {background: #f5f5f5; padding: 15px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);}
|
||||||
grid-template-columns: 15% 70% 15%;
|
/* Полупрозрачный фон */
|
||||||
gap: 20px;
|
.overlay {position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 1000;}
|
||||||
margin-top: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.grid-block {
|
/* Окна */
|
||||||
background: #f5f5f5;
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 10px;
|
|
||||||
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
|
|
||||||
}
|
|
||||||
/* Полупрозрачный фон */
|
|
||||||
.overlay {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background: rgba(0,0,0,0.5);
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
z-index: 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Окна */
|
|
||||||
/* Message */
|
/* Message */
|
||||||
.window-popup { width:400px; height:150px; background:#fff; border-radius:10px; display:flex; flex-direction:column; justify-content:center; align-items:center; padding:20px; box-shadow:0 0 10px rgba(0,0,0,0.3); }
|
.window-popup {width:400px; height:150px; background:#fff; border-radius:10px; display:flex; flex-direction:column; justify-content:center; align-items:center; padding:20px; box-shadow:0 0 10px rgba(0,0,0,0.3); }
|
||||||
.window-popup button { margin-top:20px; padding:5px 10px; cursor:pointer; }
|
|
||||||
|
|
||||||
/* Menu */
|
/* Menu */
|
||||||
.window-menu { position:absolute; background:#fff; border-radius:10px; border:1px solid rgba(0,0,0,0.12); box-shadow:0 6px 18px rgba(0,0,0,0.12); min-width:160px; z-index:9999; overflow:hidden; }
|
.window-menu { position:absolute; background:#fff; border-radius:10px; border:1px solid rgba(0,0,0,0.12); box-shadow:0 6px 18px rgba(0,0,0,0.12); min-width:160px; z-index:9999; overflow:hidden; }
|
||||||
@@ -135,39 +48,29 @@ nav a:hover {
|
|||||||
|
|
||||||
/* адаптив */
|
/* адаптив */
|
||||||
@media (max-width: 425px) {
|
@media (max-width: 425px) {
|
||||||
.grid-3 {
|
.grid-3 {grid-template-columns: 1fr;}
|
||||||
grid-template-columns: 1fr;
|
.burger {display: flex;}
|
||||||
}
|
nav {position: absolute; top: 100%; left: 0; width: 100%; background: #222; display: none; flex-direction: column; text-align: center; padding: 10px 0; z-index: 10;}
|
||||||
|
nav.open {display: flex; animation: slideDown 0.3s ease;}
|
||||||
.burger {
|
nav ul {flex-direction: column; gap: 10px;}
|
||||||
display: flex;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav {
|
|
||||||
position: absolute;
|
|
||||||
top: 100%;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
background: #222;
|
|
||||||
display: none;
|
|
||||||
flex-direction: column;
|
|
||||||
text-align: center;
|
|
||||||
padding: 10px 0;
|
|
||||||
z-index: 10;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav.open {
|
|
||||||
display: flex;
|
|
||||||
animation: slideDown 0.3s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav ul {
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes slideDown {
|
@keyframes slideDown {
|
||||||
from { opacity: 0; transform: translateY(-10px); }
|
from { opacity: 0; transform: translateY(-10px); }
|
||||||
to { opacity: 1; transform: translateY(0); }
|
to { opacity: 1; transform: translateY(0); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.ui-overlay {position: fixed; inset: 0; background: rgba(0,0,0,.4); display: flex; align-items: center; justify-content: center;}
|
||||||
|
.ui-alert {background: #fff; padding: 20px; border-radius: 16px; min-width: 300px; font-family: sans-serif; text-align: center;}
|
||||||
|
/* .ui-alert button {margin-top: 20px; border: 1px solid #ccc; padding: 8px 16px; cursor: pointer; border-radius: 8px;} */
|
||||||
|
.ui-popup-list {position: fixed; background: #fff; border: 1px solid #ccc; border-radius: 6px; box-shadow: 0 4px 10px rgba(0,0,0,.15); z-index: 1000;}
|
||||||
|
.ui-popup-list .icon {width: 16px; text-align: center;}
|
||||||
|
.ui-popup-list div {padding: 8px 12px; cursor: pointer; display: flex; align-items: center;}
|
||||||
|
.ui-popup-list div:hover {background: #eee;}
|
||||||
|
.ui-window {background: #fff; padding: 16px; border-radius: 8px; min-width: 300px; font-family: sans-serif; width: 360px;}
|
||||||
|
.ui-window .header {display: flex; justify-content: space-between; font-weight: bold; margin-bottom: 10px; cursor: move; user-select: none;}
|
||||||
|
.ui-window .row {display: flex; justify-content: space-between; padding: 4px 0;}
|
||||||
|
/* Tabs */
|
||||||
|
.tabs {display: flex; border-bottom: 1px solid #ccc; margin-bottom: 10px;}
|
||||||
|
.tab {padding: 6px 12px; cursor: pointer;}
|
||||||
|
.tab.active {border-bottom: 2px solid #0078d7; font-weight: bold;}
|
||||||
|
.tab-content {display: none;}
|
||||||
|
.tab-content.active {display: block;}
|
||||||
|
|||||||
@@ -1,117 +1,126 @@
|
|||||||
/***********************************************************************
|
/***********************************************************************
|
||||||
* ГЛОБАЛЬНОЕ СОСТОЯНИЕ
|
* access-token хранится только в памяти (без localStorage)
|
||||||
**********************************************************************/
|
**********************************************************************/
|
||||||
let accessToken = null; // access-token хранится только в памяти (без localStorage)
|
let accessToken = null;
|
||||||
|
|
||||||
/***********************************************************************
|
/***********************************************************************
|
||||||
* sendRequest УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ДЛЯ ОТПРАВКИ HTTP-ЗАПРОСОВ
|
* user объект в котором хранятся данные пользователя
|
||||||
*
|
|
||||||
* sendRequest(url, options)
|
|
||||||
* - автоматически добавляет Content-Type и credentials
|
|
||||||
* - автоматически превращает body в JSON
|
|
||||||
* - проверяет response.ok
|
|
||||||
* - пробрасывает текст ошибки
|
|
||||||
* - возвращает JSON-ответ
|
|
||||||
**********************************************************************/
|
**********************************************************************/
|
||||||
//let accessToken = ""; // access только в памяти
|
const user = {
|
||||||
|
id: 0,
|
||||||
async function apiProtected(path, options = {}) {
|
name: ""
|
||||||
const send = async () =>
|
|
||||||
fetch(path, {
|
|
||||||
...options,
|
|
||||||
headers: {
|
|
||||||
...(options.headers || {}),
|
|
||||||
Authorization: "Bearer " + accessToken,
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let r = await send();
|
|
||||||
|
|
||||||
if ((r.status === 401)) {
|
|
||||||
// обновляем access
|
|
||||||
const rr = await fetch("/api/users/refresh", {
|
|
||||||
method: "POST",
|
|
||||||
credentials: "include"
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!rr.ok) throw "refresh failed";
|
|
||||||
|
|
||||||
const j = await rr.json();
|
|
||||||
accessToken = j.access_token;
|
|
||||||
|
|
||||||
r = await send();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!r.ok) throw await r.text();
|
|
||||||
return r.json();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/***********************************************************************
|
||||||
async function sendRequest(url, options = {}) {
|
* apiProtected — это удобная функция для защищённых API-запросов,
|
||||||
// Базовые параметры
|
* которая:
|
||||||
|
*
|
||||||
|
* - Подставляет стандартные и пользовательские настройки запроса.
|
||||||
|
* - Добавляет Authorization с токеном.
|
||||||
|
* - Автоматически сериализует JSON-тело.
|
||||||
|
* - Парсит ответ.
|
||||||
|
* - Обрабатывает устаревший токен (401) и повторяет запрос.
|
||||||
|
* - Выбрасывает ошибки для внешнего try...catch.
|
||||||
|
***********************************************************************/
|
||||||
|
async function apiProtected(path, options = {}) {
|
||||||
|
// Базовые настройки
|
||||||
const defaultOptions = {
|
const defaultOptions = {
|
||||||
|
//method: "GET",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
credentials: "include"
|
credentials: "include"
|
||||||
};
|
};
|
||||||
|
|
||||||
// Объединяем настройки
|
// Объединяем настройки
|
||||||
const finalOptions = {
|
const finalOptions = {
|
||||||
...defaultOptions,
|
...defaultOptions,
|
||||||
...options,
|
...options,
|
||||||
headers: { ...defaultOptions.headers, ...(options.headers || {}) }
|
headers: { ...defaultOptions.headers, ...(options.headers || {}) }
|
||||||
};
|
};
|
||||||
|
// Если есть тело и это объект — сериализуем
|
||||||
// Если тело — объект, превращаем в JSON
|
|
||||||
if (finalOptions.body && typeof finalOptions.body === "object") {
|
if (finalOptions.body && typeof finalOptions.body === "object") {
|
||||||
finalOptions.body = JSON.stringify(finalOptions.body);
|
finalOptions.body = JSON.stringify(finalOptions.body);
|
||||||
}
|
}
|
||||||
|
// Вспомогательная функция отправки запроса
|
||||||
let response;
|
const send = async () => {
|
||||||
try {
|
try {
|
||||||
response = await fetch(url, finalOptions);
|
// Добавляем Authorization, если токен есть
|
||||||
} catch (err) {
|
if (accessToken) {
|
||||||
// Сетевые ошибки (сервер не доступен, нет интернета, CORS и т.д.)
|
finalOptions.headers.Authorization = `Bearer ${accessToken}`;
|
||||||
return {
|
}
|
||||||
ok: false,
|
// Отправляем fetch запрос.
|
||||||
status: 0,
|
const res = await fetch(path, finalOptions);
|
||||||
data: err.toString()
|
const text = await res.text();
|
||||||
};
|
let data;
|
||||||
}
|
// Пытаемся распарсить ответ как JSON, если не получается
|
||||||
|
// — возвращаем текст.
|
||||||
// Читаем тело ответа только один раз
|
try {
|
||||||
let text = await response.text();
|
data = JSON.parse(text);
|
||||||
let data;
|
} catch {
|
||||||
try {
|
data = text;
|
||||||
data = JSON.parse(text);
|
}
|
||||||
} catch {
|
return { res, data };
|
||||||
data = text;
|
} catch (err) {
|
||||||
}
|
return { res: null, data: err.toString() };
|
||||||
|
}
|
||||||
return {
|
|
||||||
ok: response.ok,
|
|
||||||
status: response.status,
|
|
||||||
data
|
|
||||||
};
|
};
|
||||||
|
// Первый запрос
|
||||||
|
let { res, data } = await send();
|
||||||
|
// Если 401 — обновляем токен и повторяем
|
||||||
|
if (res && res.status === 401) {
|
||||||
|
await refreshAccess(); // обновляем accessToken
|
||||||
|
({ res, data } = await send()); // повторный запрос
|
||||||
|
}
|
||||||
|
// Если всё равно ошибка — кидаем
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
throw { status: res ? res.status : 0, data };
|
||||||
|
}
|
||||||
|
return data; // возвращаем распарсенный JSON или текст
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/***************************************************************************
|
||||||
|
* refreshAccess() Обнавление токенов:
|
||||||
|
*
|
||||||
|
* - Отправляет POST на /api/users/refresh, используя refresh-токен в cookie.
|
||||||
|
* - Проверяет успешность ответа.
|
||||||
|
* - Сохраняет новый access-токен.
|
||||||
|
* - Декодирует токен, чтобы получить user_id.
|
||||||
|
* - Обновляет глобальные данные о пользователе (id и name).
|
||||||
|
****************************************************************************/
|
||||||
|
async function refreshAccess (){
|
||||||
|
//Отправка запроса на обновление токена
|
||||||
|
const rr = await fetch("/api/auth/refresh", {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "include"
|
||||||
|
});
|
||||||
|
// Проверка ответа
|
||||||
|
if (!rr.ok) throw "refresh failed";
|
||||||
|
// Получение нового токена
|
||||||
|
const j = await rr.json();
|
||||||
|
accessToken = j.access_token;
|
||||||
|
// Декодирование payload JWT
|
||||||
|
const payload = JSON.parse(
|
||||||
|
atob(accessToken.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))
|
||||||
|
);
|
||||||
|
// Обновление данных пользователя
|
||||||
|
user.id = payload.user_id;
|
||||||
|
user.name = (await getUserDataByID(user.id)).name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/********************************************************************************
|
||||||
/********************************************************************
|
* loadMenu функция загрузки блока меню страницы в формате Markdown
|
||||||
* loadMenu функция загрузки блока меню страницы в формате Markdown *
|
********************************************************************************/
|
||||||
********************************************************************/
|
|
||||||
async function loadMenu() {
|
async function loadMenu() {
|
||||||
await loadBlock("menu/top1", "header");
|
await loadBlock("menu/top1", "header");
|
||||||
}
|
}
|
||||||
/********************************************************************
|
/********************************************************************************
|
||||||
* loadPage функция загрузки блока страницы в формате Markdown *
|
* loadPage функция загрузки блока страницы в формате Markdown
|
||||||
********************************************************************/
|
********************************************************************************/
|
||||||
async function loadPage(path) {
|
async function loadPage(path) {
|
||||||
await loadBlock(path, "content");
|
await loadBlock(path, "content");
|
||||||
}
|
}
|
||||||
|
|
||||||
/********************************************************************
|
/*********************************************************************************
|
||||||
* loadMdScript функция загрузки Markdown библиотеки *
|
* loadMdScript функция загрузки Markdown библиотеки
|
||||||
********************************************************************/
|
*********************************************************************************/
|
||||||
function loadMdScript(src) {
|
function loadMdScript(src) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const script = document.createElement('script');
|
const script = document.createElement('script');
|
||||||
@@ -123,24 +132,32 @@ async function loadMenu() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/********************************************************************
|
/**********************************************************************************
|
||||||
* loadBlock функция загрузки блока в формате Markdown *
|
* loadBlock — это универсальная функция для динамического контента:
|
||||||
********************************************************************/
|
*
|
||||||
|
* - Находит контейнер по id.
|
||||||
|
* - Очищает старый контент и связанные скрипты/стили.
|
||||||
|
* - Запрашивает блок через apiProtected.
|
||||||
|
* - Преобразует Markdown в HTML.
|
||||||
|
* - Добавляет CSS и JS динамически.
|
||||||
|
* - Вызывает pageInit() блока, если есть.
|
||||||
|
* - Обрабатывает ошибки.
|
||||||
|
**********************************************************************************/
|
||||||
async function loadBlock(path, block_Name) {
|
async function loadBlock(path, block_Name) {
|
||||||
|
// Получаем контейнер блока
|
||||||
const container = document.getElementById(block_Name);
|
const container = document.getElementById(block_Name);
|
||||||
if (!container) {
|
if (!container) {
|
||||||
//console.warn(`loadBlock: контейнер #${block_Name} не найден — игнорируем`);
|
return;
|
||||||
return;
|
}
|
||||||
}
|
// Обработка пути
|
||||||
path = path.replace(/\/$/, "");
|
path = path.replace(/\/$/, "");
|
||||||
//console.log(path);
|
|
||||||
if (!container) {
|
if (!container) {
|
||||||
console.error(`loadBlock ERROR: element #${block_Name} not found`);
|
console.error(`loadBlock ERROR: element #${block_Name} not found`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const blockName = path === "pages" ? "pages/home" : path;
|
const blockName = path === "pages" ? "pages/home" : path;
|
||||||
//console.log(blockName);
|
|
||||||
try {
|
try {
|
||||||
|
// Очистка контейнера и старых динамических стилей/скриптов
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
document.querySelectorAll('style[data-dynamic], script[data-dynamic]').forEach(el => {
|
document.querySelectorAll('style[data-dynamic], script[data-dynamic]').forEach(el => {
|
||||||
const name = el.getAttribute('data-dynamic');
|
const name = el.getAttribute('data-dynamic');
|
||||||
@@ -148,28 +165,27 @@ if (!container) {
|
|||||||
el.remove();
|
el.remove();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const response = await sendRequest(`/api/block/${blockName}`);
|
// Получение блока с сервера
|
||||||
if (!response.ok) {
|
const response = await apiProtected(`/api/block/${blockName}`, {method: "GET"});
|
||||||
throw new Error(`Failed to load block: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Динамически подгружаем markdown-it, если он ещё не загружен
|
// Динамически подгружаем markdown-it, если он ещё не загружен
|
||||||
if (!window.markdownit) {
|
if (!window.markdownit) {
|
||||||
await loadMdScript('/static/js/markdown-it.min.js');
|
await loadMdScript('/static/js/markdown-it.min.js');
|
||||||
}
|
}
|
||||||
|
const { content: mdContent, css, js } = response;
|
||||||
const { content: mdContent, css, js } = response.data;
|
|
||||||
// Преобразуем markdown в HTML
|
// Преобразуем markdown в HTML
|
||||||
if (mdContent) {
|
if (mdContent) {
|
||||||
const md = window.markdownit({ html: true, linkify: true, typographer: true });
|
const md = window.markdownit({ html: true, linkify: true, typographer: true });
|
||||||
container.innerHTML = md.render(mdContent);
|
container.innerHTML = md.render(mdContent);
|
||||||
|
container?.id?.match(/^loadedBlock_\d+_view$/) && (document.getElementById(container.id.replace('_view', '_html')).innerHTML = mdContent);
|
||||||
}
|
}
|
||||||
|
// Добавление CSS блока
|
||||||
if (css) {
|
if (css) {
|
||||||
const style = document.createElement('style');
|
const style = document.createElement('style');
|
||||||
style.dataset.dynamic = block_Name;
|
style.dataset.dynamic = block_Name;
|
||||||
style.textContent = css;
|
style.textContent = css;
|
||||||
document.head.appendChild(style);
|
document.head.appendChild(style);
|
||||||
}
|
}
|
||||||
|
// Добавление JS блока
|
||||||
if (js) {
|
if (js) {
|
||||||
const script = document.createElement('script');
|
const script = document.createElement('script');
|
||||||
script.dataset.dynamic = block_Name;
|
script.dataset.dynamic = block_Name;
|
||||||
@@ -185,24 +201,35 @@ if (!container) {
|
|||||||
`;
|
`;
|
||||||
document.body.appendChild(script);
|
document.body.appendChild(script);
|
||||||
}
|
}
|
||||||
|
// Обработка ошибок
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
container.innerHTML = "<h2>блок не найден</h2>";
|
container.innerHTML = "<h2>блок не найден</h2>";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SPA-навигация
|
/*****************************************************************************
|
||||||
|
* SPA-навигация
|
||||||
|
*****************************************************************************/
|
||||||
function navigateTo(url, target) {
|
function navigateTo(url, target) {
|
||||||
const clean = url.replace(/^\//, "");
|
const clean = url.replace(/^\//, "");
|
||||||
history.pushState({}, "", "/" + clean);
|
history.pushState({}, "", "/" + clean);
|
||||||
loadBlock("pages/" + clean, target);
|
loadBlock("pages/" + clean, target);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Поддержка кнопки "назад/вперед"
|
/*****************************************************************************
|
||||||
|
* Поддержка кнопки "назад/вперед"
|
||||||
|
*****************************************************************************/
|
||||||
window.addEventListener("popstate", () => {loadBlock(location.pathname);});
|
window.addEventListener("popstate", () => {loadBlock(location.pathname);});
|
||||||
// Обработка истории браузера
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Обработка истории браузера
|
||||||
|
*****************************************************************************/
|
||||||
window.addEventListener("popstate", () => loadBlock(window.location.pathname));
|
window.addEventListener("popstate", () => loadBlock(window.location.pathname));
|
||||||
// Инициализация после загрузки DOM
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Инициализация после загрузки DOM
|
||||||
|
*****************************************************************************/
|
||||||
window.onload = async function () {
|
window.onload = async function () {
|
||||||
let url = window.location.href;
|
let url = window.location.href;
|
||||||
// Убираем слеш в конце, если он есть
|
// Убираем слеш в конце, если он есть
|
||||||
@@ -215,13 +242,14 @@ window.onload = async function () {
|
|||||||
await loadMenu();
|
await loadMenu();
|
||||||
await loadPage("pages"+window.location.pathname);
|
await loadPage("pages"+window.location.pathname);
|
||||||
};
|
};
|
||||||
// Перехватчик ссылок
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Перехватчик ссылок
|
||||||
|
*****************************************************************************/
|
||||||
window.addEventListener("click", (event) => {
|
window.addEventListener("click", (event) => {
|
||||||
const a = event.target.closest("a");
|
const a = event.target.closest("a");
|
||||||
if (!a) return;
|
if (!a) return;
|
||||||
|
|
||||||
const href = a.getAttribute("href");
|
const href = a.getAttribute("href");
|
||||||
|
|
||||||
// игнорируем внешние ссылки и mailto:
|
// игнорируем внешние ссылки и mailto:
|
||||||
if (!href || href.startsWith("http") || href.startsWith("mailto:")) return;
|
if (!href || href.startsWith("http") || href.startsWith("mailto:")) return;
|
||||||
const target = a.dataset.target || "content"; // default = content
|
const target = a.dataset.target || "content"; // default = content
|
||||||
@@ -229,64 +257,305 @@ window.addEventListener("click", (event) => {
|
|||||||
navigateTo(href, target);
|
navigateTo(href, target);
|
||||||
});
|
});
|
||||||
|
|
||||||
//popup
|
|
||||||
function popup(message, afterClose){
|
|
||||||
// Создаём overlay
|
|
||||||
const overlay = document.createElement('div');
|
|
||||||
overlay.className = 'overlay';
|
|
||||||
// Создаём popup
|
|
||||||
const popup = document.createElement('div');
|
|
||||||
popup.className = 'popup';
|
|
||||||
// Добавляем текст
|
|
||||||
const text = document.createElement('div');
|
|
||||||
text.textContent = message;
|
|
||||||
// Добавляем кнопку закрытия
|
|
||||||
const closeBtn = document.createElement('button');
|
|
||||||
closeBtn.textContent = 'Закрыть';
|
|
||||||
closeBtn.addEventListener('click', () => {
|
|
||||||
overlay.remove();
|
|
||||||
if (typeof afterClose === 'function') {
|
|
||||||
afterClose(); // ← ВАША ФУНКЦИЯ ПОСЛЕ ЗАКРЫТИЯ
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
//popupMenu
|
|
||||||
function popupMenu(message, afterClose){
|
|
||||||
// Создаём popupMenu
|
|
||||||
const popupMenu = document.createElement('div');
|
|
||||||
popup.className = 'popup_Menu';
|
|
||||||
// Добавляем текст
|
|
||||||
const text = document.createElement('div');
|
|
||||||
text.textContent = message;
|
|
||||||
// Добавляем кнопку закрытия
|
|
||||||
const closeBtn = document.createElement('button');
|
|
||||||
closeBtn.textContent = 'Закрыть';
|
|
||||||
closeBtn.addEventListener('click', () => {
|
|
||||||
overlay.remove();
|
|
||||||
if (typeof afterClose === 'function') {
|
|
||||||
afterClose(); // ← ВАША ФУНКЦИЯ ПОСЛЕ ЗАКРЫТИЯ
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
popup.appendChild(text);
|
|
||||||
popup.appendChild(closeBtn);
|
|
||||||
overlay.appendChild(popup);
|
|
||||||
document.body.appendChild(overlay);
|
|
||||||
};
|
|
||||||
|
|
||||||
/* ------------------- Переключение видимости пароля ------------------- */
|
|
||||||
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Переключение видимости пароля
|
||||||
|
*****************************************************************************/
|
||||||
document.addEventListener("click", (e) => {
|
document.addEventListener("click", (e) => {
|
||||||
if (!e.target.classList.contains("toggle-pass")) return;
|
if (!e.target.classList.contains("toggle-pass")) return;
|
||||||
//console.log("toggle");
|
console.log("toggle");
|
||||||
const input = e.target.previousElementSibling;
|
const input = e.target.previousElementSibling;
|
||||||
if (!input) return;
|
if (!input) return;
|
||||||
|
|
||||||
if (input.type === "password") {
|
if (input.type === "password") {
|
||||||
input.type = "text";
|
input.type = "text";
|
||||||
e.target.textContent = "🙈";
|
e.target.textContent = "*";//🔓
|
||||||
} else {
|
} else {
|
||||||
input.type = "password";
|
input.type = "password";
|
||||||
e.target.textContent = "👁";
|
e.target.textContent = "A";//🔒
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Получение данных пользователя. Пример использования:
|
||||||
|
* btn.onclick = async function () {
|
||||||
|
* const user = await getUserDataByID(3);
|
||||||
|
* alert(user.name);
|
||||||
|
* };
|
||||||
|
*****************************************************************************/
|
||||||
|
async function getUserDataByID(id) {
|
||||||
|
const data = await apiProtected(
|
||||||
|
`/api/users/getUserData?userid=${encodeURIComponent(id)}&by=id`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
id: data.ID,
|
||||||
|
name: data.Username
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* Функция userLogin:
|
||||||
|
*
|
||||||
|
* - пытается залогиниться через API,
|
||||||
|
* - возвращает accessToken при успехе,
|
||||||
|
* - бросает понятные ошибки (INVALID_CREDENTIALS, LOGIN_FAILED) при неудаче.
|
||||||
|
******************************************************************************/
|
||||||
|
async function userLogin(username, password) {
|
||||||
|
try {
|
||||||
|
// Запрос логина
|
||||||
|
const r = await apiProtected(`/api/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
})
|
||||||
|
});
|
||||||
|
// Проверка access token
|
||||||
|
if (!r?.access_token) {
|
||||||
|
throw new Error("Token not received");
|
||||||
|
}
|
||||||
|
const payload = JSON.parse(
|
||||||
|
atob(r.access_token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))
|
||||||
|
);
|
||||||
|
// Успешный результат
|
||||||
|
user.name = username;
|
||||||
|
user.id = payload.user_id;
|
||||||
|
return {
|
||||||
|
accessToken: r.access_token
|
||||||
|
};
|
||||||
|
// Обработка ошибок (catch)
|
||||||
|
} catch (err) {
|
||||||
|
// err — объект { status, data } из apiProtected
|
||||||
|
if (err?.status === 401) {
|
||||||
|
throw new Error("INVALID_CREDENTIALS");
|
||||||
|
}
|
||||||
|
// Неверный логин / пароль
|
||||||
|
console.error("Login error:", err);
|
||||||
|
throw new Error("LOGIN_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* userLogout — это функция выхода пользователя из системы.
|
||||||
|
******************************************************************************/
|
||||||
|
async function userLogout() {
|
||||||
|
accessToken = "";
|
||||||
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
||||||
|
};
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* userRegister функция которая:
|
||||||
|
*
|
||||||
|
* - регистрирует нового пользователя,
|
||||||
|
* - возвращает ответ сервера при успехе,
|
||||||
|
* - преобразует HTTP-ошибки в бизнес-ошибки, понятные UI.
|
||||||
|
******************************************************************************/
|
||||||
|
async function userRegister(username, password) {
|
||||||
|
try {
|
||||||
|
// Запрос регистрации
|
||||||
|
const data = await apiProtected("/api/auth/register", {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Успешный результат
|
||||||
|
return data;
|
||||||
|
// Перехват ошибок
|
||||||
|
} catch (err) {
|
||||||
|
// Сюда прилетают ошибки, брошенные apiProtected:
|
||||||
|
// Логирование
|
||||||
|
console.error("Register error:", err);
|
||||||
|
// Маппинг HTTP → бизнес-ошибки
|
||||||
|
// Некорректные данные
|
||||||
|
if (err?.status === 400) {
|
||||||
|
throw new Error("BAD_REQUEST");
|
||||||
|
}
|
||||||
|
// Пользователь уже существует
|
||||||
|
if (err?.status === 409) {
|
||||||
|
throw new Error("USER_EXISTS");
|
||||||
|
}
|
||||||
|
// Любая другая ошибка
|
||||||
|
throw new Error("REGISTER_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************************************************************************
|
||||||
|
* Класса UIComponents это статический UI-helper, который:
|
||||||
|
*
|
||||||
|
* - не хранит состояние приложения
|
||||||
|
* - не зависит от фреймворков
|
||||||
|
* - создаёт всплывающие UI-элементы поверх страницы
|
||||||
|
*
|
||||||
|
* Содержит методы:
|
||||||
|
*
|
||||||
|
* - UIComponents.showAlert(...)
|
||||||
|
* - UIComponents.confirm(...)
|
||||||
|
* - UIComponents.showPopupList(...)
|
||||||
|
* - UIComponents.showFileProperties(...)
|
||||||
|
***************************************************************************/
|
||||||
|
class UIComponents {
|
||||||
|
/* ============== 1. АЛЕРТ С ОВЕРЛЕЕМ ============== */
|
||||||
|
/* Показывает модальное окно с кнопкой OK.
|
||||||
|
с затемняющим фоном, который перекрывает страницу*/
|
||||||
|
static showAlert(message) {//, title = 'Сообщение'
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.className = 'ui-overlay';
|
||||||
|
|
||||||
|
const alertBox = document.createElement('div');
|
||||||
|
alertBox.className = 'window-popup';//ui-alert
|
||||||
|
|
||||||
|
alertBox.innerHTML =
|
||||||
|
//<h3>${title}</h3>
|
||||||
|
`<p>${message}</p>
|
||||||
|
<button>OK</button>
|
||||||
|
`;
|
||||||
|
|
||||||
|
alertBox.querySelector('button').onclick = () => {
|
||||||
|
overlay.remove();
|
||||||
|
};
|
||||||
|
|
||||||
|
overlay.appendChild(alertBox);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*==================== 2. confirm ===================== */
|
||||||
|
/* Аналог window.confirm */
|
||||||
|
static confirm(message, title = 'Подтверждение') {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.className = 'ui-overlay';
|
||||||
|
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.className = 'ui-alert';
|
||||||
|
|
||||||
|
box.innerHTML = `
|
||||||
|
<h3>${title}</h3>
|
||||||
|
<p>${message}</p>
|
||||||
|
<div style="display:flex;justify-content:center;gap:12px;margin-top:16px">
|
||||||
|
<button data-yes>Да</button>
|
||||||
|
<button data-no>Нет</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const close = (result) => {
|
||||||
|
overlay.remove();
|
||||||
|
resolve(result);
|
||||||
|
};
|
||||||
|
|
||||||
|
box.querySelector('[data-yes]').onclick = () => close(true);
|
||||||
|
box.querySelector('[data-no]').onclick = () => close(false);
|
||||||
|
|
||||||
|
overlay.appendChild(box);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ========== 3. ПОПАП СПИСОК ========== */
|
||||||
|
static showPopupList(items = {}, x = 0, y = 0) {
|
||||||
|
// Удаляем предыдущий popup
|
||||||
|
if (UIComponents.currentPopup) {
|
||||||
|
UIComponents.currentPopup.remove();
|
||||||
|
UIComponents.currentPopup = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const popup = document.createElement('div');
|
||||||
|
popup.className = 'ui-popup-list';
|
||||||
|
popup.style.left = x + 'px';
|
||||||
|
popup.style.top = y + 'px';
|
||||||
|
|
||||||
|
for (const [name, fn] of Object.entries(items)) {
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.textContent = name;
|
||||||
|
el.onclick = () => {
|
||||||
|
fn(); // вызываем конкретную функцию
|
||||||
|
popup.remove();
|
||||||
|
UIComponents.currentPopup = null;
|
||||||
|
};
|
||||||
|
popup.appendChild(el);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.body.appendChild(popup);
|
||||||
|
UIComponents.currentPopup = popup;
|
||||||
|
|
||||||
|
const removePopup = () => {
|
||||||
|
if (UIComponents.currentPopup) {
|
||||||
|
UIComponents.currentPopup.remove();
|
||||||
|
UIComponents.currentPopup = null;
|
||||||
|
}
|
||||||
|
document.removeEventListener('click', removePopup);
|
||||||
|
};
|
||||||
|
setTimeout(() => document.addEventListener('click', removePopup), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ========== 4. ОКНО "СВОЙСТВА ФАЙЛА" ========== */
|
||||||
|
static showFileProperties(general = {}, details = {}) {
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.className = 'ui-overlay';
|
||||||
|
|
||||||
|
const win = document.createElement('div');
|
||||||
|
win.className = 'ui-window';
|
||||||
|
win.style.position = 'absolute';
|
||||||
|
|
||||||
|
const rows = obj =>
|
||||||
|
Object.entries(obj)
|
||||||
|
.map(([k, v]) => `<div class="row"><span>${k}</span><span>${v}</span></div>`)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
win.innerHTML = `
|
||||||
|
<div class="header">
|
||||||
|
<span>Свойства</span>
|
||||||
|
<button>×</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tabs">
|
||||||
|
<div class="tab active" data-tab="general">Общие</div>
|
||||||
|
<div class="tab" data-tab="details">Подробно</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tab-content active" id="general">${rows(general)}</div>
|
||||||
|
<div class="tab-content" id="details">${rows(details)}</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
win.querySelector('button').onclick = () => overlay.remove();
|
||||||
|
|
||||||
|
/* tabs */
|
||||||
|
win.querySelectorAll('.tab').forEach(tab => {
|
||||||
|
tab.onclick = () => {
|
||||||
|
win.querySelectorAll('.tab, .tab-content')
|
||||||
|
.forEach(e => e.classList.remove('active'));
|
||||||
|
|
||||||
|
tab.classList.add('active');
|
||||||
|
win.querySelector('#' + tab.dataset.tab).classList.add('active');
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/* drag */
|
||||||
|
const header = win.querySelector('.header');
|
||||||
|
header.onmousedown = (e) => {
|
||||||
|
const r = win.getBoundingClientRect();
|
||||||
|
const dx = e.clientX - r.left;
|
||||||
|
const dy = e.clientY - r.top;
|
||||||
|
|
||||||
|
document.onmousemove = e =>
|
||||||
|
Object.assign(win.style, {
|
||||||
|
left: e.clientX - dx + 'px',
|
||||||
|
top: e.clientY - dy + 'px'
|
||||||
|
});
|
||||||
|
|
||||||
|
document.onmouseup = () => document.onmousemove = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
overlay.appendChild(win);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
|
||||||
|
win.style.left = 'calc(50% - 180px)';
|
||||||
|
win.style.top = '20%';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="ru">
|
<html lang="ru">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<base href="/">
|
<base href="/">
|
||||||
<link rel="icon" type="image/png" href="/static/img/favicon.png">
|
<link rel="icon" type="image/png" href="/img/favicon.png">
|
||||||
<title>JWT SPA project</title>
|
<title>TS Web</title>
|
||||||
<link rel="stylesheet" href="/static/css/style.css">
|
<link rel="stylesheet" href="/static/css/style.css">
|
||||||
<script defer src="/static/js/app.js"></script>
|
<script defer src="/static/js/app.js"></script>
|
||||||
</head>
|
</head>
|
||||||
@@ -18,7 +17,7 @@
|
|||||||
<main id="content"></main>
|
<main id="content"></main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>© 2025 Go Markdown SPA</p>
|
<p>© 2025 TriggersSmith web</p>
|
||||||
</footer>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -17,5 +17,6 @@
|
|||||||
<li><a href="/gpt" data-link="true" data-target="content">GPT</a></li>
|
<li><a href="/gpt" data-link="true" data-target="content">GPT</a></li>
|
||||||
<li><a href="/ACL" data-link="true" data-target="content">ACL</a></li>
|
<li><a href="/ACL" data-link="true" data-target="content">ACL</a></li>
|
||||||
<li><a href="/userSlava/popup" data-link="true" data-target="content">Сообщения popup</a></li>
|
<li><a href="/userSlava/popup" data-link="true" data-target="content">Сообщения popup</a></li>
|
||||||
|
<li><a href="/session" data-link="true" data-target="content">Сессия</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ async function UserLogin() {
|
|||||||
const p = document.getElementById("password").value;
|
const p = document.getElementById("password").value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const r = await fetch("/api/users/login", {
|
const r = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -35,7 +35,7 @@ async function UserLogin() {
|
|||||||
|
|
||||||
async function UserLogout() {
|
async function UserLogout() {
|
||||||
try {
|
try {
|
||||||
await fetch("/api/users/logout", { method: "POST", credentials: "include" });
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
||||||
accessToken = "";
|
accessToken = "";
|
||||||
alert("logged out");
|
alert("logged out");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
19
static/blocks/pages/session/content.md
Normal file
19
static/blocks/pages/session/content.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<div class="form1" id="login_block">
|
||||||
|
|
||||||
|
# Вход в систему
|
||||||
|
|
||||||
|
Пожалуйста, введите ваши данные для входа.
|
||||||
|
|
||||||
|
<div class="grid-block">
|
||||||
|
<label for="username">Имя пользователя</label>
|
||||||
|
<input type="text" id="username" name="username" required>
|
||||||
|
<label for="password">Пароль</label>
|
||||||
|
<input type="password" id="password" name="password" required>
|
||||||
|
<button type="submit" id="login_btn">Войти</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form1" id="user_block">
|
||||||
|
<p id="user_info"></p>
|
||||||
|
<button id="logout_btn">Выйти</button>
|
||||||
|
</div>
|
||||||
67
static/blocks/pages/session/script.js
Normal file
67
static/blocks/pages/session/script.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
async function initUser() {
|
||||||
|
try {
|
||||||
|
// Если нет токена, делаем refresh
|
||||||
|
if (!accessToken) {
|
||||||
|
await refreshAccess ();
|
||||||
|
}
|
||||||
|
// Проверяем, получили ли токен
|
||||||
|
if (!accessToken) throw new Error("no token");
|
||||||
|
// выводим имя пользователя
|
||||||
|
user_info.innerHTML = `Вы зашли как: ${user.name}. </br> Ваш ID:${user.id}`;
|
||||||
|
// Показываем блок пользователя
|
||||||
|
showUser()
|
||||||
|
} catch (e) {
|
||||||
|
// Показываем блок логина
|
||||||
|
showLogin()
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function showLogin() {
|
||||||
|
login_block.classList.remove("hiden_block");
|
||||||
|
user_block.classList.add("hiden_block");
|
||||||
|
}
|
||||||
|
|
||||||
|
function showUser() {
|
||||||
|
login_block.classList.add("hiden_block");
|
||||||
|
user_block.classList.remove("hiden_block");
|
||||||
|
}
|
||||||
|
initUser();
|
||||||
|
|
||||||
|
/* --------------------------- Логин ------------------------------- */
|
||||||
|
|
||||||
|
async function onLoginClick() {
|
||||||
|
try {
|
||||||
|
const { accessToken: token } = await userLogin(
|
||||||
|
username.value.trim(),
|
||||||
|
password.value
|
||||||
|
);
|
||||||
|
|
||||||
|
accessToken = token;
|
||||||
|
// UIComponents.showAlert("Вы успешно вошли как "+user.name+".</br> Ваш ID:"+user.id);
|
||||||
|
|
||||||
|
username.value = "";
|
||||||
|
password.value = "";
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
switch (e.message) {
|
||||||
|
case "INVALID_CREDENTIALS":
|
||||||
|
UIComponents.showAlert("Неверный логин или пароль");
|
||||||
|
break;
|
||||||
|
case "BAD_REQUEST":
|
||||||
|
UIComponents.showAlert("Некорректный запрос");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
UIComponents.showAlert("Ошибка при логине");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initUser();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------- Кнопки ------------------- */
|
||||||
|
logout_btn.onclick = async () => {
|
||||||
|
await userLogout(); // вызываем существующую функцию
|
||||||
|
initUser(); // делаем своё
|
||||||
|
};
|
||||||
|
login_btn.onclick = onLoginClick;
|
||||||
78
static/blocks/pages/session/style.css
Normal file
78
static/blocks/pages/session/style.css
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
.hiden_block{
|
||||||
|
display:none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 {
|
||||||
|
background: #fff;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 16px;
|
||||||
|
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
|
||||||
|
/*max-width: 250px;
|
||||||
|
width: 100%;*/
|
||||||
|
width: 250px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 h1 {
|
||||||
|
margin-top: 0;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 26px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 p {
|
||||||
|
text-align: center;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 25px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 .grid-block h3 {
|
||||||
|
margin-bottom: 15px;
|
||||||
|
color: #444;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 label {
|
||||||
|
font-size: 15px;
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 input {
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 15px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
transition: border 0.2s, box-shadow 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 input:focus {
|
||||||
|
border-color: #7f57ff;
|
||||||
|
box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 16px;
|
||||||
|
background:#e4e4e4;
|
||||||
|
/* color: white; */
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
margin-top: 10px;
|
||||||
|
transition: background 0.25s, transform 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 button:hover {
|
||||||
|
background: #aa92f8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 button:active {
|
||||||
|
transform: scale(0.98);
|
||||||
|
}
|
||||||
@@ -12,14 +12,14 @@ btn_prot.onclick = async () => {
|
|||||||
|
|
||||||
async function UserLogout() {
|
async function UserLogout() {
|
||||||
accessToken = "";
|
accessToken = "";
|
||||||
await fetch("/api/users/logout", { method: "POST", credentials: "include" });
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include"});
|
||||||
};
|
};
|
||||||
|
|
||||||
async function UserLogin() {
|
async function UserLogin() {
|
||||||
const u = log_user.value,
|
const u = log_user.value,
|
||||||
p = log_pass.value;
|
p = log_pass.value;
|
||||||
|
|
||||||
const r = await fetch("/api/users/login", {
|
const r = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
|
|||||||
Reference in New Issue
Block a user