From 83860cbbfb3f56680d2c0fb8464c16ccc7a34e7b Mon Sep 17 00:00:00 2001 From: Jagepard Date: Thu, 4 Jun 2026 13:51:15 +0300 Subject: [PATCH] docs: add comprehensive usage examples to README --- README.md | 159 ++++++++++++++++++++++++++++++++++++++++++++++++--- src/Auth.php | 40 +++++++++++-- 2 files changed, 186 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 46cf573..e4a1ab8 100755 --- a/README.md +++ b/README.md @@ -10,11 +10,55 @@ #### Install / Установка ```composer require rudra/auth``` +##### Usage / Использование +```php +use Rudra\Auth\AuthFacade as Auth; +``` +##### Configuration / Конфигурация +>For the component to work correctly, you need to add the following parameters to the Rudra configuration file + +>Для корректной работы компонента необходимо добавить следующие параметры в конфигурационный файл Rudra: + +```php +return [ + /** + * ---------------------------------------------------------------| + * Secret key for encrypting cookies and generating session hashes + * ---------------------------------------------------------------| + * Секретный ключ для шифрования cookie и генерации хэшей + * ---------------------------------------------------------------| + */ + "secret" => "your_super_secret_key_here", + + /** + * --------------------------------------------------------------------------------------| + * Roles for Role-Based Access Control (the smaller the number, the higher the privilege) + * --------------------------------------------------------------------------------------| + * Роли для Role-Based Access Control (чем меньше число, тем выше привилегия) + * --------------------------------------------------------------------------------------| + */ + "roles" => [ + "admin" => 1, + "editor" => 2, + "user" => 3, + ], + + /** + * --------------------------------------------------------------------------| + * Environment (in the 'test' environment, cookies are not deleted on logout) + * --------------------------------------------------------------------------| + * Окружение (в среде 'test' не удаляются cookie при logout) + * --------------------------------------------------------------------------| + */ + "environment" => "prod", +]; +``` + ##### User registration / Регистрация пользователя ```php $user = [ "email" => "user@email.com", - "password" => Auth::bcrypr("password") + "password" => Auth::bcrypt("password") ]; ``` ##### Getting a user from the database / Получение пользователя из базы данных @@ -24,12 +68,12 @@ $user = [ "password" => "password_hash" ]; ``` - -##### Usage / Использование -```php -use Rudra\Auth\AuthFacade as Auth; -``` ##### Authentication / Аутентификация +> The second argument is the **plain text password** entered by the user. +> The `$user['password']` must contain a **hash** from the database. + +> Второй аргумент — это **пароль в открытом виде**, введённый пользователем. +> В `$user['password']` должен быть **хэш** из базы данных. ```php Auth::authentication( $user, @@ -38,9 +82,108 @@ Auth::authentication( ["error" => "Wrong access data"] ); ``` -##### Logout from authentication session / Выход из сеанса аутентификации +> **Note:** For the "Remember Me" feature to work, the login form must contain a checkbox with the name `remember_me`. + +> **Примечание:** Чтобы работала функция "Запомнить меня", форма входа должна содержать чекбокс с именем `remember_me`. +##### Login form example / Пример формы входа +```html +
+ + + + +
+``` +##### Restoring session (Remember Me) / Восстановление сессии +>Called at the beginning of the application loading (before authorization check). +>If the user has valid 'Remember Me' cookies, the session will be restored automatically. + +>Вызывается в начале загрузки приложения (до проверки авторизации). +>Если у пользователя есть валидные cookie "Remember Me", сессия будет восстановлена автоматически. +```php +Auth::restoreSessionIfSetRememberMe("login"); +``` +##### Authorization check / Проверка авторизации + +###### General authorization check / Общая проверка авторизации +>Check if the user is authorized. If not — redirect to 'login' + +>Проверяем, авторизован ли пользователь. Если нет — редирект на 'login' +```php +if (!Auth::authorization(null, "login")) { + exit; +} +``` +>If you just need to get a boolean value without a redirect (for example, for an API): + +>Если нужно просто получить булево значение без редиректа (например, для API): +```php +$isLoggedIn = Auth::authorization(); +``` +###### Access to personal user resources / Доступ к личным ресурсам пользователя +>For access control to a specific user's resources (e.g., profile, personal data), a token is used. +The token is generated from the user's password, email, and session hash. + +>Для контроля доступа к ресурсам конкретного пользователя (например, профиль, личные данные) используется токен. +Токен генерируется из пароля, email пользователя и хэша сессии. + +```php +/** + * ------------------------------------------| + * Generate token for the current user + * ------------------------------------------| + * Генерируем токен для текущего пользователя + * ------------------------------------------| + */ +$token = md5($user['password'] . $user['email'] . Auth::getSessionHash()); + +/** + * --------------------------------------------| + * Check if the token matches the session token + * --------------------------------------------| + * Проверяем, совпадает ли токен с сессионным + * --------------------------------------------| + */ +if (!Auth::authorization($token, "login")) { + exit; +} +``` +##### Role-Based Access Control / Ролевой доступ +>Check if the current role ('admin') has privileges not lower than the requested ones ('editor'). +>If privileges are insufficient — redirect to 'error/403' + +>Проверяем, имеет ли текущая роль ('admin') права не ниже запрашиваемых ('editor'). +>Если прав не хватает — редирект на 'error/403' +```php +use Rudra\Container\Facades\Session; + +/** + * ------------------------------------------------------------------------------------| + * Get the role of the current user from the session (for example, after authorization) + * ------------------------------------------------------------------------------------| + * Получаем роль текущего пользователя из сессии (например, после авторизации) + * ------------------------------------------------------------------------------------| + */ +if (Session::has("user")) { + $currentRole = Session::get("user")['role'] ?? 'user'; +} + +/** + * --------------------------------------------------------------------------------------------| + * Check if the permissions are sufficient for access (for example, 'editor' level is required) + * --------------------------------------------------------------------------------------------| + * Проверяем, достаточно ли прав для доступа (например, требуется уровень 'editor') + * --------------------------------------------------------------------------------------------| + */ +if (!Auth::roleBasedAccess($currentRole, "editor", "error/403")) { + exit; +} +``` +##### Log out of the authentication session with a redirect to the login page / Выход из сеанса аутентификации с редиректом на страницу входа ```php -Auth::logout(); +Auth::logout("login"); ``` ## License diff --git a/src/Auth.php b/src/Auth.php index 57f91ca..1d5fb50 100755 --- a/src/Auth.php +++ b/src/Auth.php @@ -29,7 +29,13 @@ public function __construct(private readonly RudraInterface $rudra) $userAgent = $rudra->request()?->server()?->get("HTTP_USER_AGENT") ?? ''; $secret = $rudra->config()?->get("secret") ?? throw new \RuntimeException('Auth secret is missing'); - // Sets the cookie lifetime, session hash / Устанавливает время жизни cookie, хэш сессии. + /** + * --------------------------------------------| + * Sets the cookie lifetime, session hash + * --------------------------------------------| + * Устанавливает время жизни cookie, хэш сессии + * --------------------------------------------| + */ $this->expireTime = strtotime('+1 week'); $this->sessionHash = hash_hmac( algo: 'sha256', @@ -159,17 +165,35 @@ public function authorization(?string $token = null, ?string $redirect = null): return false; } - // Providing access to shared resources / Предоставление доступа к общим ресурсам + /** + * ---------------------------------------| + * Providing access to shared resources + * ---------------------------------------| + * Предоставление доступа к общим ресурсам + * ---------------------------------------| + */ if ($token === null) { return true; } - // Providing access to the user's personal resources / Предоставление доступа к личным ресурсам пользователя + /** + * -----------------------------------------------------| + * Providing access to the user's personal resources + * -----------------------------------------------------| + * Предоставление доступа к личным ресурсам пользователя + * -----------------------------------------------------| + */ if (hash_equals($token, $this->rudra->session()->get("token"))) { return true; } - // If not logged in / Если не авторизован + /** + * -------------------| + * If not logged in + * -------------------| + * Если не авторизован + * -------------------| + */ if ($redirect !== null) { $this->handleRedirect($redirect, ["status" => "Access denied"]); return false; @@ -189,7 +213,13 @@ public function roleBasedAccess(string $role, string $privilege, ?string $redire { $roles = $this->rudra->config()->get("roles"); - // Roles: the smaller the number, the higher the privilege (1 > 2 > 3) / Роли: чем меньше число, тем выше привилегия (1 > 2 > 3) + /** + * -------------------------------------------------------------------| + * Roles: the smaller the number, the higher the privilege (1 > 2 > 3) + * -------------------------------------------------------------------| + * Роли: чем меньше число, тем выше привилегия (1 > 2 > 3) + * -------------------------------------------------------------------| + */ if ($roles[$role] <= $roles[$privilege]) { return true; }