склади и инструмент готовы
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
// api.js
|
||||
export async function apiRequest(url, payload = {}, method = 'POST') {
|
||||
const res = await fetch(url, {
|
||||
method: method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`HTTP ${res.status}: ${text}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// auth.js
|
||||
import { setCookie } from '/static/js/cookies.js';
|
||||
import { apiRequest } from '/static/js/api.js';
|
||||
|
||||
const form = document.getElementById('loginForm');
|
||||
const loginInput = document.getElementById('loginInput');
|
||||
const passwordInput = document.getElementById('passwordInput');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const formError = document.getElementById('formError');
|
||||
|
||||
function showError(msg) {
|
||||
formError.hidden = false;
|
||||
formError.textContent = msg;
|
||||
}
|
||||
|
||||
function clearError() {
|
||||
formError.hidden = true;
|
||||
formError.textContent = '';
|
||||
}
|
||||
|
||||
async function getUserEndpoint() {
|
||||
const meta = document.querySelector('meta[name="userAuth-endpoint"]');
|
||||
return meta ? meta.getAttribute('content') : '/user';
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
clearError();
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Входим...';
|
||||
|
||||
const login = loginInput.value.trim();
|
||||
const password = passwordInput.value;
|
||||
|
||||
if (!login || !password) {
|
||||
showError('Введите логин и пароль');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Войти';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = await getUserEndpoint();
|
||||
// Отправляем данные
|
||||
const resp = await apiRequest(url, { login, password });
|
||||
|
||||
// Пример ожидаемого формата:
|
||||
// { "status": "ok" | "error", "user": {...}, "access": {...} }
|
||||
if (!resp || typeof resp !== 'object') {
|
||||
throw new Error('Некорректный ответ от сервера');
|
||||
}
|
||||
|
||||
if (resp.status && (resp.status === 'error' || resp.status === 'fail')) {
|
||||
// Ошибка авторизации
|
||||
showError(resp.message || 'Неправильный логин или пароль');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Войти';
|
||||
return;
|
||||
}
|
||||
|
||||
// Если статус == success / ok / authenticated и есть user + access — считаем успешной
|
||||
const okStatuses = new Set(['ok', 'success', 'authenticated']);
|
||||
const isOk = resp.status && okStatuses.has(String(resp.status).toLowerCase());
|
||||
|
||||
// fallback: если resp.user или resp.access присутствуют — считаем ок
|
||||
const hasData = resp.user && typeof resp.user === 'object' && resp.access && typeof resp.access === 'object';
|
||||
|
||||
if (!isOk && !hasData) {
|
||||
showError('Авторизация не выполнена: пустой ответ');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Войти';
|
||||
return;
|
||||
}
|
||||
await setCookie('toolbox_user', JSON.stringify(resp.user));
|
||||
await setCookie('toolbox_access', JSON.stringify(resp.access));
|
||||
|
||||
window.location.href = '/'; // или другой URL
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showError(err.message || 'Ошибка при авторизации');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Войти';
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { deriveKeyFromSecret, encryptJSON, decryptToJSON } from '/static/js/crypto.js';
|
||||
|
||||
async function getAppSecret() {
|
||||
const meta = document.querySelector('meta[name="app-secret"]');
|
||||
return meta ? meta.getAttribute('content') : null;
|
||||
}
|
||||
|
||||
export async function setCookie(name, value, days = 180) {
|
||||
const appSecret = await getAppSecret();
|
||||
|
||||
let cookieValue;
|
||||
|
||||
if (!appSecret) {
|
||||
console.warn('APP SECRET is missing — cookies will be stored without client-side encryption.');
|
||||
cookieValue = encodeURIComponent(JSON.stringify(value));
|
||||
} else {
|
||||
try {
|
||||
const key = await deriveKeyFromSecret(appSecret);
|
||||
cookieValue = await encryptJSON(key, value);
|
||||
} catch (error) {
|
||||
console.error('Encryption failed:', error);
|
||||
cookieValue = encodeURIComponent(JSON.stringify(value));
|
||||
}
|
||||
}
|
||||
|
||||
const secure = false; // TODO включить после тестов
|
||||
const sameSite = 'Lax';
|
||||
|
||||
const expires = new Date(Date.now() + days * 864e5).toUTCString();
|
||||
|
||||
let cookie = `${encodeURIComponent(name)}=${cookieValue}; expires=${expires}; path=/`;
|
||||
if (secure) cookie += '; Secure';
|
||||
if (sameSite) cookie += `; SameSite=${sameSite}`;
|
||||
|
||||
document.cookie = cookie;
|
||||
}
|
||||
|
||||
export async function getCookie(name) {
|
||||
const cookies = document.cookie ? document.cookie.split('; ') : [];
|
||||
|
||||
for (const c of cookies) {
|
||||
const parts = c.split('=');
|
||||
if (parts.length < 2) continue;
|
||||
|
||||
const cookieName = decodeURIComponent(parts[0]);
|
||||
if (cookieName !== name) continue;
|
||||
|
||||
const cookieValue = parts.slice(1).join('=');
|
||||
const appSecret = await getAppSecret();
|
||||
|
||||
if (appSecret) {
|
||||
try {
|
||||
const key = await deriveKeyFromSecret(appSecret);
|
||||
const decrypted = await decryptToJSON(key, cookieValue);
|
||||
return JSON.parse(decrypted);
|
||||
} catch (error) {
|
||||
console.error('Decryption failed for cookie', name, error);
|
||||
return
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return JSON.parse(decodeURIComponent(cookieValue));
|
||||
} catch (e) {
|
||||
return decodeURIComponent(cookieValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deleteCookie(name) {
|
||||
try {
|
||||
document.cookie = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
export async function deriveKeyFromSecret(secret, salt = 'toolbox_salt_v1') {
|
||||
if (!secret || typeof secret !== 'string') {
|
||||
throw new Error('Invalid secret: must be a non-empty string');
|
||||
}
|
||||
|
||||
const enc = new TextEncoder();
|
||||
const secretKey = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
enc.encode(secret),
|
||||
{ name: 'PBKDF2' },
|
||||
false,
|
||||
['deriveKey']
|
||||
);
|
||||
|
||||
const key = await crypto.subtle.deriveKey(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: enc.encode(salt),
|
||||
iterations: 100000,
|
||||
hash: 'SHA-256'
|
||||
},
|
||||
secretKey,
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
function _randBytes(len = 12) {
|
||||
const b = new Uint8Array(len);
|
||||
crypto.getRandomValues(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
export async function encryptJSON(key, obj) {
|
||||
if (!key || !(key instanceof CryptoKey)) {
|
||||
throw new Error('Valid CryptoKey is required');
|
||||
}
|
||||
|
||||
const enc = new TextEncoder();
|
||||
const iv = _randBytes(12);
|
||||
const plain = enc.encode(JSON.stringify(obj));
|
||||
|
||||
const cipher = await crypto.subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv: iv },
|
||||
key,
|
||||
plain
|
||||
);
|
||||
|
||||
const combined = new Uint8Array(iv.byteLength + cipher.byteLength);
|
||||
combined.set(iv, 0);
|
||||
combined.set(new Uint8Array(cipher), iv.byteLength);
|
||||
|
||||
// Безопасное преобразование в base64
|
||||
const binaryString = Array.from(combined, byte =>
|
||||
String.fromCharCode(byte)).join('');
|
||||
return btoa(binaryString);
|
||||
}
|
||||
|
||||
export async function decryptToJSON(key, b64) {
|
||||
if (!key || !(key instanceof CryptoKey)) {
|
||||
throw new Error('Valid CryptoKey is required');
|
||||
}
|
||||
|
||||
if (!b64 || typeof b64 !== 'string') {
|
||||
throw new Error('Invalid base64 string');
|
||||
}
|
||||
|
||||
try {
|
||||
// Безопасное преобразование из base64
|
||||
const binaryString = atob(b64);
|
||||
const raw = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
raw[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
const iv = raw.slice(0, 12);
|
||||
const cipher = raw.slice(12);
|
||||
|
||||
const plainBuf = await crypto.subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: iv },
|
||||
key,
|
||||
cipher
|
||||
);
|
||||
|
||||
const dec = new TextDecoder();
|
||||
return JSON.parse(dec.decode(plainBuf));
|
||||
} catch (error) {
|
||||
console.error('Decryption error:', error);
|
||||
throw new Error('Failed to decrypt data: ' + error.message);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,177 @@
|
||||
import { getCookie, deleteCookie } from '/static/js/cookies.js';
|
||||
|
||||
class ClientManager {
|
||||
constructor() {
|
||||
this.userData = null;
|
||||
this.accessData = null;
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
// Получаем данные пользователя из cookie
|
||||
this.userData = await getCookie('toolbox_user');
|
||||
this.accessData = await getCookie('toolbox_access');
|
||||
|
||||
|
||||
if (!this.userData || !this.accessData) {
|
||||
console.warn('User data or access data not found in cookie');
|
||||
this.clearUserCookie();
|
||||
window.location.href = '/user/login';
|
||||
}
|
||||
|
||||
// Вставляем данные пользователя в DOM
|
||||
this.renderUserInfo();
|
||||
|
||||
// Инициализируем обработчики
|
||||
this.initLogoutHandler();
|
||||
this.initHoverEffects();
|
||||
this.addAvatarErrorHandler();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error initializing client manager:', error);
|
||||
}
|
||||
}
|
||||
|
||||
renderUserInfo() {
|
||||
if (!this.userData) {
|
||||
// Если нет данных, показываем заглушку
|
||||
this.renderFallbackUser();
|
||||
return;
|
||||
}
|
||||
|
||||
// Находим элементы для обновления
|
||||
const avatar = document.querySelector('.client-avatar');
|
||||
const nameElement = document.querySelector('.client-name');
|
||||
const roleElement = document.querySelector('.client-role');
|
||||
|
||||
// Обновляем аватар
|
||||
if (avatar) {
|
||||
avatar.src = this.userData.photo || 'static/images/users/default.png';
|
||||
avatar.alt = this.userData.username || 'Пользователь';
|
||||
}
|
||||
|
||||
// Обновляем имя
|
||||
if (nameElement) {
|
||||
nameElement.textContent = this.userData.username || 'Неизвестный пользователь';
|
||||
}
|
||||
|
||||
// Обновляем роль
|
||||
if (roleElement) {
|
||||
const role = this.accessData.title || 'Неизвестная роль';
|
||||
roleElement.textContent = role;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
renderFallbackUser() {
|
||||
const userCard = document.querySelector('.client-card');
|
||||
if (userCard) {
|
||||
userCard.innerHTML = `
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<div class="position-relative">
|
||||
<img src="images/users/default.png"
|
||||
alt="Гость"
|
||||
class="client-avatar">
|
||||
<span class="position-absolute bottom-0 end-0 bg-warning border border-2 border-white rounded-circle p-1"></span>
|
||||
</div>
|
||||
<div class="me-3">
|
||||
<h6 class="client-name mb-1">Гость</h6>
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="badge bg-warning bg-opacity-10 text-warning fs-7 px-2 py-1 me-2">
|
||||
<i class="bi bi-exclamation-triangle me-1"></i>
|
||||
Не авторизован
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<a href="/login" class="btn btn-primary btn-sm">
|
||||
<i class="bi bi-box-arrow-in-right me-1"></i>
|
||||
Войти
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
initLogoutHandler() {
|
||||
const logoutBtn = document.getElementById('clientLogoutBtn');
|
||||
if (logoutBtn) {
|
||||
logoutBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
this.handleLogout(logoutBtn);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleLogout(button) {
|
||||
// Анимация нажатия
|
||||
button.style.transform = 'scale(0.95)';
|
||||
|
||||
// Добавляем иконку загрузки
|
||||
const originalContent = button.innerHTML;
|
||||
button.innerHTML = `
|
||||
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
|
||||
Выход...
|
||||
`;
|
||||
button.disabled = true;
|
||||
|
||||
// Очищаем cookie пользователя
|
||||
this.clearUserCookie();
|
||||
|
||||
// Переход на страницу выхода
|
||||
setTimeout(() => {
|
||||
window.location.href = '/user/login';
|
||||
}, 800);
|
||||
}
|
||||
|
||||
clearUserCookie() {
|
||||
try {
|
||||
const cookieNames = ['toolbox_user', 'toolbox_access'];
|
||||
|
||||
cookieNames.forEach(cookieName => {
|
||||
deleteCookie(cookieName);
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Error clearing cookies:', error);
|
||||
}
|
||||
}
|
||||
|
||||
initHoverEffects() {
|
||||
const clientCard = document.querySelector('.client-card');
|
||||
if (clientCard) {
|
||||
clientCard.addEventListener('mouseenter', () => {
|
||||
clientCard.style.transform = 'translateY(-4px) scale(1.01)';
|
||||
});
|
||||
|
||||
clientCard.addEventListener('mouseleave', () => {
|
||||
clientCard.style.transform = 'translateY(0) scale(1)';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
addAvatarErrorHandler() {
|
||||
const avatar = document.querySelector('.client-avatar');
|
||||
if (avatar) {
|
||||
avatar.onerror = () => {
|
||||
avatar.src = 'static/images/users/default.png';
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Инициализация при загрузке документа
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Инициализируем менеджер пользователя
|
||||
window.clientManager = new ClientManager();
|
||||
|
||||
// Добавляем анимацию появления
|
||||
const elements = document.querySelectorAll('.animate-fade-up');
|
||||
elements.forEach((el, index) => {
|
||||
el.style.animationDelay = `${index * 0.1}s`;
|
||||
});
|
||||
});
|
||||
|
||||
// Экспорт для использования в других модулях
|
||||
export { ClientManager };
|
||||
Reference in New Issue
Block a user