[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
This commit is contained in:
217
app/Controllers/AuthController.php
Normal file
217
app/Controllers/AuthController.php
Normal file
@@ -0,0 +1,217 @@
|
||||
<?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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user