Delete comment
This commit is contained in:
@@ -1,16 +1,10 @@
|
||||
<?php
|
||||
/**
|
||||
* Функции авторизации для AETERNA
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
/**
|
||||
* Авторизация пользователя
|
||||
*/
|
||||
function loginUser(string $email, string $password): array {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
|
||||
try {
|
||||
$stmt = $db->prepare("
|
||||
SELECT user_id, email, password_hash, full_name, phone, city, is_admin, is_active
|
||||
@@ -31,7 +25,6 @@ function loginUser(string $email, string $password): array {
|
||||
return ['success' => false, 'message' => 'Неверный пароль'];
|
||||
}
|
||||
|
||||
// Сохраняем в сессию
|
||||
$_SESSION['user_id'] = $user['user_id'];
|
||||
$_SESSION['user_email'] = $user['email'];
|
||||
$_SESSION['full_name'] = $user['full_name'];
|
||||
@@ -41,7 +34,6 @@ function loginUser(string $email, string $password): array {
|
||||
$_SESSION['isAdmin'] = (bool)$user['is_admin'];
|
||||
$_SESSION['login_time'] = time();
|
||||
|
||||
// Обновляем время последнего входа
|
||||
$updateStmt = $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = ?");
|
||||
$updateStmt->execute([$user['user_id']]);
|
||||
|
||||
@@ -52,43 +44,38 @@ function loginUser(string $email, string $password): array {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрация нового пользователя
|
||||
*/
|
||||
function registerUser(array $data): array {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
|
||||
$email = trim($data['email'] ?? '');
|
||||
$password = $data['password'] ?? '';
|
||||
$fullName = trim($data['full_name'] ?? '');
|
||||
$phone = trim($data['phone'] ?? '');
|
||||
$city = trim($data['city'] ?? '');
|
||||
|
||||
// Валидация
|
||||
|
||||
if (empty($email) || empty($password) || empty($fullName)) {
|
||||
return ['success' => false, 'message' => 'Заполните все обязательные поля'];
|
||||
}
|
||||
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return ['success' => false, 'message' => 'Некорректный email'];
|
||||
}
|
||||
|
||||
|
||||
if (strlen($password) < 6) {
|
||||
return ['success' => false, 'message' => 'Пароль должен содержать минимум 6 символов'];
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
// Проверяем существование пользователя
|
||||
|
||||
$checkStmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
|
||||
$checkStmt->execute([$email]);
|
||||
|
||||
|
||||
if ($checkStmt->fetch()) {
|
||||
return ['success' => false, 'message' => 'Пользователь с таким email уже существует'];
|
||||
}
|
||||
|
||||
// Создаем пользователя
|
||||
|
||||
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
|
||||
|
||||
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO users (email, password_hash, full_name, phone, city, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, TRUE)
|
||||
@@ -96,8 +83,7 @@ function registerUser(array $data): array {
|
||||
");
|
||||
$stmt->execute([$email, $passwordHash, $fullName, $phone, $city]);
|
||||
$userId = $stmt->fetchColumn();
|
||||
|
||||
// Автоматически авторизуем
|
||||
|
||||
$_SESSION['user_id'] = $userId;
|
||||
$_SESSION['user_email'] = $email;
|
||||
$_SESSION['full_name'] = $fullName;
|
||||
@@ -106,20 +92,17 @@ function registerUser(array $data): array {
|
||||
$_SESSION['isLoggedIn'] = true;
|
||||
$_SESSION['isAdmin'] = false;
|
||||
$_SESSION['login_time'] = time();
|
||||
|
||||
|
||||
return ['success' => true, 'user_id' => $userId];
|
||||
|
||||
|
||||
} catch (PDOException $e) {
|
||||
return ['success' => false, 'message' => 'Ошибка базы данных: ' . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выход пользователя
|
||||
*/
|
||||
function logoutUser(): void {
|
||||
$_SESSION = [];
|
||||
|
||||
|
||||
if (ini_get("session.use_cookies")) {
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 42000,
|
||||
@@ -127,22 +110,18 @@ function logoutUser(): void {
|
||||
$params["secure"], $params["httponly"]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка является ли пользователь администратором
|
||||
*/
|
||||
function checkAdminAccess(): bool {
|
||||
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,4 +47,3 @@
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,25 +1,13 @@
|
||||
<?php
|
||||
/**
|
||||
* Общие функции для AETERNA
|
||||
*/
|
||||
|
||||
/**
|
||||
* Проверка авторизации пользователя
|
||||
*/
|
||||
function isLoggedIn(): bool {
|
||||
return isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка прав администратора
|
||||
*/
|
||||
function isAdmin(): bool {
|
||||
return isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Требовать авторизацию - редирект на login если не авторизован
|
||||
*/
|
||||
function requireAuth(string $redirectUrl = 'login.php'): void {
|
||||
if (!isLoggedIn()) {
|
||||
header('Location: ' . $redirectUrl . '?error=auth_required&redirect=' . urlencode($_SERVER['REQUEST_URI']));
|
||||
@@ -27,9 +15,6 @@ function requireAuth(string $redirectUrl = 'login.php'): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Требовать права администратора
|
||||
*/
|
||||
function requireAdmin(string $redirectUrl = 'login.php'): void {
|
||||
if (!isAdmin()) {
|
||||
header('Location: ' . $redirectUrl . '?error=admin_required');
|
||||
@@ -37,14 +22,11 @@ function requireAdmin(string $redirectUrl = 'login.php'): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить текущего пользователя
|
||||
*/
|
||||
function getCurrentUser(): ?array {
|
||||
if (!isLoggedIn()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return [
|
||||
'user_id' => $_SESSION['user_id'] ?? 0,
|
||||
'email' => $_SESSION['user_email'] ?? '',
|
||||
@@ -53,38 +35,23 @@ function getCurrentUser(): ?array {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирование цены
|
||||
*/
|
||||
function formatPrice(float $price): string {
|
||||
return number_format($price, 0, '', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
/**
|
||||
* Безопасный вывод HTML
|
||||
*/
|
||||
function e(string $str): string {
|
||||
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация номера заказа
|
||||
*/
|
||||
function generateOrderNumber(): string {
|
||||
return 'AET-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация SKU для товара
|
||||
*/
|
||||
function generateSKU(string $productName): string {
|
||||
$prefix = strtoupper(substr(preg_replace('/[^a-zA-Z0-9]/', '', transliterate($productName)), 0, 6));
|
||||
return $prefix . '-' . rand(100, 999);
|
||||
}
|
||||
|
||||
/**
|
||||
* Транслитерация кириллицы в латиницу
|
||||
*/
|
||||
function transliterate(string $str): string {
|
||||
$converter = [
|
||||
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd',
|
||||
@@ -105,9 +72,6 @@ function transliterate(string $str): string {
|
||||
return strtr($str, $converter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Создание slug из строки
|
||||
*/
|
||||
function createSlug(string $str): string {
|
||||
$slug = transliterate($str);
|
||||
$slug = strtolower($slug);
|
||||
@@ -116,9 +80,6 @@ function createSlug(string $str): string {
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Показать flash-сообщение
|
||||
*/
|
||||
function setFlashMessage(string $type, string $message): void {
|
||||
$_SESSION['flash_message'] = [
|
||||
'type' => $type,
|
||||
@@ -126,9 +87,6 @@ function setFlashMessage(string $type, string $message): void {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить и удалить flash-сообщение
|
||||
*/
|
||||
function getFlashMessage(): ?array {
|
||||
if (isset($_SESSION['flash_message'])) {
|
||||
$message = $_SESSION['flash_message'];
|
||||
@@ -137,4 +95,3 @@ function getFlashMessage(): ?array {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* Единый header для всех страниц AETERNA
|
||||
* Подключение: require_once 'includes/header.php';
|
||||
*/
|
||||
|
||||
// Запускаем сессию если еще не запущена
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Определяем текущую страницу
|
||||
$currentPage = basename($_SERVER['PHP_SELF'], '.php');
|
||||
|
||||
// Проверяем авторизацию
|
||||
$isLoggedIn = isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
$isAdmin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
$userEmail = $_SESSION['user_email'] ?? '';
|
||||
@@ -29,7 +22,7 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
/* Стили для профиля пользователя */
|
||||
|
||||
.user-profile-dropdown { position: relative; display: inline-block; }
|
||||
.user-profile-toggle { display: flex; align-items: center; gap: 10px; cursor: pointer; padding: 8px 12px; border-radius: 4px; transition: all 0.3s ease; }
|
||||
.user-profile-toggle:hover { background-color: rgba(0, 0, 0, 0.05); }
|
||||
@@ -88,13 +81,12 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<div class="header__icons--top">
|
||||
<?php if ($isLoggedIn): ?>
|
||||
<!-- Иконка корзины -->
|
||||
|
||||
<a href="checkout.php" class="icon cart-icon">
|
||||
<i class="fas fa-shopping-cart"></i>
|
||||
<span class="cart-count" id="cartCount">0</span>
|
||||
</a>
|
||||
|
||||
<!-- Блок профиля -->
|
||||
<div class="user-profile-dropdown">
|
||||
<div class="user-profile-toggle" id="profileToggle">
|
||||
<div class="user-avatar"><?= !empty($userEmail) ? strtoupper(substr($userEmail, 0, 1)) : 'U' ?></div>
|
||||
@@ -151,19 +143,18 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// Профиль пользователя - открытие/закрытие
|
||||
|
||||
$('#profileToggle').click(function(e) {
|
||||
e.stopPropagation();
|
||||
$('#profileMenu').toggle();
|
||||
});
|
||||
|
||||
|
||||
$(document).click(function(e) {
|
||||
if (!$(e.target).closest('.user-profile-dropdown').length) {
|
||||
$('#profileMenu').hide();
|
||||
}
|
||||
});
|
||||
|
||||
// Обновление счетчика корзины
|
||||
<?php if ($isLoggedIn): ?>
|
||||
$.ajax({
|
||||
url: 'api/cart.php?action=count',
|
||||
@@ -180,4 +171,3 @@ $(document).ready(function() {
|
||||
<?php endif; ?>
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user