Files
minicrm/public/auth.js
2026-02-13 14:02:21 +05:00

165 lines
5.5 KiB
JavaScript

// 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;
// 👇 СОЗДАЕМ НАВИГАЦИЮ ПОСЛЕ УСТАНОВКИ ПОЛЬЗОВАТЕЛЯ 👇
if (typeof createNavigation === 'function') {
console.log('🔄 Создание навигации для пользователя:', currentUser.role);
createNavigation();
}
document.getElementById('tasks-controls').style.display = 'block';
const showDeletedLabel = document.querySelector('.show-deleted-label');
if (showDeletedLabel) {
if (currentUser.role === 'admin') {
showDeletedLabel.style.display = 'flex';
} else {
showDeletedLabel.style.display = 'none';
}
}
loadUsers();
loadTasks();
loadActivityLogs();
showSection('tasks');
loadKanbanTasks();
showingTasksWithoutDate = false;
const btn = document.getElementById('tasks-no-date-btn');
if (btn) btn.classList.remove('active');
}
// Вспомогательная функция для отображения понятного имени роли
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();
} catch (error) {
console.error('Ошибка выхода:', error);
}
}