38916-vm/auth.php
Flatlogic Bot fd8a2de90a z
2026-03-01 18:23:38 +00:00

74 lines
2.1 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/db/config.php';
function getCurrentUser() {
if (isset($_SESSION['user_id'])) {
$stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
return $stmt->fetch();
}
return null;
}
function requireAuth() {
$user = getCurrentUser();
if (!$user) {
header('Location: login.php');
exit;
}
if ($user['status'] === 'blocked') {
session_destroy();
die('Ваш аккаунт заблокирован.');
}
return $user;
}
function requireRole($role) {
$user = requireAuth();
if (is_array($role)) {
if (!in_array($user['role'], $role)) {
die('Доступ запрещен.');
}
} else {
if ($user['role'] !== $role) {
die('Доступ запрещен.');
}
}
return $user;
}
function login($username, $password) {
$stmt = db()->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
if ($user['status'] === 'blocked') {
return ['error' => 'Ваш аккаунт заблокирован.'];
}
$_SESSION['user_id'] = $user['id'];
return ['success' => true];
}
return ['error' => 'Неверное имя пользователя или пароль.'];
}
function register($username, $password) {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
try {
$stmt = db()->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
$stmt->execute([$username, $passwordHash]);
return ['success' => true];
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
return ['error' => 'Имя пользователя уже занято.'];
}
return ['error' => 'Ошибка при регистрации.'];
}
}
function logout() {
session_destroy();
header('Location: login.php');
exit;
}