diff --git a/README.md b/README.md index e4a1ab8..cf587f8 100755 --- a/README.md +++ b/README.md @@ -4,8 +4,7 @@ [![Coverage Status](https://coveralls.io/repos/github/Jagepard/Rudra-Auth/badge.svg?branch=master)](https://coveralls.io/github/Jagepard/Rudra-Auth?branch=master) ----- -# Rudra-Auth | [API](https://github.com/Jagepard/Rudra-Auth/blob/master/docs.md "Documentation API") -### Authorization +## Authentication, session management and RBAC / Аутентификация, управление сессиями и ролевой доступ | [API](https://github.com/Jagepard/Rudra-Auth/blob/master/docs.md "Documentation API") #### Install / Установка ```composer require rudra/auth``` @@ -19,39 +18,31 @@ use Rudra\Auth\AuthFacade as Auth; >Для корректной работы компонента необходимо добавить следующие параметры в конфигурационный файл 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", -]; +```yml +#---------------------------------------------------------------- +# 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: 0 + editor: 1 + moderator: 2 + user: 3 + +#--------------------------------------------------------------------------- +# Environment (in the 'test' environment, cookies are not deleted on logout) +#--------------------------------------------------------------------------- +# Окружение (в среде 'test' не удаляются cookie при logout) +#--------------------------------------------------------------------------- +environment: production ``` ##### User registration / Регистрация пользователя @@ -66,6 +57,7 @@ $user = [ $user = [ "email" => "user@email.com", "password" => "password_hash" + "role" => "admin" ]; ``` ##### Authentication / Аутентификация @@ -131,20 +123,20 @@ The token is generated from the user's password, email, and session hash. ```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; @@ -160,22 +152,22 @@ if (!Auth::authorization($token, "login")) { 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; diff --git a/docs.md b/docs.md index 556127b..b30e975 100644 --- a/docs.md +++ b/docs.md @@ -2,7 +2,11 @@ - [Rudra\Auth\Auth](#rudra_auth_auth) - [Rudra\Auth\AuthFacade](#rudra_auth_authfacade) - [Rudra\Auth\AuthInterface](#rudra_auth_authinterface) -
+ + +--- + + @@ -30,7 +34,7 @@ ### Class: Rudra\Auth\AuthFacade | Visibility | Function | |:-----------|:---------| -| public static | `__callStatic(string $method, array $parameters): ?mixed`
Handles static method calls for the Facade class.
It dynamically resolves the underlying class name by removing "Facade" from the class name.
If the resolved class does not exist, it attempts to clean up the class name by removing spaces.
If the resolved class is not already registered in the container, it registers it.
Finally, it delegates the static method call to the resolved class instance.
-------------------------
Обрабатывает статические вызовы методов для класса Facade.
Динамически разрешает имя базового класса, удаляя "Facade" из имени класса.
Если разрешённый класс не существует, пытается очистить имя класса, удаляя пробелы.
Если разрешённый класс ещё не зарегистрирован в контейнере, он регистрируется.
В конце делегирует статический вызов метода экземпляру разрешённого класса. | +| public static | `__callStatic(string $method, array $parameters): mixed`
Handles static method calls for the Facade class.
It dynamically resolves the underlying class name by removing "Facade" from the class name.
If the resolved class does not exist, it attempts to clean up the class name by removing spaces.
If the resolved class is not already registered in the container, it registers it.
Finally, it delegates the static method call to the resolved class instance.
-------------------------
Обрабатывает статические вызовы методов для класса Facade.
Динамически разрешает имя базового класса, удаляя "Facade" из имени класса.
Если разрешённый класс не существует, пытается очистить имя класса, удаляя пробелы.
Если разрешённый класс ещё не зарегистрирован в контейнере, он регистрируется.
В конце делегирует статический вызов метода экземпляру разрешённого класса. | @@ -43,6 +47,8 @@ | abstract public | `authorization(?string $token, ?string $redirect): bool`
| | abstract public | `roleBasedAccess(string $role, string $privilege, ?string $redirect): bool`
| | abstract public | `bcrypt(string $password, int $cost): string`
| -
-###### created with [Rudra-Documentation-Collector](#https://github.com/Jagepard/Rudra-Documentation-Collector) + +--- + +###### created with [Rudra-Documentation-Collector](https://github.com/Jagepard/Rudra-Documentation-Collector) diff --git a/src/Auth.php b/src/Auth.php index 1d5fb50..d3cd34b 100755 --- a/src/Auth.php +++ b/src/Auth.php @@ -30,11 +30,11 @@ public function __construct(private readonly RudraInterface $rudra) $secret = $rudra->config()?->get("secret") ?? throw new \RuntimeException('Auth secret is missing'); /** - * --------------------------------------------| + * -------------------------------------------- * Sets the cookie lifetime, session hash - * --------------------------------------------| + * -------------------------------------------- * Устанавливает время жизни cookie, хэш сессии - * --------------------------------------------| + * -------------------------------------------- */ $this->expireTime = strtotime('+1 week'); $this->sessionHash = hash_hmac( @@ -166,33 +166,33 @@ public function authorization(?string $token = null, ?string $redirect = null): } /** - * ---------------------------------------| + * --------------------------------------- * Providing access to shared resources - * ---------------------------------------| + * --------------------------------------- * Предоставление доступа к общим ресурсам - * ---------------------------------------| + * --------------------------------------- */ if ($token === null) { return true; } /** - * -----------------------------------------------------| + * ----------------------------------------------------- * Providing access to the user's personal resources - * -----------------------------------------------------| + * ----------------------------------------------------- * Предоставление доступа к личным ресурсам пользователя - * -----------------------------------------------------| + * ----------------------------------------------------- */ if (hash_equals($token, $this->rudra->session()->get("token"))) { return true; } /** - * -------------------| + * ------------------- * If not logged in - * -------------------| + * ------------------- * Если не авторизован - * -------------------| + * ------------------- */ if ($redirect !== null) { $this->handleRedirect($redirect, ["status" => "Access denied"]); @@ -214,11 +214,11 @@ 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) - * -------------------------------------------------------------------| + * ------------------------------------------------------------------- */ if ($roles[$role] <= $roles[$privilege]) { return true;