clean debug

This commit is contained in:
Lain Iwakura 2025-06-16 02:25:29 +03:00
parent 4cccebd793
commit 7e211c7a8b
No known key found for this signature in database
GPG Key ID: C7C18257F2ADC6F8
2 changed files with 136 additions and 188 deletions

View File

@ -1,124 +1,89 @@
<?php <?php
ob_start(); require_once 'config.php';
ini_set('session.cookie_httponly', 1); require_once 'functions.php';
ini_set('session.cookie_secure', 1);
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Content-Security-Policy: default-src \'self\'; style-src \'self\' \'unsafe-inline\';');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
session_start(); session_start();
$debug = [];
try {
$config = require 'config.php';
$debug[] = "Config loaded";
$db = new PDO(
"mysql:host={$config['db']['host']};dbname={$config['db']['name']}",
$config['db']['user'],
$config['db']['pass']
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$debug[] = "Database connected";
} catch (PDOException $e) {
$debug[] = "Database error: " . $e->getMessage();
die("Database connection error: " . $e->getMessage());
}
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $username = $_POST['username'] ?? '';
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING); $password = $_POST['password'] ?? '';
$debug[] = "Login attempt for: " . $username; try {
$pdo = new PDO(
if ($username && $password) { "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
try { $config['db_user'],
$stmt = $db->prepare('SELECT id, password, is_blocked, login_attempts, last_attempt FROM users WHERE username = ?'); $config['db_pass'],
$stmt->execute([$username]); [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
$user = $stmt->fetch(PDO::FETCH_ASSOC); );
$debug[] = "User found: " . ($user ? 'yes' : 'no'); $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
if ($user['is_blocked']) {
$error = "Аккаунт заблокирован: " . htmlspecialchars($user['block_reason']);
} else {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['is_moderator'] = $user['is_moderator'];
$stmt = $pdo->prepare("UPDATE users SET login_attempts = 0, last_attempt = NULL WHERE id = ?");
$stmt->execute([$user['id']]);
header("Location: index.php");
exit;
}
} else {
if ($user) { if ($user) {
if ($user['is_blocked']) { $stmt = $pdo->prepare("UPDATE users SET login_attempts = login_attempts + 1, last_attempt = CURRENT_TIMESTAMP WHERE id = ?");
$error = 'Account is blocked'; $stmt->execute([$user['id']]);
$debug[] = "Account blocked";
} else if ($user['login_attempts'] >= 5 && strtotime($user['last_attempt']) > strtotime('-15 minutes')) { if ($user['login_attempts'] >= 4) {
$error = 'Too many login attempts'; $stmt = $pdo->prepare("UPDATE users SET is_blocked = 1, block_reason = 'Превышено количество попыток входа' WHERE id = ?");
$debug[] = "Too many attempts";
} else if (password_verify($password, $user['password'])) {
$stmt = $db->prepare('UPDATE users SET login_attempts = 0, last_attempt = NOW() WHERE id = ?');
$stmt->execute([$user['id']]); $stmt->execute([$user['id']]);
$_SESSION['user_id'] = $user['id']; $error = "Аккаунт заблокирован из-за превышения количества попыток входа";
$_SESSION['username'] = $username;
$debug[] = "Login successful";
header('Location: index.php');
exit;
} else { } else {
$stmt = $db->prepare('UPDATE users SET login_attempts = login_attempts + 1, last_attempt = NOW() WHERE id = ?'); $error = "Неверный пароль";
$stmt->execute([$user['id']]);
$error = 'Invalid password';
$debug[] = "Invalid password";
} }
} else { } else {
$error = 'User not found'; $error = "Пользователь не найден";
$debug[] = "User not found";
} }
} catch (PDOException $e) {
$error = 'Server error';
$debug[] = "SQL Error: " . $e->getMessage();
$debug[] = "SQL State: " . $e->getCode();
} }
} catch (PDOException $e) {
$error = "Ошибка сервера";
} }
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="ru">
<head> <head>
<meta charset="utf-8"> <meta charset="UTF-8">
<title>Text0Nly - Login</title> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<style> <title>Вход</title>
body { font-family: Arial, sans-serif; max-width: 400px; margin: 20px auto; padding: 20px; } <link rel="stylesheet" href="style.css">
.form-group { margin: 10px 0; }
input { width: 100%; padding: 8px; margin: 5px 0; }
button { width: 100%; padding: 10px; background: #2196F3; color: white; border: none; cursor: pointer; }
.error { color: red; }
.success { color: green; }
.debug { background: #f5f5f5; padding: 10px; margin: 10px 0; font-family: monospace; }
</style>
</head> </head>
<body> <body>
<h2>Login</h2> <div class="container">
<?php if ($error): ?> <h1>Вход</h1>
<div class="error"><?= htmlspecialchars($error) ?></div> <?php if (isset($error)): ?>
<?php endif; ?> <div class="error"><?php echo $error; ?></div>
<?php if ($success): ?> <?php endif; ?>
<div class="success"><?= htmlspecialchars($success) ?></div> <?php if (isset($success)): ?>
<?php endif; ?> <div class="success"><?php echo $success; ?></div>
<?php endif; ?>
<form method="post"> <form method="POST" action="">
<div class="form-group"> <div class="form-group">
<input type="text" name="username" placeholder="Username" required> <label for="username">Имя пользователя:</label>
</div> <input type="text" id="username" name="username" required>
<div class="form-group"> </div>
<input type="password" name="password" placeholder="Password" required> <div class="form-group">
</div> <label for="password">Пароль:</label>
<button type="submit">Login</button> <input type="password" id="password" name="password" required>
</form> </div>
<p><a href="register.php">Register</a> | <a href="index.php">Back to chat</a></p> <button type="submit">Войти</button>
</form>
<?php if (!empty($debug)): ?> <p>Нет аккаунта? <a href="register.php">Зарегистрироваться</a></p>
<div class="debug"> </div>
<strong>Debug info:</strong><br>
<?php foreach ($debug as $line): ?>
<?= htmlspecialchars($line) ?><br>
<?php endforeach; ?>
</div>
<?php endif; ?>
</body> </body>
</html> </html>
<?php ob_end_flush(); ?>

View File

@ -1,100 +1,83 @@
<?php <?php
ob_start(); require_once 'config.php';
ini_set('session.cookie_httponly', 1); require_once 'functions.php';
ini_set('session.cookie_secure', 1);
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Content-Security-Policy: default-src \'self\'; style-src \'self\' \'unsafe-inline\';');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
session_start(); session_start();
$config = require 'config.php';
$db = new PDO(
"mysql:host={$config['db']['host']};dbname={$config['db']['name']}",
$config['db']['user'],
$config['db']['pass']
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $username = $_POST['username'] ?? '';
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING); $password = $_POST['password'] ?? '';
$pgp_key = filter_input(INPUT_POST, 'pgp_key', FILTER_SANITIZE_STRING); $pgp_key = $_POST['pgp_key'] ?? '';
if ($username && $password) { try {
if (strlen($username) > 50 || strlen($password) < 8 || !preg_match('/^[a-zA-Z0-9_]+$/', $username)) { $pdo = new PDO(
$error = 'Invalid data'; "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
} else if (strlen($pgp_key) > 4096) { $config['db_user'],
$error = 'PGP key is too long'; $config['db_pass'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$stmt = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$stmt->execute();
$recent_registrations = $stmt->fetchColumn();
if ($recent_registrations >= 3) {
$error = "Слишком много регистраций за последний час. Попробуйте позже.";
} else { } else {
$stmt = $db->prepare('SELECT COUNT(*) FROM registrations WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)'); $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
$stmt->execute(); $stmt->execute([$username]);
$count = $stmt->fetchColumn(); if ($stmt->fetchColumn() > 0) {
$error = "Пользователь с таким именем уже существует";
if ($count >= 20) {
$error = 'Registration limit exceeded';
} else { } else {
try { $hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $db->prepare('INSERT INTO users (username, password, pgp_key, login_attempts, last_attempt) VALUES (?, ?, ?, 0, NOW())');
$stmt->execute([ $stmt = $pdo->prepare("INSERT INTO users (username, password, pgp_key) VALUES (?, ?, ?)");
$username, $stmt->execute([$username, $hashed_password, $pgp_key]);
password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]),
$pgp_key $stmt = $pdo->prepare("INSERT INTO registrations (created_at) VALUES (NOW())");
]); $stmt->execute();
$stmt = $db->prepare('INSERT INTO registrations () VALUES ()'); $success = "Регистрация успешна! Теперь вы можете войти.";
$stmt->execute();
$success = 'Registration successful';
} catch (PDOException $e) {
$error = 'Username already exists';
}
} }
} }
} catch (PDOException $e) {
$error = "Ошибка сервера";
} }
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="ru">
<head> <head>
<meta charset="utf-8"> <meta charset="UTF-8">
<title>Text0Nly - Registration</title> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<style> <title>Регистрация</title>
body { font-family: Arial, sans-serif; max-width: 400px; margin: 20px auto; padding: 20px; } <link rel="stylesheet" href="style.css">
.form-group { margin: 10px 0; }
input, textarea { width: 100%; padding: 8px; margin: 5px 0; }
textarea { height: 100px; }
button { width: 100%; padding: 10px; background: #2196F3; color: white; border: none; cursor: pointer; }
.error { color: red; }
.success { color: green; }
</style>
</head> </head>
<body> <body>
<h2>Registration</h2> <div class="container">
<?php if ($error): ?> <h1>Регистрация</h1>
<div class="error"><?= htmlspecialchars($error) ?></div> <?php if (isset($error)): ?>
<?php endif; ?> <div class="error"><?php echo $error; ?></div>
<?php if ($success): ?> <?php endif; ?>
<div class="success"><?= htmlspecialchars($success) ?></div> <?php if (isset($success)): ?>
<?php endif; ?> <div class="success"><?php echo $success; ?></div>
<?php endif; ?>
<form method="post"> <form method="POST" action="">
<div class="form-group"> <div class="form-group">
<input type="text" name="username" placeholder="Username" required maxlength="50"> <label for="username">Имя пользователя:</label>
</div> <input type="text" id="username" name="username" required>
<div class="form-group"> </div>
<input type="password" name="password" placeholder="Password (min 8 characters)" required minlength="8"> <div class="form-group">
</div> <label for="password">Пароль:</label>
<div class="form-group"> <input type="password" id="password" name="password" required>
<textarea name="pgp_key" placeholder="PGP key (optional)"></textarea> </div>
</div> <div class="form-group">
<button type="submit">Register</button> <label for="pgp_key">PGP ключ (опционально):</label>
</form> <textarea id="pgp_key" name="pgp_key" rows="5"></textarea>
<p><a href="index.php">Back to chat</a></p> </div>
<button type="submit">Зарегистрироваться</button>
</form>
<p>Уже есть аккаунт? <a href="login.php">Войти</a></p>
</div>
</body> </body>
</html> </html>
<?php ob_end_flush(); ?>