Files
web_work/app/Controllers/AuthController.php
kirill.khorkov d2c15ec37f [MVC] Полная миграция на MVC архитектуру
- Создано ядро MVC: App, Router, Controller, Model, View, Database
- Созданы модели: User, Product, Category, Cart, Order
- Созданы контроллеры: Home, Auth, Product, Cart, Order, Page, Admin
- Созданы layouts и partials для представлений
- Добавлены все views для страниц
- Настроена маршрутизация с чистыми URL
- Обновлена конфигурация Docker и Apache для mod_rewrite
- Добавлена единая точка входа public/index.php
2026-01-03 11:48:14 +03:00

218 lines
6.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Models\User;
/**
* AuthController - контроллер авторизации
*/
class AuthController extends Controller
{
private User $userModel;
public function __construct()
{
$this->userModel = new User();
}
/**
* Форма входа
*/
public function loginForm(): void
{
if ($this->isAuthenticated()) {
$this->redirect('/catalog');
}
$redirect = $this->getQuery('redirect', '/catalog');
$this->view('auth/login', [
'redirect' => $redirect,
'error' => $this->getFlash('error'),
'success' => $this->getFlash('success')
]);
}
/**
* Обработка входа
*/
public function login(): void
{
$email = $this->getPost('email', '');
$password = $this->getPost('password', '');
$redirect = $this->getPost('redirect', '/catalog');
if (empty($email) || empty($password)) {
$this->json([
'success' => false,
'message' => 'Заполните все поля'
]);
return;
}
$user = $this->userModel->authenticate($email, $password);
if (!$user) {
$this->json([
'success' => false,
'message' => 'Неверный email или пароль'
]);
return;
}
// Устанавливаем сессию
$this->setSession($user);
$this->json([
'success' => true,
'redirect' => $redirect
]);
}
/**
* Форма регистрации
*/
public function registerForm(): void
{
if ($this->isAuthenticated()) {
$this->redirect('/catalog');
}
$this->view('auth/register', [
'errors' => $_SESSION['registration_errors'] ?? [],
'old' => $_SESSION['old_data'] ?? [],
'success' => $_SESSION['registration_success'] ?? null
]);
// Очищаем flash данные
unset($_SESSION['registration_errors']);
unset($_SESSION['old_data']);
unset($_SESSION['registration_success']);
}
/**
* Обработка регистрации
*/
public function register(): void
{
$errors = [];
$fullName = trim($this->getPost('fio', ''));
$city = trim($this->getPost('city', ''));
$email = trim($this->getPost('email', ''));
$phone = trim($this->getPost('phone', ''));
$password = $this->getPost('password', '');
$confirmPassword = $this->getPost('confirm-password', '');
$privacy = $this->getPost('privacy');
// Валидация
if (empty($fullName) || strlen($fullName) < 3) {
$errors[] = 'ФИО должно содержать минимум 3 символа';
}
if (empty($city) || strlen($city) < 2) {
$errors[] = 'Введите корректное название города';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Введите корректный email адрес';
}
if (empty($phone)) {
$errors[] = 'Введите номер телефона';
}
if (empty($password) || strlen($password) < 6) {
$errors[] = 'Пароль должен содержать минимум 6 символов';
}
if ($password !== $confirmPassword) {
$errors[] = 'Пароли не совпадают';
}
if (!$privacy) {
$errors[] = 'Необходимо согласие с условиями обработки персональных данных';
}
// Проверяем существование email
if (empty($errors) && $this->userModel->emailExists($email)) {
$errors[] = 'Пользователь с таким email уже существует';
}
if (!empty($errors)) {
$_SESSION['registration_errors'] = $errors;
$_SESSION['old_data'] = [
'fio' => $fullName,
'city' => $city,
'email' => $email,
'phone' => $phone
];
$this->redirect('/register');
return;
}
// Создаем пользователя
try {
$userId = $this->userModel->register([
'email' => $email,
'password' => $password,
'full_name' => $fullName,
'phone' => $phone,
'city' => $city
]);
if (!$userId) {
throw new \Exception('Ошибка при создании пользователя');
}
// Получаем созданного пользователя
$user = $this->userModel->find($userId);
// Устанавливаем сессию
$this->setSession($user);
$_SESSION['registration_success'] = 'Регистрация прошла успешно!';
$this->redirect('/catalog');
} catch (\Exception $e) {
$_SESSION['registration_errors'] = [$e->getMessage()];
$_SESSION['old_data'] = [
'fio' => $fullName,
'city' => $city,
'email' => $email,
'phone' => $phone
];
$this->redirect('/register');
}
}
/**
* Выход из системы
*/
public function logout(): void
{
session_destroy();
session_start();
$this->redirect('/');
}
/**
* Установить сессию пользователя
*/
private function setSession(array $user): void
{
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['full_name'] = $user['full_name'];
$_SESSION['user_phone'] = $user['phone'] ?? '';
$_SESSION['user_city'] = $user['city'] ?? '';
$_SESSION['isLoggedIn'] = true;
$_SESSION['isAdmin'] = (bool) $user['is_admin'];
$_SESSION['login_time'] = time();
}
}