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
159 changes: 151 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 / Получение пользователя из базы данных
Expand All @@ -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,
Expand All @@ -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
<form method="POST" action="/login">
<input type="email" name="email" required>
<input type="password" name="password" required>
<label>
<input type="checkbox" name="remember_me"> Remember me / Запомнить меня
</label>
<button type="submit">Login</button>
</form>
```
##### 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

Expand Down
40 changes: 35 additions & 5 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
Expand Down
Loading