bc/server_modules/auth.js
2025-05-13 04:14:01 +00:00

127 lines
7.2 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.

// /server_modules/auth.js
const bcrypt = require('bcryptjs'); // Для хеширования паролей
const db = require('./db'); // Ваш модуль для работы с базой данных
const SALT_ROUNDS = 10; // Количество раундов для генерации соли bcrypt
/**
* Регистрирует нового пользователя.
* @param {string} username - Имя пользователя.
* @param {string} password - Пароль пользователя.
* @returns {Promise<object>} Объект с результатом: { success: boolean, message: string, userId?: number }
*/
async function registerUser(username, password) {
console.log(`[Auth DEBUG] registerUser called with username: "${username}"`); // 1. Начало функции
if (!username || !password) {
console.warn('[Auth DEBUG] Validation failed: Username or password empty.');
return { success: false, message: 'Имя пользователя и пароль не могут быть пустыми.' };
}
if (password.length < 6) {
console.warn(`[Auth DEBUG] Validation failed for "${username}": Password too short.`);
return { success: false, message: 'Пароль должен содержать не менее 6 символов.' };
}
try {
// Этап A: Проверка существующего пользователя
console.log(`[Auth DEBUG] Stage A: Checking if user "${username}" exists...`);
const [existingUsers] = await db.query('SELECT id FROM users WHERE username = ?', [username]);
console.log(`[Auth DEBUG] Stage A: existingUsers query result length: ${existingUsers.length}`);
if (existingUsers.length > 0) {
console.warn(`[Auth DEBUG] Registration declined for "${username}": Username already taken.`);
return { success: false, message: 'Это имя пользователя уже занято.' };
}
console.log(`[Auth DEBUG] Stage A: Username "${username}" is available.`);
// Этап B: Хеширование пароля
console.log(`[Auth DEBUG] Stage B: Hashing password for user "${username}"...`);
const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
console.log(`[Auth DEBUG] Stage B: Password for "${username}" hashed successfully.`);
// Этап C: Сохранение пользователя в БД
console.log(`[Auth DEBUG] Stage C: Attempting to insert user "${username}" into DB...`);
const [result] = await db.query(
'INSERT INTO users (username, password_hash) VALUES (?, ?)',
[username, hashedPassword]
);
console.log(`[Auth DEBUG] Stage C: DB insert result for "${username}":`, result);
if (result && result.insertId) { // Добавлена проверка на существование result
console.log(`[Auth] Пользователь "${username}" успешно зарегистрирован с ID: ${result.insertId}.`);
return { success: true, message: 'Регистрация прошла успешно!', userId: result.insertId };
} else {
console.error(`[Auth] Ошибка БД при регистрации пользователя "${username}": Запись не была вставлена или insertId отсутствует. Result:`, result);
return { success: false, message: 'Ошибка сервера при регистрации (данные не сохранены). Попробуйте позже.' };
}
} catch (error) {
console.error(`[Auth] КРИТИЧЕСКАЯ ОШИБКА (catch block) при регистрации пользователя "${username}":`, error);
// Логируем более детальную информацию об ошибке, если это ошибка MySQL
if (error.sqlMessage) {
console.error(`[Auth] MySQL Error Message: ${error.sqlMessage}`);
console.error(`[Auth] MySQL Error Code: ${error.code}`);
console.error(`[Auth] MySQL Errno: ${error.errno}`);
}
return { success: false, message: 'Внутренняя ошибка сервера при регистрации.' };
}
}
/**
* Выполняет вход пользователя.
* @param {string} username - Имя пользователя.
* @param {string} password - Пароль пользователя.
* @returns {Promise<object>} Объект с результатом: { success: boolean, message: string, userId?: number, username?: string }
*/
async function loginUser(username, password) {
console.log(`[Auth DEBUG] loginUser called with username: "${username}"`);
if (!username || !password) {
console.warn('[Auth DEBUG] Login validation failed: Username or password empty.');
return { success: false, message: 'Имя пользователя и пароль не могут быть пустыми.' };
}
try {
console.log(`[Auth DEBUG] Searching for user "${username}" in DB...`);
const [users] = await db.query('SELECT id, username, password_hash FROM users WHERE username = ?', [username]);
console.log(`[Auth DEBUG] DB query result for user "${username}" (length): ${users.length}`);
if (users.length === 0) {
console.warn(`[Auth DEBUG] Login failed: User "${username}" not found.`);
return { success: false, message: 'Неверное имя пользователя или пароль.' };
}
const user = users[0];
console.log(`[Auth DEBUG] User "${username}" found. ID: ${user.id}. Comparing password...`);
const passwordMatch = await bcrypt.compare(password, user.password_hash);
console.log(`[Auth DEBUG] Password comparison result for "${username}": ${passwordMatch}`);
if (passwordMatch) {
console.log(`[Auth] Пользователь "${user.username}" (ID: ${user.id}) успешно вошел в систему.`);
return {
success: true,
message: 'Вход выполнен успешно!',
userId: user.id,
username: user.username
};
} else {
console.warn(`[Auth DEBUG] Login failed for user "${user.username}": Incorrect password.`);
return { success: false, message: 'Неверное имя пользователя или пароль.' };
}
} catch (error) {
console.error(`[Auth] КРИТИЧЕСКАЯ ОШИБКА (catch block) при входе пользователя "${username}":`, error);
if (error.sqlMessage) {
console.error(`[Auth] MySQL Error Message: ${error.sqlMessage}`);
console.error(`[Auth] MySQL Error Code: ${error.code}`);
console.error(`[Auth] MySQL Errno: ${error.errno}`);
}
return { success: false, message: 'Внутренняя ошибка сервера при входе.' };
}
}
module.exports = {
registerUser,
loginUser
};