File: /home/muratemr/theotto.tr/includes/auth.php
<?php
/**
* includes/auth.php
* Oturum yönetimi ve yetkilendirme
*/
declare(strict_types=1);
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/csrf.php';
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
define('SESSION_TIMEOUT', 7200); // 2 saat
// Oturum zaman aşımı kontrolü
if (isset($_SESSION['user_id'])) {
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > SESSION_TIMEOUT) {
session_unset();
session_destroy();
session_start();
} else {
$_SESSION['last_activity'] = time();
}
}
/**
* Kullanıcı giriş yapmış mı?
*/
function is_logged_in(): bool
{
return !empty($_SESSION['user_id']);
}
/**
* Giriş yapmamışsa login'e yönlendir
*/
function require_login(): void
{
if (!is_logged_in()) {
header('Location: /admin/login.php');
exit;
}
}
/**
* Mevcut kullanıcı bilgisini döner
*/
function current_user(): array
{
static $user = null;
if ($user !== null) return $user;
if (!is_logged_in()) return [];
$row = db_row(
'SELECT id, full_name, username, role, is_active FROM users WHERE id = ? LIMIT 1',
[$_SESSION['user_id']]
);
if (!$row || !$row['is_active']) {
session_unset();
session_destroy();
return [];
}
$user = $row;
return $user;
}
/**
* Kullanıcı admin mi?
*/
function is_admin(): bool
{
$u = current_user();
return isset($u['role']) && $u['role'] === 'admin';
}
/**
* Belirli modüle erişim yetkisi var mı?
*/
function has_permission(string $module): bool
{
$u = current_user();
if (empty($u)) return false;
if ($u['role'] === 'admin') return true;
$row = db_row(
'SELECT is_active FROM user_permissions WHERE user_id = ? AND module_key = ? LIMIT 1',
[$u['id'], $module]
);
return $row && (bool)$row['is_active'];
}
/**
* Modül yetkisi yoksa:
* - AJAX isteğinde JSON hata
* - Normal istekte login sayfasına yönlendir
*/
function require_permission(string $module): void
{
require_login();
if (!has_permission($module)) {
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
|| str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json')
|| (strpos($_SERVER['REQUEST_URI'] ?? '', '/api/') !== false);
if ($is_ajax) {
http_response_code(403);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Bu işlem için yetkiniz yok.']);
exit;
}
header('Location: /admin/dashboard.php?err=yetersiz_yetki');
exit;
}
}
/**
* Kullanıcı girişini doğrula ve oturum aç
* @return array ['success'=>bool, 'message'=>string]
*/
function attempt_login(string $username, string $password, string $ip): array
{
// Login log yardımcısı
$log = function (bool $success) use ($username, $ip) {
db_run(
'INSERT INTO login_logs (username, ip_address, success) VALUES (?, ?, ?)',
[$username, $ip, (int)$success]
);
};
$user = db_row(
'SELECT * FROM users WHERE username = ? LIMIT 1',
[$username]
);
if (!$user) {
$log(false);
return ['success' => false, 'message' => 'Kullanıcı adı veya şifre hatalı.'];
}
// Hesap kilitli mi?
if ($user['locked_until'] && new DateTime() < new DateTime($user['locked_until'])) {
$remaining = (new DateTime($user['locked_until']))->diff(new DateTime());
$log(false);
return ['success' => false, 'message' => "Hesabınız kilitlenmiştir. {$remaining->i} dakika {$remaining->s} saniye sonra tekrar deneyin."];
}
// Pasif kullanıcı
if (!$user['is_active']) {
$log(false);
return ['success' => false, 'message' => 'Hesabınız devre dışı bırakılmıştır.'];
}
// Şifre kontrolü
if (!password_verify($password, $user['password_hash'])) {
$attempts = $user['failed_attempts'] + 1;
if ($attempts >= 10) {
$lockedUntil = (new DateTime())->modify('+10 minutes')->format('Y-m-d H:i:s');
db_run(
'UPDATE users SET failed_attempts = ?, locked_until = ? WHERE id = ?',
[$attempts, $lockedUntil, $user['id']]
);
$log(false);
return ['success' => false, 'message' => 'Çok fazla hatalı deneme. Hesabınız 10 dakika kilitlendi.'];
} else {
db_run(
'UPDATE users SET failed_attempts = ? WHERE id = ?',
[$attempts, $user['id']]
);
$left = 10 - $attempts;
$log(false);
return ['success' => false, 'message' => "Şifre hatalı. $left deneme hakkınız kaldı."];
}
}
// Başarılı giriş
db_run(
'UPDATE users SET failed_attempts = 0, locked_until = NULL WHERE id = ?',
[$user['id']]
);
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['full_name'];
$_SESSION['user_role'] = $user['role'];
$_SESSION['last_activity'] = time();
$log(true);
return ['success' => true, 'message' => 'Giriş başarılı.'];
}
/**
* Oturumu kapat
*/
function logout(): void
{
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
}
session_destroy();
}