waitwaitwait i need a restore

This commit is contained in:
Lain Iwakura 2025-06-16 02:27:51 +03:00
parent 01c562f5b6
commit 01ee11e3e4
No known key found for this signature in database
GPG Key ID: C7C18257F2ADC6F8
6 changed files with 325 additions and 138 deletions

4
README
View File

@ -16,10 +16,10 @@ Installation:
USE messenger; USE messenger;
# For new installation: # For new installation:
source sql/create.sql source main/create.sql
# For updating existing installation: # For updating existing installation:
source sql/migrate.sql source main/migrate.sql
# Create user with password # Create user with password
CREATE USER 'messenger'@'localhost' IDENTIFIED BY 'your_secure_password'; CREATE USER 'messenger'@'localhost' IDENTIFIED BY 'your_secure_password';

29
main/create.sql Normal file
View File

@ -0,0 +1,29 @@
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
signature TEXT,
is_encrypted BOOLEAN DEFAULT FALSE,
INDEX idx_created_at (created_at)
);
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
pgp_key TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_moderator TINYINT(1) NOT NULL DEFAULT 0,
login_attempts INT NOT NULL DEFAULT 0,
last_attempt TIMESTAMP NULL,
is_blocked TINYINT(1) NOT NULL DEFAULT 0,
block_reason TEXT,
INDEX idx_username (username)
);
CREATE TABLE registrations (
id INT AUTO_INCREMENT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_created_at (created_at)
);

81
main/db.sql Normal file
View File

@ -0,0 +1,81 @@
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
signature TEXT,
is_encrypted BOOLEAN DEFAULT FALSE,
INDEX idx_created_at (created_at)
);
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
pgp_key TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_moderator TINYINT(1) NOT NULL DEFAULT 0,
login_attempts INT NOT NULL DEFAULT 0,
last_attempt TIMESTAMP NULL,
is_blocked TINYINT(1) NOT NULL DEFAULT 0,
block_reason TEXT,
INDEX idx_username (username)
);
CREATE TABLE registrations (
id INT AUTO_INCREMENT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_created_at (created_at)
);
DELIMITER //
CREATE OR REPLACE PROCEDURE migrate_if_needed()
BEGIN
IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = 'messages') THEN
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
signature TEXT,
is_encrypted BOOLEAN DEFAULT FALSE,
INDEX idx_created_at (created_at)
);
END IF;
IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = 'users') THEN
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
pgp_key TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_moderator TINYINT(1) NOT NULL DEFAULT 0,
login_attempts INT NOT NULL DEFAULT 0,
last_attempt TIMESTAMP NULL,
is_blocked TINYINT(1) NOT NULL DEFAULT 0,
block_reason TEXT,
INDEX idx_username (username)
);
END IF;
IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = 'registrations') THEN
CREATE TABLE registrations (
id INT AUTO_INCREMENT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_created_at (created_at)
);
END IF;
IF EXISTS (
SELECT * FROM information_schema.columns
WHERE table_name = 'registrations' AND column_name = 'ip'
) THEN
DROP INDEX IF EXISTS idx_ip_created ON registrations;
ALTER TABLE registrations DROP COLUMN ip;
END IF;
END //
DELIMITER ;
CALL migrate_if_needed();
DROP PROCEDURE IF EXISTS migrate_if_needed;

View File

