Makes old code work with the new Log plugin

main
Yasen Pramatarov 2025-04-27 15:55:35 +03:00
parent 457c946946
commit 1e975f7b18
4 changed files with 41 additions and 29 deletions

View File

@ -1,9 +1,12 @@
<?php
use App\Core\NullLogger;
class RateLimiter {
public $db;
private $database;
private $log;
/** @var mixed NullLogger (or PSR-3 logger) or plugin Log */
private $logger;
public $maxAttempts = 5; // Maximum login attempts
public $decayMinutes = 15; // Time window in minutes
public $autoBlacklistThreshold = 10; // Attempts before auto-blacklist
@ -23,12 +26,22 @@ class RateLimiter {
'config' => 10
];
public function __construct($database) {
$this->database = $database; // Store the Database object
/**
* @param mixed $database Database object
* @param mixed $logger Optional NullLogger (or PSR-3 logger) or plugin Log
*/
public function __construct($database, $logger = null) {
$this->database = $database;
$this->db = $database->getConnection();
// Initialize logger via Log wrapper
require_once __DIR__ . '/log.php';
$this->log = new Log($database);
// Initialize logger (plugin Log if present or NullLogger otherwise)
if ($logger !== null) {
$this->logger = $logger;
} else {
global $logObject;
$this->logger = isset($logObject) && is_object($logObject) && method_exists($logObject, 'info')
? $logObject
: new NullLogger();
}
// Initialize database tables
$this->createTablesIfNotExist();
}
@ -219,7 +232,7 @@ class RateLimiter {
if ($this->isIpBlacklisted($ip)) {
$message = "Cannot whitelist {$ip} - IP is currently blacklisted";
if ($userId) {
$this->log->insertLog($userId, "IP Whitelist: {$message}", 'system');
$this->logger->info("IP Whitelist: {$message}", ['user_id' => $userId]);
Feedback::flash('ERROR', 'DEFAULT', $message);
}
return false;
@ -243,14 +256,14 @@ class RateLimiter {
$createdBy,
$description
);
$this->log->insertLog($userId ?? null, $logMessage, 'system');
$this->logger->info($logMessage, ['user_id' => $userId ?? null]);
}
return $result;
} catch (Exception $e) {
if ($userId) {
$this->log->insertLog($userId, "IP Whitelist: Failed to add {$ip}: " . $e->getMessage(), 'system');
$this->logger->error("IP Whitelist: Failed to add {$ip}: " . $e->getMessage(), ['user_id' => $userId]);
Feedback::flash('ERROR', 'DEFAULT', "IP Whitelist: Failed to add {$ip}: " . $e->getMessage());
}
return false;
@ -278,14 +291,14 @@ class RateLimiter {
$removedBy,
$ipDetails['created_by']
);
$this->log->insertLog($userId ?? null, $logMessage, 'system');
$this->logger->info($logMessage, ['user_id' => $userId ?? null]);
}
return $result;
} catch (Exception $e) {
if ($userId) {
$this->log->insertLog($userId, "IP Whitelist: Failed to remove {$ip}: " . $e->getMessage(), 'system');
$this->logger->error("IP Whitelist: Failed to remove {$ip}: " . $e->getMessage(), ['user_id' => $userId]);
Feedback::flash('ERROR', 'DEFAULT', "IP Whitelist: Failed to remove {$ip}: " . $e->getMessage());
}
return false;
@ -298,7 +311,7 @@ class RateLimiter {
if ($this->isIpWhitelisted($ip)) {
$message = "Cannot blacklist {$ip} - IP is currently whitelisted";
if ($userId) {
$this->log->insertLog($userId, "IP Blacklist: {$message}", 'system');
$this->logger->info("IP Blacklist: {$message}", ['user_id' => $userId]);
Feedback::flash('ERROR', 'DEFAULT', $message);
}
return false;
@ -326,13 +339,13 @@ class RateLimiter {
$reason,
$expiryTime ?? 'never'
);
$this->log->insertLog($userId ?? null, $logMessage, 'system');
$this->logger->info($logMessage, ['user_id' => $userId ?? null]);
}
return $result;
} catch (Exception $e) {
if ($userId) {
$this->log->insertLog($userId, "IP Blacklist: Failed to add {$ip}: " . $e->getMessage(), 'system');
$this->logger->error("IP Blacklist: Failed to add {$ip}: " . $e->getMessage(), ['user_id' => $userId]);
Feedback::flash('ERROR', 'DEFAULT', "IP Blacklist: Failed to add {$ip}: " . $e->getMessage());
}
return false;
@ -360,13 +373,13 @@ class RateLimiter {
$ipDetails['created_by'],
$ipDetails['reason']
);
$this->log->insertLog($userId ?? null, $logMessage, 'system');
$this->logger->info($logMessage, ['user_id' => $userId ?? null]);
}
return $result;
} catch (Exception $e) {
if ($userId) {
$this->log->insertLog($userId, "IP Blacklist: Failed to remove {$ip}: " . $e->getMessage(), 'system');
$this->logger->error("IP Blacklist: Failed to remove {$ip}: " . $e->getMessage(), ['user_id' => $userId]);
Feedback::flash('ERROR', 'DEFAULT', "IP Blacklist: Failed to remove {$ip}: " . $e->getMessage());
}
return false;
@ -401,7 +414,7 @@ class RateLimiter {
return true;
} catch (Exception $e) {
$this->log->insertLog(null, "Failed to cleanup expired entries: " . $e->getMessage(), 'system');
$this->logger->error("Failed to cleanup expired entries: " . $e->getMessage());
Feedback::flash('ERROR', 'DEFAULT', "Failed to cleanup expired entries: " . $e->getMessage());
return false;
}

View File

@ -51,7 +51,7 @@ if (!$isWritable) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check if user has permission to edit config
if (!$userObject->hasRight($userId, 'edit config file')) {
$logObject->insertLog($userId, "Unauthorized: User \"$currentUser\" tried to edit config file. IP: $user_IP", 'system');
$logObject->log('error', "Unauthorized: User \"$currentUser\" tried to edit config file. IP: $user_IP", ['user_id' => $userId, 'scope' => 'system']);
if ($isAjax) {
ApiResponse::error('Forbidden: You do not have permission to edit the config file', null, 403);
exit;
@ -73,7 +73,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get raw input
$jsonData = file_get_contents('php://input');
if ($jsonData === false) {
$logObject->insertLog($userId, "Failed to read request data for config update", 'system');
$logObject->log('error', "Failed to read request data for config update", ['user_id' => $userId, 'scope' => 'system']);
ApiResponse::error('Failed to read request data');
exit;
}
@ -118,7 +118,7 @@ if (!$isAjax) {
$userObject->hasRight($userId, 'view config file')) {
include '../app/templates/config.php';
} else {
$logObject->insertLog($userId, "Unauthorized: User \"$currentUser\" tried to access \"config\" page. IP: $user_IP", 'system');
$logObject->log('error', "Unauthorized: User \"$currentUser\" tried to access \"config\" page. IP: $user_IP", ['user_id' => $userId, 'scope' => 'system']);
include '../app/templates/error-unauthorized.php';
}
}

View File

@ -97,7 +97,7 @@ try {
// Process reset request
require_once '../app/classes/passwordReset.php';
$resetHandler = new PasswordReset($db);
$resetHandler = new PasswordReset($db, $config);
$result = $resetHandler->requestReset($email);
// Always show same message whether email exists or not for security
@ -123,7 +123,7 @@ try {
// Handle password reset
try {
require_once '../app/classes/passwordReset.php';
$resetHandler = new PasswordReset($db);
$resetHandler = new PasswordReset($db, $config);
$token = $_GET['token'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
@ -257,7 +257,7 @@ try {
Feedback::flash('ERROR', 'DEFAULT', $e->getMessage());
if (isset($username)) {
$userId = $userObject->getUserId($username)[0]['id'] ?? 0;
$logObject->insertLog($userId, "Login: Failed login attempt for user \"$username\". IP: $user_IP. Reason: {$e->getMessage()}", 'user');
$logObject->log('error', "Login: Failed login attempt for user \"$username\". IP: $user_IP. Reason: {$e->getMessage()}", ['user_id' => $userId, 'scope' => 'user']);
$rateLimiter->attempt($username, $user_IP);
}
}
@ -285,11 +285,10 @@ function handleSuccessfulLogin($userId, $username, $rememberMe, $config, $app_ro
Session::createAuthSession($userId, $username, $rememberMe, $config);
// Log successful login
$logObject->insertLog($userId, "Login: User \"$username\" logged in. IP: $userIP", 'user');
$logObject->log('info', "Login: User \"$username\" logged in. IP: $userIP", ['user_id' => $userId, 'scope' => 'user']);
// Set success message
Feedback::flash('LOGIN', 'LOGIN_SUCCESS');
header('Location: ' . htmlspecialchars($app_root));
// After successful login, redirect to original page if provided in URL param or POST
$redirect = $app_root;

View File

@ -74,27 +74,27 @@ if ($config['registration_enabled'] == true) {
if ($result === true) {
// Get the new user's ID for logging
$userId = $userObject->getUserId($username)[0]['id'];
$logObject->insertLog($userId, "Registration: New user \"$username\" registered successfully. IP: $user_IP", 'user');
$logObject->log('info', "Registration: New user \"$username\" registered successfully. IP: $user_IP", ['user_id' => $userId, 'scope' => 'user']);
Feedback::flash('NOTICE', 'DEFAULT', "Registration successful. You can log in now.");
header('Location: ' . htmlspecialchars($app_root . '?page=login'));
exit();
// registration fail, redirect to login
} else {
$logObject->insertLog(null, "Registration: Failed registration attempt for user \"$username\". IP: $user_IP. Reason: $result", 'system');
$logObject->log('error', "Registration: Failed registration attempt for user \"$username\". IP: $user_IP. Reason: $result", ['user_id' => null, 'scope' => 'system']);
Feedback::flash('ERROR', 'DEFAULT', "Registration failed. $result");
header('Location: ' . htmlspecialchars($app_root . '?page=register'));
exit();
}
} else {
$error = $validator->getFirstError();
$logObject->insertLog(null, "Registration: Failed validation for user \"" . ($username ?? 'unknown') . "\". IP: $user_IP. Reason: $error", 'system');
$logObject->log('error', "Registration: Failed validation for user \"" . ($username ?? 'unknown') . "\". IP: $user_IP. Reason: $error", ['user_id' => null, 'scope' => 'system']);
Feedback::flash('ERROR', 'DEFAULT', $error);
header('Location: ' . htmlspecialchars($app_root . '?page=register'));
exit();
}
}
} catch (Exception $e) {
$logObject->insertLog(null, "Registration: System error. IP: $user_IP. Error: " . $e->getMessage(), 'system');
$logObject->log('error', "Registration: System error. IP: $user_IP. Error: " . $e->getMessage(), ['user_id' => null, 'scope' => 'system']);
Feedback::flash('ERROR', 'DEFAULT', $e->getMessage());
}