refactor users module to domain/controller and release 0.253 update package

This commit is contained in:
2026-02-12 21:44:40 +01:00
parent f5054047fd
commit c1284ef06c
24 changed files with 1452 additions and 453 deletions

View File

@@ -0,0 +1,346 @@
<?php
namespace admin\Controllers;
use Domain\User\UserRepository;
use admin\ViewModels\Forms\FormAction;
use admin\ViewModels\Forms\FormEditViewModel;
use admin\ViewModels\Forms\FormField;
use admin\Support\Forms\FormRequestHandler;
class UsersController
{
private UserRepository $repository;
private FormRequestHandler $formHandler;
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
$this->formHandler = new FormRequestHandler();
}
public function user_delete(): void
{
if ($this->repository->delete((int)\S::get('id'))) {
\S::alert('Uzytkownik zostal usuniety.');
}
header('Location: /admin/users/view_list/');
exit;
}
public function user_save(): void
{
$legacyValues = \S::get('values');
if ($legacyValues) {
$values = json_decode((string)$legacyValues, true);
if (!is_array($values)) {
echo json_encode(['status' => 'error', 'msg' => 'Nieprawidlowe dane formularza.']);
exit;
}
if (!$this->isTwofaEmailValidForEnabled($values['twofa_enabled'] ?? 0, (string)($values['twofa_email'] ?? ''))) {
echo json_encode([
'status' => 'error',
'msg' => 'Jesli wlaczono dwustopniowe uwierzytelnianie (2FA), pole "E-mail do 2FA" jest wymagane.',
]);
exit;
}
$response = $this->repository->save(
(int)($values['id'] ?? 0),
(string)($values['login'] ?? ''),
$values['status'] ?? 0,
(string)($values['password'] ?? ''),
(string)($values['password_re'] ?? ''),
$values['admin'] ?? 1,
$values['twofa_enabled'] ?? 0,
(string)($values['twofa_email'] ?? '')
);
echo json_encode($response);
exit;
}
$userId = (int)\S::get('id');
$user = $this->normalizeUser($this->repository->find($userId));
$viewModel = $this->buildFormViewModel($user);
$result = $this->formHandler->handleSubmit($viewModel, $_POST);
if (!$result['success']) {
$_SESSION['form_errors'][$this->getFormId()] = $result['errors'];
echo json_encode(['success' => false, 'errors' => $result['errors']]);
exit;
}
$data = $result['data'];
$data['id'] = $userId;
$data['admin'] = 1;
if (!$this->isTwofaEmailValidForEnabled($data['twofa_enabled'] ?? 0, (string)($data['twofa_email'] ?? ''))) {
echo json_encode([
'success' => false,
'errors' => [
'twofa_email' => 'Pole "E-mail do 2FA" jest wymagane, gdy wlaczono 2FA.',
],
]);
exit;
}
$duplicateLoginCheck = $this->repository->checkLogin((string)($data['login'] ?? ''), $userId);
if (($duplicateLoginCheck['status'] ?? '') !== 'ok') {
echo json_encode([
'success' => false,
'errors' => ['login' => (string)($duplicateLoginCheck['msg'] ?? 'Podany login jest juz zajety.')],
]);
exit;
}
$response = $this->repository->save(
(int)$data['id'],
(string)($data['login'] ?? ''),
(int)($data['status'] ?? 0),
(string)($data['password'] ?? ''),
(string)($data['password_re'] ?? ''),
1,
(int)($data['twofa_enabled'] ?? 0),
(string)($data['twofa_email'] ?? '')
);
echo json_encode([
'success' => ($response['status'] ?? '') === 'ok',
'message' => (string)($response['msg'] ?? 'Zmiany zostaly zapisane.'),
'errors' => (($response['status'] ?? '') === 'ok') ? [] : ['general' => (string)($response['msg'] ?? 'Wystapil blad.')],
]);
exit;
}
public function user_edit(): string
{
$user = $this->normalizeUser($this->repository->find((int)\S::get('id')));
$validationErrors = $_SESSION['form_errors'][$this->getFormId()] ?? null;
if ($validationErrors) {
unset($_SESSION['form_errors'][$this->getFormId()]);
}
return \Tpl::view('users/user-edit', [
'form' => $this->buildFormViewModel($user, $validationErrors),
]);
}
public function view_list(): string
{
$sortableColumns = ['login', 'status'];
$filterDefinitions = [
[
'key' => 'login',
'label' => 'Login',
'type' => 'text',
],
[
'key' => 'status',
'label' => 'Aktywny',
'type' => 'select',
'options' => [
'' => '- aktywny -',
'1' => 'tak',
'0' => 'nie',
],
],
];
$listRequest = \admin\Support\TableListRequestFactory::fromRequest(
$filterDefinitions,
$sortableColumns,
'login'
);
$sortDir = $listRequest['sortDir'];
if (trim((string)\S::get('sort')) === '') {
$sortDir = 'ASC';
}
$result = $this->repository->listForAdmin(
$listRequest['filters'],
$listRequest['sortColumn'],
$sortDir,
$listRequest['page'],
$listRequest['perPage']
);
$rows = [];
$lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
foreach ($result['items'] as $item) {
$id = (int)$item['id'];
$login = trim((string)($item['login'] ?? ''));
$status = (int)($item['status'] ?? 0);
$rows[] = [
'lp' => $lp++ . '.',
'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
'login' => '<a href="/admin/users/user_edit/id=' . $id . '">' . htmlspecialchars($login, ENT_QUOTES, 'UTF-8') . '</a>',
'_actions' => [
[
'label' => 'Edytuj',
'url' => '/admin/users/user_edit/id=' . $id,
'class' => 'btn btn-xs btn-primary',
],
[
'label' => 'Usun',
'url' => '/admin/users/user_delete/id=' . $id,
'class' => 'btn btn-xs btn-danger',
'confirm' => 'Na pewno chcesz usunac wybranego uzytkownika?',
],
],
];
}
$total = (int)$result['total'];
$totalPages = max(1, (int)ceil($total / $listRequest['perPage']));
$viewModel = new \admin\ViewModels\Common\PaginatedTableViewModel(
[
['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
['key' => 'status', 'sort_key' => 'status', 'label' => 'Aktywny', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
['key' => 'login', 'sort_key' => 'login', 'label' => 'Login', 'sortable' => true, 'raw' => true],
],
$rows,
$listRequest['viewFilters'],
[
'column' => $listRequest['sortColumn'],
'dir' => $sortDir,
],
[
'page' => $listRequest['page'],
'per_page' => $listRequest['perPage'],
'total' => $total,
'total_pages' => $totalPages,
],
array_merge($listRequest['queryFilters'], [
'sort' => $listRequest['sortColumn'],
'dir' => $sortDir,
'per_page' => $listRequest['perPage'],
]),
$listRequest['perPageOptions'],
$sortableColumns,
'/admin/users/view_list/',
'Brak danych w tabeli.',
'/admin/users/user_edit/',
'Dodaj uzytkownika'
);
return \Tpl::view('users/users-list', [
'viewModel' => $viewModel,
]);
}
public function list(): string
{
return $this->view_list();
}
public function login_form(): string
{
return \Tpl::view('site/unlogged-layout');
}
public function twofa(): string
{
return \Tpl::view('site/unlogged', [
'content' => \Tpl::view('users/user-2fa'),
]);
}
private function normalizeUser(?array $user): array
{
return [
'id' => (int)($user['id'] ?? 0),
'login' => (string)($user['login'] ?? ''),
'status' => (int)($user['status'] ?? 1),
'admin' => (int)($user['admin'] ?? 1),
'twofa_enabled' => (int)($user['twofa_enabled'] ?? 0),
'twofa_email' => (string)($user['twofa_email'] ?? ''),
];
}
private function buildFormViewModel(array $user, ?array $errors = null): FormEditViewModel
{
$userId = (int)($user['id'] ?? 0);
$isNew = $userId <= 0;
$data = [
'id' => $userId,
'login' => (string)($user['login'] ?? ''),
'status' => (int)($user['status'] ?? 1),
'twofa_enabled' => (int)($user['twofa_enabled'] ?? 0),
'twofa_email' => (string)($user['twofa_email'] ?? ''),
'password' => '',
'password_re' => '',
];
$fields = [
FormField::text('login', [
'label' => 'Login',
'required' => true,
]),
FormField::switch('status', [
'label' => 'Aktywny',
]),
FormField::switch('twofa_enabled', [
'label' => 'Dwustopniowe uwierzytelnianie (2FA)',
]),
FormField::email('twofa_email', [
'label' => 'E-mail do 2FA',
]),
FormField::password('password', [
'label' => 'Haslo',
'required' => $isNew,
'attributes' => ['minlength' => 5],
]),
FormField::password('password_re', [
'label' => 'Haslo - powtorz',
'required' => $isNew,
'attributes' => ['minlength' => 5],
]),
];
$actionUrl = '/admin/users/user_save/' . ($isNew ? '' : ('id=' . $userId));
$actions = [
FormAction::save($actionUrl, '/admin/users/view_list/'),
FormAction::cancel('/admin/users/view_list/'),
];
return new FormEditViewModel(
$this->getFormId(),
$isNew ? 'Nowy uzytkownik' : 'Edycja uzytkownika',
$data,
$fields,
[],
$actions,
'POST',
$actionUrl,
'/admin/users/view_list/',
true,
[
'id' => $userId,
'admin' => 1,
],
null,
$errors
);
}
private function getFormId(): string
{
return 'users-edit';
}
private function isTwofaEmailValidForEnabled($twofaEnabled, string $twofaEmail): bool
{
$enabled = ($twofaEnabled === 'on' || $twofaEnabled === 1 || $twofaEnabled === '1' || $twofaEnabled === true);
if (!$enabled) {
return true;
}
return trim($twofaEmail) !== '';
}
}

View File

@@ -34,9 +34,12 @@ class Site
public static function special_actions()
{
global $mdb;
$sa = \S::get('s-action');
$domain = preg_replace('/^www\./', '', $_SERVER['SERVER_NAME']);
$cookie_name = 'admin_remember_' . str_replace( '.', '-', $domain );
$users = new \Domain\User\UserRepository($mdb);
switch ($sa)
{
@@ -45,11 +48,11 @@ class Site
$login = \S::get('login');
$pass = \S::get('password');
$result = \admin\factory\Users::logon($login, $pass);
$result = $users->logon($login, $pass);
if ( $result == 1 )
{
$user = \admin\factory\Users::details($login);
$user = $users->details($login);
if ( $user['twofa_enabled'] == 1 )
{
@@ -60,7 +63,7 @@ class Site
'started' => time(),
] );
if ( !\admin\factory\Users::send_twofa_code( (int)$user['id'] ) )
if ( !$users->sendTwofaCode( (int)$user['id'] ) )
{
\S::alert('Nie udało się wysłać kodu 2FA. Spróbuj ponownie.');
\S::delete_session('twofa_pending');
@@ -73,7 +76,7 @@ class Site
}
else
{
$user = \admin\factory\Users::details($login);
$user = $users->details($login);
self::finalize_admin_login(
$user,
@@ -119,7 +122,7 @@ class Site
exit;
}
$ok = \admin\factory\Users::verify_twofa_code((int)$pending['uid'], $code);
$ok = $users->verifyTwofaCode((int)$pending['uid'], $code);
if (!$ok)
{
\S::alert('Błędny lub wygasły kod.');
@@ -128,7 +131,7 @@ class Site
}
// 2FA OK — finalna sesja
$user = \admin\factory\Users::details($pending['login']);
$user = $users->details($pending['login']);
self::finalize_admin_login(
$user,
@@ -152,7 +155,7 @@ class Site
exit;
}
if (!\admin\factory\Users::send_twofa_code((int)$pending['uid'], true))
if (!$users->sendTwofaCode((int)$pending['uid'], true))
{
\S::alert('Kod można wysłać ponownie po krótkiej przerwie.');
}
@@ -245,6 +248,13 @@ class Site
'Filemanager' => function() {
return new \admin\Controllers\FilemanagerController();
},
'Users' => function() {
global $mdb;
return new \admin\Controllers\UsersController(
new \Domain\User\UserRepository( $mdb )
);
},
];
return self::$newControllers;

View File

@@ -1,43 +0,0 @@
<?php
namespace admin\controls;
class Users
{
public static function user_delete()
{
if ( \admin\factory\Users::user_delete( \S::get( 'id' ) ) )
\S::alert( 'Użytkownik został usunięty.' );
header( 'Location: /admin/users/view_list/' );
exit;
}
public static function user_save()
{
$values = json_decode( \S::get( 'values' ), true );
$response = \admin\factory\Users::user_save( $values['id'], $values['login'], $values['status'], $values['password'], $values['password_re'], $values['admin'], $values['twofa_enabled'], $values['twofa_email'] );
echo json_encode( $response );
exit;
}
public static function user_edit()
{
return \admin\view\Users::user_edit(
\admin\factory\Users::user_details(
\S::get( 'id' )
)
);
}
public static function view_list()
{
return \admin\view\Users::users_list();
}
static public function twofa() {
return \Tpl::view( 'site/unlogged', [
'content' => \Tpl::view( 'users/user-2fa' )
] );
}
}
?>

View File

@@ -1,214 +0,0 @@
<?php
namespace admin\factory;
class Users
{
static public function verify_twofa_code(int $userId, string $code): bool
{
$user = self::get_by_id( $userId );
if (!$user) return false;
if ((int)$user['twofa_failed_attempts'] >= 5)
{
return false; // zbyt wiele prób
}
// sprawdź ważność
if (empty($user['twofa_expires_at']) || time() > strtotime($user['twofa_expires_at']))
{
// wyczyść po wygaśnięciu
self::update_by_id($userId, [
'twofa_code_hash' => null,
'twofa_expires_at' => null,
]);
return false;
}
$ok = (!empty($user['twofa_code_hash']) && password_verify($code, $user['twofa_code_hash']));
if ($ok)
{
// sukces: czyścimy wszystko
self::update_by_id($userId, [
'twofa_code_hash' => null,
'twofa_expires_at' => null,
'twofa_sent_at' => null,
'twofa_failed_attempts' => 0,
'last_logged' => date('Y-m-d H:i:s'),
]);
return true;
}
// zła próba — inkrementacja
self::update_by_id($userId, [
'twofa_failed_attempts' => (int)$user['twofa_failed_attempts'] + 1,
'last_error_logged' => date('Y-m-d H:i:s'),
]);
return false;
}
static public function get_by_id(int $userId): ?array {
global $mdb;
return $mdb->get('pp_users', '*', ['id' => $userId]) ?: null;
}
static public function update_by_id(int $userId, array $data): bool {
global $mdb;
return (bool)$mdb->update('pp_users', $data, ['id' => $userId]);
}
static public function send_twofa_code(int $userId, bool $resend = false): bool {
$user = self::get_by_id($userId);
if ( !$user )
return false;
if ( (int)$user['twofa_enabled'] !== 1 )
return false;
$to = $user['twofa_email'] ?: $user['login'];
if (!filter_var($to, FILTER_VALIDATE_EMAIL))
return false;
if ( $resend && !empty( $user['twofa_sent_at'] ) ) {
$last = strtotime($user['twofa_sent_at']);
if ($last && (time() - $last) < 30)
return false;
}
$code = random_int(100000, 999999);
$hash = password_hash((string)$code, PASSWORD_DEFAULT);
self::update_by_id( $userId, [
'twofa_code_hash' => $hash,
'twofa_expires_at' => date('Y-m-d H:i:s', time() + 10 * 60), // 10 minut
'twofa_sent_at' => date('Y-m-d H:i:s'),
'twofa_failed_attempts' => 0,
] );
$subject = 'Twój kod logowania 2FA';
$body = "Twój kod logowania do panelu administratora: {$code}. Kod jest ważny przez 10 minut. Jeśli to nie Ty inicjowałeś logowanie zignoruj tę wiadomość i poinformuj administratora.";
$sent = \S::send_email($to, $subject, $body);
if (!$sent) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
$headers .= "From: no-reply@" . ($_SERVER['HTTP_HOST'] ?? 'localhost') . "\r\n";
$encodedSubject = mb_encode_mimeheader($subject, 'UTF-8');
$sent = mail($to, $encodedSubject, $body, $headers);
}
return $sent;
}
public static function user_delete( $user_id )
{
global $mdb;
return $mdb -> delete( 'pp_users', [ 'id' => (int)$user_id ] );
}
public static function user_details( $user_id )
{
global $mdb;
return $mdb -> get( 'pp_users', '*', [ 'id' => (int)$user_id ] );
}
public static function user_save( $user_id = '', $login, $status, $password, $password_re, $admin, $twofa_enabled = 0, $twofa_email = '' )
{
global $mdb, $lang, $config;
if ( !$user_id )
{
if ( strlen( $password ) < 5 )
return $response = [ 'status' => 'error', 'msg' => 'Podane hasło jest zbyt krótkie.' ];
if ( $password != $password_re )
return $response = [ 'status' => 'error', 'msg' => 'Podane hasła są różne' ];
if ( $mdb -> insert( 'pp_users', [
'login' => $login,
'status' => $status == 'on' ? 1 : 0,
'admin' => $admin,
'password' => md5( $password ),
'twofa_enabled' => $twofa_enabled == 'on' ? 1 : 0,
'twofa_email' => $twofa_email
] ) )
{
return $response = [ 'status' => 'ok', 'msg' => 'Użytkownik został zapisany.' ];
}
}
else
{
if ( $password and strlen( $password ) < 5 )
return $response = [ 'status' => 'error', 'msg' => 'Podane hasło jest zbyt krótkie.' ];
if ( $password and $password != $password_re )
return $response = [ 'status' => 'error', 'msg' => 'Podane hasła są różne' ];
if ( $password )
$mdb -> update( 'pp_users', [
'password' => md5( $password )
], [
'id' => (int)$user_id
] );
$mdb -> update( 'pp_users', [
'login' => $login,
'admin' => $admin,
'status' => $status == 'on' ? 1 : 0,
'twofa_enabled' => $twofa_enabled == 'on' ? 1 : 0,
'twofa_email' => $twofa_email
], [
'id' => (int)$user_id
] );
return $response = [ 'status' => 'ok', 'msg' => 'Uzytkownik został zapisany.' ];
}
}
public static function check_login( $login, $user_id )
{
global $mdb;
if ( $mdb -> get( 'pp_users', 'login', [ 'AND' => [ 'login' => $login, 'id[!]' => (int)$user_id ] ] ) )
return $response = [ 'status' => 'error', 'msg' => 'Podany login jest już zajęty.' ];
return $response = [ 'status' => 'ok' ];
}
public static function logon( $login, $password )
{
global $mdb;
if ( !$mdb -> get( 'pp_users', '*', [ 'login' => $login ] ) )
return 0;
if ( !$mdb -> get( 'pp_users', '*', [ 'AND' => [ 'login' => $login, 'status' => 1, 'error_logged_count[<]' => 5 ] ] ) )
return -1;
if ( $mdb -> get( 'pp_users', '*', [ 'AND' => [ 'login' => $login, 'status' => 1, 'password' => md5( $password ) ] ] ) )
{
$mdb -> update( 'pp_users', [ 'last_logged' => date( 'Y-m-d H:i:s' ), 'error_logged_count' => 0 ], [ 'login' => $login ] );
return 1;
}
else
{
$mdb -> update( 'pp_users', [ 'last_error_logged' => date( 'Y-m-d H:i:s' ), 'error_logged_count[+]' => 1 ], [ 'login' => $login ] );
if ( $mdb -> get( 'pp_users', 'error_logged_count', [ 'login' => $login ] ) >= 5 )
{
$mdb -> update( 'pp_users', [ 'status' => 0 ], [ 'login' => $login ] );
return -1;
}
}
return 0;
}
public static function details( $login )
{
global $mdb;
return $mdb -> get( 'pp_users', '*', [ 'login' => $login ] );
}
}
?>

View File

@@ -5,14 +5,22 @@ class Page {
public static function show()
{
global $user;
global $user, $mdb;
if ( $_GET['module'] == 'user' && $_GET['action'] == 'twofa' ) {
return \admin\controls\Users::twofa();
$controller = new \admin\Controllers\UsersController(
new \Domain\User\UserRepository( $mdb )
);
return $controller->twofa();
}
if ( !$user || !$user['admin'] )
return \admin\view\Users::login_form();
{
$controller = new \admin\Controllers\UsersController(
new \Domain\User\UserRepository( $mdb )
);
return $controller->login_form();
}
$tpl = new \Tpl;
$tpl -> content = \admin\Site::route();

View File

@@ -1,25 +0,0 @@
<?php
namespace admin\view;
class Users
{
public static function login_form()
{
$tpl = new \Tpl;
return $tpl -> render( 'site/unlogged-layout' );
}
public static function users_list()
{
$tpl = new \Tpl;
return $tpl -> render( 'users/users-list' );
}
public static function user_edit( $user )
{
$tpl = new \Tpl;
$tpl -> user = $user;
return $tpl -> render( 'users/user-edit' );
}
}
?>