@ -1,88 +1,124 @@
<?php <?php
require_once 'config.php'; ob_start();
ini_set('session.cookie_httponly', 1);
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();
if ($_SERVER['REQUEST_METHOD'] === 'POST') { $debug = [];
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
try { try {
$pdo = new PDO( $config = require 'config.php';
"mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4", $debug[] = "Config loaded";
$config['db_user'],
$config['db_pass'], $db = new PDO(
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] "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());
}
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?"); $error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$debug[] = "Login attempt for: " . $username;
if ($username && $password) {
try {
$stmt = $db->prepare('SELECT id, password, is_blocked, login_attempts, last_attempt FROM users WHERE username = ?');
$stmt->execute([$username]); $stmt->execute([$username]);
$user = $stmt->fetch(); $user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) { $debug[] = "User found: " . ($user ? 'yes' : 'no');
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) {
$stmt = $pdo->prepare("UPDATE users SET login_attempts = login_attempts + 1, last_attempt = CURRENT_TIMESTAMP WHERE id = ?"); if ($user['is_blocked']) {
$error = 'Account is blocked';
$debug[] = "Account blocked";
} else if ($user['login_attempts'] >= 5 && strtotime($user['last_attempt']) > strtotime('-15 minutes')) {
$error = 'Too many login attempts';
$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'];
if ($user['login_attempts'] >= 4) { $_SESSION['username'] = $username;
$stmt = $pdo->prepare("UPDATE users SET is_blocked = 1, block_reason = 'Превышено количество попыток входа' WHERE id = ?"); $debug[] = "Login successful";
$stmt->execute([$user['id']]); header('Location: index.php');
$error = "Аккаунт заблокирован из-за превышения количества попыток входа"; exit;
} else { } else {
$error = "Неверный пароль"; $stmt = $db->prepare('UPDATE users SET login_attempts = login_attempts + 1, last_attempt = NOW() WHERE id = ?');
$stmt->execute([$user['id']]);
$error = 'Invalid password';
$debug[] = "Invalid password";
} }
} else { } else {
$error = "Пользователь не найден"; $error = 'User not found';
} $debug[] = "User not found";
} }
} catch (PDOException $e) { } catch (PDOException $e) {
$error = "Ошибка сервера"; $error = 'Server error';
$debug[] = "SQL Error: " . $e->getMessage();
$debug[] = "SQL State: " . $e->getCode();
}
} }
} }
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru"> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text0Nly - Login</title>
<title>Вход</title> <style>
<link rel="stylesheet" href="style.css"> body { font-family: Arial, sans-serif; max-width: 400px; margin: 20px auto; padding: 20px; }
.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>
<div class="container"> <h2>Login</h2>
<h1>Вход</h1> <?php if ($error): ?>
<?php if (isset($error)): ?> <div class="error"><?= htmlspecialchars($error) ?></div>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?> <?php endif; ?>
<?php if (isset($success)): ?> <?php if ($success): ?>
<div class="success"><?php echo $success; ?></div> <div class="success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?> <?php endif; ?>
<form method="POST" action="">
<form method="post">
<div class="form-group"> <div class="form-group">
<label for="username">Имя пользователя:</label> <input type="text" name="username" placeholder="Username" required>
<input type="text" id="username" name="username" required>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="password">Пароль:</label> <input type="password" name="password" placeholder="Password" required>
<input type="password" id="password" name="password" required>
</div> </div>
<button type="submit">Войти</button> <button type="submit">Login</button>
</form> </form>
<p>Нет аккаунта? <a href="register.php">Зарегистрироваться</a></p> <p><a href="register.php">Register</a> | <a href="index.php">Back to chat</a></p>
<?php if (!empty($debug)): ?>
<div class="debug">
<strong>Debug info:</strong><br>
<?php foreach ($debug as $line): ?>
<?= htmlspecialchars($line) ?><br>
<?php endforeach; ?>
</div> </div>
<?php endif; ?>
</body> </body>
</html> </html>
<?php ob_end_flush(); ?>

24
main/migrate.sql Normal file
View File

@ -0,0 +1,24 @@
DELIMITER //
CREATE OR REPLACE PROCEDURE migrate_if_needed()
BEGIN
IF EXISTS (
SELECT * FROM information_schema.columns
WHERE table_name = 'registrations' AND column_name = 'ip'
) THEN
DROP INDEX IF EXISTS idx_ip_created ON registrations;
ALTER TABLE registrations DROP COLUMN ip;
END IF;
IF NOT EXISTS (
SELECT * FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'is_blocked'
) THEN
ALTER TABLE users
ADD COLUMN is_blocked TINYINT(1) NOT NULL DEFAULT 0,
ADD COLUMN block_reason TEXT;
END IF;
END //
DELIMITER ;
CALL migrate_if_needed();
DROP PROCEDURE IF EXISTS migrate_if_needed;

View File

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