Files
minicrm/public/auth.js
2026-03-19 10:20:55 +05:00

270 lines
8.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.
// auth.js - Аутентификация и авторизация
let currentUser = null;
async function checkAuth() {
try {
const response = await fetch('/api/user');
if (response.ok) {
const data = await response.json();
currentUser = data.user;
showMainInterface();
} else {
showLoginInterface();
}
} catch (error) {
showLoginInterface();
}
}
function showLoginInterface() {
document.getElementById('login-modal').style.display = 'block';
document.querySelector('.container').style.display = 'none';
}
function showMainInterface() {
document.getElementById('login-modal').style.display = 'none';
document.querySelector('.container').style.display = 'block';
let userInfo = `Вы вошли как: ${currentUser.name}`;
if (currentUser.auth_type === 'ldap') {
userInfo += ` (LDAP)`;
}
// Показываем только группы, которые влияют на роль
if (currentUser.groups && currentUser.groups.length > 0) {
// Получаем все группы ролей из конфигурации
const roleGroups = [];
// Администраторы
if (window.ALLOWED_GROUPS) {
roleGroups.push(...window.ALLOWED_GROUPS.split(',').map(g => g.trim()));
}
// Секретари
if (window.SECRETARY_GROUPS) {
roleGroups.push(...window.SECRETARY_GROUPS.split(',').map(g => g.trim()));
}
// Группа помощи
if (window.HELP_GROUPS) {
roleGroups.push(...window.HELP_GROUPS.split(',').map(g => g.trim()));
}
// IT поддержка
if (window.ITHELP_GROUPS) {
roleGroups.push(...window.ITHELP_GROUPS.split(',').map(g => g.trim()));
}
// Заявки
if (window.REQUEST_GROUPS) {
roleGroups.push(...window.REQUEST_GROUPS.split(',').map(g => g.trim()));
}
// Задачи
if (window.TASKS_GROUPS) {
roleGroups.push(...window.TASKS_GROUPS.split(',').map(g => g.trim()));
}
// Фильтруем группы пользователя, оставляя только те, что влияют на роль
const relevantGroups = currentUser.groups.filter(group =>
roleGroups.includes(group)
);
// Также всегда показываем роль пользователя
if (currentUser.role) {
userInfo += ` | Роль: ${getRoleDisplayName(currentUser.role)}`;
}
// Показываем группы только если есть релевантные
if (relevantGroups.length > 0) {
userInfo += ` | Группы ролей: ${relevantGroups.join(', ')}`;
}
}
document.getElementById('current-user').textContent = userInfo;
// 👇 ПЕРЕЗАГРУЗКА ВСЕХ СКРИПТОВ ПОСЛЕ АВТОРИЗАЦИИ 👇
reloadAllScripts();
}
// Функция для перезагрузки всех скриптов
function reloadAllScripts() {
//console.log('🔄 Перезагрузка всех скриптов после авторизации...');
// Список скриптов для перезагрузки (в правильном порядке)
// 'loading-start.js',
// 'document-fields.js',
// 2025.03.11 kalugin66 delete 'openTaskChat2.js',
const scriptsToReload = [
'users.js',
'ui.js',
'signature.js',
'tasks.js',
'kanban.js',
'files.js',
'profile.js',
'time-selector.js',
'openTaskChat.js',
'tasks_files.js',
'navbar.js',
'chat-ui.js',
'loadMyCreatedTasks.js',
'main.js',
'nav-task-actions.js',
'reports.js'
];
// Удаляем существующие скрипты
scriptsToReload.forEach(src => {
const existingScripts = document.querySelectorAll(`script[src="${src}"]`);
existingScripts.forEach(script => script.remove());
});
// Загружаем скрипты последовательно
loadScriptsSequentially(scriptsToReload, 0);
}
function loadScriptsSequentially(scripts, index) {
if (index >= scripts.length) {
////console.log('✅ Все скрипты успешно перезагружены');
// Инициализация после загрузки всех скриптов
setTimeout(() => {
initializeAfterReload();
}, 100);
return;
}
const script = document.createElement('script');
script.src = scripts[index];
script.onload = () => {
// console.log(`✅ Загружен: ${scripts[index]}`);
loadScriptsSequentially(scripts, index + 1);
};
script.onerror = (error) => {
console.error(`❌ Ошибка загрузки ${scripts[index]}:`, error);
loadScriptsSequentially(scripts, index + 1);
};
document.head.appendChild(script);
}
function initializeAfterReload() {
////console.log('🚀 Инициализация интерфейса после перезагрузки...');
// Создаем навигацию
if (typeof createNavigation === 'function') {
createNavigation();
} else {
console.warn('⚠️ createNavigation не найдена, пробуем позже...');
setTimeout(() => {
if (typeof createNavigation === 'function') {
createNavigation();
}
}, 200);
}
// Настраиваем отображение чекбокса удаленных задач
const showDeletedLabel = document.querySelector('.show-deleted-label');
if (showDeletedLabel) {
if (currentUser.role === 'admin') {
showDeletedLabel.style.display = 'flex';
} else {
showDeletedLabel.style.display = 'none';
}
}
// Загружаем данные
if (typeof loadUsers === 'function') {
loadUsers();
}
if (typeof loadTasks === 'function') {
loadTasks();
}
if (typeof loadActivityLogs === 'function') {
loadActivityLogs();
}
if (typeof loadKanbanTasks === 'function') {
loadKanbanTasks();
}
// Показываем секцию задач
if (typeof showSection === 'function') {
showSection('tasks');
}
// Сбрасываем состояние кнопки задач без даты
window.showingTasksWithoutDate = false;
const btn = document.getElementById('tasks-no-date-btn');
if (btn) btn.classList.remove('active');
// Переустанавливаем обработчики событий
if (typeof setupEventListeners === 'function') {
setupEventListeners();
}
}
// Вспомогательная функция для отображения понятного имени роли
function getRoleDisplayName(role) {
const roleNames = {
'admin': 'Администратор',
'secretary': 'Секретарь',
'help': 'Помощь',
'ithelp': 'IT поддержка',
'request': 'Заявки',
'tasks': 'Администрация',
'teacher': 'Учитель'
};
return roleNames[role] || role;
}
async function login(event) {
event.preventDefault();
const login = document.getElementById('login').value;
const password = document.getElementById('password').value;
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ login, password })
});
if (response.ok) {
const data = await response.json();
currentUser = data.user;
showMainInterface();
} else {
const error = await response.json();
alert(error.error || 'Ошибка входа');
}
} catch (error) {
console.error('Ошибка:', error);
alert('Ошибка подключения к серверу');
}
}
async function logout() {
try {
await fetch('/api/logout', { method: 'POST' });
currentUser = null;
showLoginInterface();
// Очищаем интерфейс
document.querySelector('.container').style.display = 'none';
document.querySelectorAll('.section').forEach(section => {
section.classList.remove('active');
});
} catch (error) {
console.error('Ошибка выхода:', error);
}
}