79 lines
2.5 KiB
JavaScript
79 lines
2.5 KiB
JavaScript
'use strict';
|
||
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const ldapClient = require('./ldapClient');
|
||
const config = require('./config');
|
||
|
||
const accessPath = path.join(__dirname, '..', 'data', 'zup-access.json');
|
||
|
||
function readAccess() {
|
||
try {
|
||
const parsed = JSON.parse(fs.readFileSync(accessPath, 'utf8'));
|
||
return Array.isArray(parsed) ? parsed : [];
|
||
} catch (err) {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
function writeAccess(items) {
|
||
fs.mkdirSync(path.dirname(accessPath), { recursive: true });
|
||
fs.writeFileSync(accessPath, JSON.stringify(items, null, 2), 'utf8');
|
||
}
|
||
|
||
function list() {
|
||
return readAccess().sort((a, b) => String(a.fio || '').localeCompare(String(b.fio || ''), 'ru'));
|
||
}
|
||
|
||
function has(login) {
|
||
const needle = String(login || '').toLowerCase();
|
||
return readAccess().some((item) => String(item.login).toLowerCase() === needle);
|
||
}
|
||
|
||
async function add(login, addedBy) {
|
||
const value = String(login || '').trim();
|
||
if (!value) {
|
||
const err = new Error('Укажите логин сотрудника');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
const items = readAccess();
|
||
const needle = value.toLowerCase();
|
||
if (items.some((item) => String(item.login).toLowerCase() === needle)) {
|
||
const err = new Error('Этот сотрудник уже имеет доступ к ЗУП');
|
||
err.status = 409;
|
||
throw err;
|
||
}
|
||
let fio = '';
|
||
try {
|
||
const user = await ldapClient.getUser(value);
|
||
fio = user.full_name || '';
|
||
if (isAdminLogin(user.login || value)) {
|
||
const err = new Error('Администратор уже имеет доступ');
|
||
err.status = 400;
|
||
throw err;
|
||
}
|
||
} catch (err) {
|
||
if (err.status === 400) throw err;
|
||
const e = new Error(`Не удалось найти пользователя «${value}» в LDAP: ${err.message}`);
|
||
e.status = 404;
|
||
throw e;
|
||
}
|
||
const item = { login: value, fio, addedBy: String(addedBy || ''), addedAt: Date.now() };
|
||
items.push(item);
|
||
writeAccess(items);
|
||
return item;
|
||
}
|
||
|
||
function isAdminLogin(login) {
|
||
const aliases = new Set(ldapClient.buildBindNames(config.adminLogin).map((n) => n.toLowerCase()));
|
||
aliases.add(String(config.adminLogin || '').split('@')[0].split('\\').pop().toLowerCase());
|
||
return aliases.has(String(login || '').toLowerCase());
|
||
}
|
||
|
||
function remove(login) {
|
||
const needle = String(login || '').toLowerCase();
|
||
writeAccess(readAccess().filter((item) => String(item.login).toLowerCase() !== needle));
|
||
}
|
||
|
||
module.exports = { list, has, add, remove, isAdminLogin, accessPath }; |