fdnjhbpfwbz

This commit is contained in:
2026-07-07 10:43:31 +05:00
parent 026d346d31
commit 5d54a7dba8
3 changed files with 77 additions and 4 deletions

73
auth.js
View File

@@ -1,4 +1,5 @@
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
const fetch = require('node-fetch');
class AuthService { class AuthService {
constructor() { constructor() {
@@ -33,13 +34,19 @@ class AuthService {
if (!row) { if (!row) {
const hashedPassword = await bcrypt.hash(userData.password, 10); const hashedPassword = await bcrypt.hash(userData.password, 10);
this.db.prepare( this.db.prepare(
'INSERT INTO users (login, password, name, email, role, auth_type, created_at) VALUES (?, ?, ?, ?, ?, ?, datetime(\'now\'))' "INSERT INTO users (login, password, name, email, role, auth_type, created_at) VALUES (?, ?, ?, ?, ?, ?, datetime('now'))"
).run(userData.login, hashedPassword, userData.name, userData.email || null, userData.role, 'local'); ).run(userData.login, hashedPassword, userData.name, userData.email || null, userData.role, userData.auth_type || 'local');
console.log('Создан пользователь: ' + userData.name); console.log('Создан пользователь: ' + userData.name);
} }
} }
authenticate(login, password) { authenticate(login, password) {
const user = this.authenticateLocal(login, password);
if (user) return user;
return null;
}
authenticateLocal(login, password) {
const user = this.db.prepare("SELECT * FROM users WHERE login = ? AND auth_type = 'local'").get(login); const user = this.db.prepare("SELECT * FROM users WHERE login = ? AND auth_type = 'local'").get(login);
if (!user) return null; if (!user) return null;
const isValid = bcrypt.compareSync(password, user.password); const isValid = bcrypt.compareSync(password, user.password);
@@ -51,6 +58,68 @@ class AuthService {
return null; return null;
} }
async authenticateWithLDAP(login, password) {
if (!this.db) return null;
if (!process.env.LDAP_AUTH_URL) return null;
try {
const response = await fetch(process.env.LDAP_AUTH_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: login, password })
});
if (!response.ok) return null;
const data = await response.json();
if (!data.success) return null;
return this.processLDAPUser(data);
} catch (error) {
console.error('Ошибка LDAP аутентификации:', error.message);
return null;
}
}
processLDAPUser(ldapData) {
if (!this.db) return null;
const { username, full_name, groups } = ldapData;
const userGroups = groups || [];
const allowedGroups = process.env.ALLOWED_GROUPS
? process.env.ALLOWED_GROUPS.split(',').map(g => g.trim())
: [];
let role = 'teacher';
if (userGroups.some(group => allowedGroups.includes(group))) {
role = 'admin';
}
const existingUser = this.db.prepare("SELECT * FROM users WHERE login = ? AND auth_type = 'ldap'").get(username);
if (existingUser) {
this.db.prepare(
"UPDATE users SET name = ?, email = ?, role = ?, groups = ?, last_login = datetime('now') WHERE id = ?"
).run(full_name || username, username + '@school25.ru', role, JSON.stringify(userGroups), existingUser.id);
const { password, ...userWithoutPassword } = existingUser;
return { ...userWithoutPassword, name: full_name || username, email: username + '@school25.ru', role, groups: JSON.stringify(userGroups) };
} else {
this.db.prepare(
"INSERT INTO users (login, name, email, role, auth_type, groups, created_at, last_login) VALUES (?, ?, ?, ?, 'ldap', ?, datetime('now'), datetime('now'))"
).run(username, full_name || username, username + '@school25.ru', role, JSON.stringify(userGroups));
const newUser = this.db.prepare("SELECT * FROM users WHERE login = ? AND auth_type = 'ldap'").get(username);
if (newUser) {
const { password, ...userWithoutPassword } = newUser;
console.log('Создан LDAP пользователь: ' + (full_name || username));
return userWithoutPassword;
}
}
return null;
}
getUserById(id) { getUserById(id) {
const user = this.db.prepare('SELECT id, login, name, email, role, auth_type, created_at, last_login FROM users WHERE id = ?').get(id); const user = this.db.prepare('SELECT id, login, name, email, role, auth_type, created_at, last_login FROM users WHERE id = ?').get(id);
return user || null; return user || null;

View File

@@ -19,6 +19,7 @@
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"express": "^4.22.2", "express": "^4.22.2",
"express-session": "^1.18.2", "express-session": "^1.18.2",
"node-fetch": "~2.6.7",
"multer": "^2.2.0", "multer": "^2.2.0",
"pdf-parse": "^2.4.5" "pdf-parse": "^2.4.5"
} }

View File

@@ -111,7 +111,7 @@ const requireAuth = (req, res, next) => {
const loginAttempts = new Map(); const loginAttempts = new Map();
app.post('/api/login', (req, res) => { app.post('/api/login', async (req, res) => {
const ip = req.ip || req.connection.remoteAddress; const ip = req.ip || req.connection.remoteAddress;
const now = Date.now(); const now = Date.now();
if (loginAttempts.has(ip)) { if (loginAttempts.has(ip)) {
@@ -134,7 +134,10 @@ app.post('/api/login', (req, res) => {
} }
try { try {
const user = authService.authenticate(login, password); let user = authService.authenticateLocal(login, password);
if (!user) {
user = await authService.authenticateWithLDAP(login, password);
}
if (user) { if (user) {
const sessionUser = { const sessionUser = {
id: user.id, id: user.id,