MicroFrameWork/kernel/modules/secure/controllers/SecureController.php

60 lines
1.7 KiB
PHP
Raw Normal View History

2024-09-24 17:22:09 +03:00
<?php
2024-09-25 14:17:36 +03:00
namespace kernel\modules\secure\controllers;
2024-09-24 17:22:09 +03:00
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
2024-09-25 14:17:36 +03:00
use kernel\modules\secure\models\forms\LoginForm;
2024-09-24 17:22:09 +03:00
use kernel\modules\user\service\UserService;
class SecureController extends AdminController
{
protected UserService $userService;
protected function init(): void
{
parent::init();
2024-09-25 14:17:36 +03:00
// $this->cgView->viewPath = KERNEL_DIR . "/views/secure/";
$this->cgView->viewPath = KERNEL_MODULES_DIR. "/secure/views/";
2024-09-24 17:22:09 +03:00
$this->cgView->layout = "/login.php";
$this->userService = new UserService();
}
public function actionLogin(): void
{
$this->cgView->render('login.php');
}
public function actionAuth(): void
{
$loginForm = new LoginForm();
$loginForm->load($_REQUEST);
if(filter_var($loginForm->getItem("username"), FILTER_VALIDATE_EMAIL)) {
$field = "email";
}
else {
$field = "username";
}
$user = $this->userService->getByField($field, $loginForm->getItem("username"));
if (!$user){
throw new \Exception(message: "User not found");
}
if (password_verify($loginForm->getItem("password"), $user->password_hash)) {
setcookie('user_id', $user->id, time()+60*60*24, '/', $_SERVER['SERVER_NAME'], false);
$this->redirect("/admin");
} else {
$this->redirect("/admin/login");
}
}
#[NoReturn] public function actionLogout(): void
{
unset($_COOKIE['user_id']);
2024-09-25 14:17:36 +03:00
setcookie('user_id', "", -1, '/', $_SERVER['SERVER_NAME'], false);
2024-09-26 14:47:13 +03:00
$this->redirect("/", code: 302);
2024-09-24 17:22:09 +03:00
}
}