Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 39 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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```
Expand All @@ -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 / Регистрация пользователя
Expand All @@ -66,6 +57,7 @@ $user = [
$user = [
"email" => "user@email.com",
"password" => "password_hash"
"role" => "admin"
];
```
##### Authentication / Аутентификация
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down
14 changes: 10 additions & 4 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
- [Rudra\Auth\Auth](#rudra_auth_auth)
- [Rudra\Auth\AuthFacade](#rudra_auth_authfacade)
- [Rudra\Auth\AuthInterface](#rudra_auth_authinterface)
<hr>


---



<a id="rudra_auth_auth"></a>

Expand Down Expand Up @@ -30,7 +34,7 @@
### Class: Rudra\Auth\AuthFacade
| Visibility | Function |
|:-----------|:---------|
| public static | `__callStatic(string $method, array $parameters): ?mixed`<br>Handles static method calls for the Facade class.<br>It dynamically resolves the underlying class name by removing "Facade" from the class name.<br>If the resolved class does not exist, it attempts to clean up the class name by removing spaces.<br>If the resolved class is not already registered in the container, it registers it.<br>Finally, it delegates the static method call to the resolved class instance.<br>-------------------------<br>Обрабатывает статические вызовы методов для класса Facade.<br>Динамически разрешает имя базового класса, удаляя "Facade" из имени класса.<br>Если разрешённый класс не существует, пытается очистить имя класса, удаляя пробелы.<br>Если разрешённый класс ещё не зарегистрирован в контейнере, он регистрируется.<br>В конце делегирует статический вызов метода экземпляру разрешённого класса. |
| public static | `__callStatic(string $method, array $parameters): mixed`<br>Handles static method calls for the Facade class.<br>It dynamically resolves the underlying class name by removing "Facade" from the class name.<br>If the resolved class does not exist, it attempts to clean up the class name by removing spaces.<br>If the resolved class is not already registered in the container, it registers it.<br>Finally, it delegates the static method call to the resolved class instance.<br>-------------------------<br>Обрабатывает статические вызовы методов для класса Facade.<br>Динамически разрешает имя базового класса, удаляя "Facade" из имени класса.<br>Если разрешённый класс не существует, пытается очистить имя класса, удаляя пробелы.<br>Если разрешённый класс ещё не зарегистрирован в контейнере, он регистрируется.<br>В конце делегирует статический вызов метода экземпляру разрешённого класса. |


<a id="rudra_auth_authinterface"></a>
Expand All @@ -43,6 +47,8 @@
| abstract public | `authorization(?string $token, ?string $redirect): bool`<br> |
| abstract public | `roleBasedAccess(string $role, string $privilege, ?string $redirect): bool`<br> |
| abstract public | `bcrypt(string $password, int $cost): string`<br> |
<hr>

###### created with [Rudra-Documentation-Collector](#https://github.com/Jagepard/Rudra-Documentation-Collector)

---

###### created with [Rudra-Documentation-Collector](https://github.com/Jagepard/Rudra-Documentation-Collector)
30 changes: 15 additions & 15 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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"]);
Expand All @@ -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;
Expand Down
Loading