Skip to content

Commit

Permalink
refactoring & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sinbadxiii committed Sep 1, 2022
1 parent 9211d0e commit 646b899
Show file tree
Hide file tree
Showing 19 changed files with 660 additions and 59 deletions.
79 changes: 73 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Phalcon Auth позволит вам создать систему аутент

## Manager

Если вы следуете философии фреймворка Phalcon и хотите вручную настроить все компоненты аутентификации, то вам понадобится класс `Sinbadxiii\PhalconAuth\Manager` - с помощью данного менджера можно настроить охранника, адаптер поставщиков и распределить доступы пользователям.
Если вы строго придерживаетесь философии фреймворка Phalcon и хотите вручную настроить все компоненты аутентификации, то вам понадобится класс `Sinbadxiii\PhalconAuth\Manager` - с помощью данного менеджера можно настроить охранника, адаптер поставщиков и распределить доступы пользователям.

```php
use Sinbadxiii\PhalconAuth\Manager;
Expand Down Expand Up @@ -99,7 +99,7 @@ return $auth;

В результате получился менеджер, который будет искать пользователей через модель `User` в таблице базе данных `users`.
Результат аутентификации будет храниться в сессии, и куках, если выбрать "Запомнить меня".
В качестве других аргументов нужно передать сервис провайдеры `$this->security`, `$this->session`, `$this->cookies`, `$this->request`, `$this->eventsManager`, которые будут необходимы при дальнейшем использовании охранников и адаптеров поставщиков.
В качестве других аргументов нужно передать сервис провайдеры `$this->security`, `$this->session`, `$this->cookies`, `$this->request`, `$this->eventsManager`, которые будут необходимы при дальнейшем использовании охранника и адаптера поставщиков.

- public <b>addGuard</b>(string $nameGuard, GuardInterface $guard, bool $isDefault = false) - добавить охранника
- public <b>guard</b>(?string $name = null) - получить конкретного охранника или по заданного по дефолту
Expand Down Expand Up @@ -160,7 +160,6 @@ $auth->addGuard("api", $guard, true);

return $auth;
```

Соответствено GET запрос должен будет иметь вид:

```shell
Expand Down Expand Up @@ -358,9 +357,7 @@ namespace Sinbadxiii\PhalconAuth\Access;
interface AccessInterface
{
public function setExceptActions(...$actions): void;
public function getExceptActions(): array;
public function setOnlyActions(...$actions): void;
public function getOnlyActions(): array;
public function isAllowed(): bool;
public function redirectTo();
public function allowedIf(): bool;
Expand Down Expand Up @@ -662,6 +659,76 @@ class User extends Model implements AuthenticatableInterface, RememberingInterfa
}
```

Модель `App\Models\RememberToken` будет иметь вид:

```php
<?php

declare(strict_types=1);

namespace App\Models;

use Phalcon\Mvc\Model;
use Sinbadxiii\PhalconAuth\RememberTokenInterface;

class RememberToken extends Model implements RememberTokenInterface
{
/**
* @var integer
*/
public $id;

/**
* @var integer
*/
public $user_id;

/**
* @var string
*/
public $token;

/**
* @var string
*/
public $ip;

/**
* @var string
*/
public $user_agent;

/**
* @var integer
*/
public $created_at;

/**
* @var integer
*/
public $updated_at;

/**
* @var integer
*/
public $expired_at;

public function initialize()
{
$this->setSource("users_remember_tokens");
}

public function getToken(): string
{
return $this->token;
}

public function getUserAgent(): string
{
return $this->user_agent;
}
}
```
Интерфейс `Sinbadxiii\PhalconAuth\AuthenticatableInterface` имеет следущий вид:

```php
Expand Down Expand Up @@ -1280,4 +1347,4 @@ class AuthWithBasic extends AbstractAccess
После запроса, ни куки, ни сессия не будут содержать данные о пользователе, и следущий запрос так же должен содержать пользовательские данные заголовка `Authorization`, иначе будет вызвано исключение `Sinbadxiii\PhalconAuth\Exceptions`

### License
The MIT License (MIT). Please see [License File](https://github.com/sinbadxiii/phalcon-auth/blob/master/LICENSE) for more information.
The MIT License (MIT). Please see [License File](https://github.com/sinbadxiii/phalcon-auth/blob/master/LICENSE) for more information.
5 changes: 0 additions & 5 deletions src/Access/AbstractAccess.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@ abstract class AbstractAccess extends Injectable implements AccessInterface
*/
protected array $onlyActions = [];

/**
* @return bool
*/
abstract public function allowedIf(): bool;

/**
* @param ...$actions
* @return void
Expand Down
2 changes: 0 additions & 2 deletions src/Access/AccessInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
interface AccessInterface
{
public function setExceptActions(...$actions): void;
public function getExceptActions(): array;
public function setOnlyActions(...$actions): void;
public function getOnlyActions(): array;
public function isAllowed(string $actionName): bool;
public function redirectTo();
public function allowedIf(): bool;
Expand Down
1 change: 0 additions & 1 deletion src/Access/AuthenticatesRequestInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,4 @@
interface AuthenticatesRequestInterface
{
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher): void;
//protected function authenticate();
}
8 changes: 6 additions & 2 deletions src/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ public function __construct(Security $hasher, array $config = [])
$this->hasher = $hasher;
$this->config = $config;

if (!empty($config['model'])) {
$this->model = $config['model'];
if (!empty($this->config['model'])) {
$this->model = $this->config['model'];
}
}

Expand Down Expand Up @@ -76,6 +76,10 @@ public function setConfig(array $config): static
{
$this->config = $config;

if (!empty($this->config['model'])) {
$this->model = $this->config['model'];
}

return $this;
}
}
26 changes: 17 additions & 9 deletions src/Adapter/Memory.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

use InvalidArgumentException;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;

use function array_column;
use function array_search;
use function var_dump;

/**
* Class Memory
Expand Down Expand Up @@ -43,7 +45,13 @@ public function retrieveById($identifier): ?AuthenticatableInterface

$userModel = $this->model;

return ($userData = $this->getProviderStorage()[$identifier]) ? new $userModel($userData) : null;
$userData = null;

if (isset($this->getProviderStorage()[$identifier])) {
$userData = $this->getProviderStorage()[$identifier];
}

return ($userData) ? new $userModel($userData) : null;
}

/**
Expand Down Expand Up @@ -88,13 +96,7 @@ public function first(array $providerStorage, array $credentials): ?Authenticata
*/
protected function getProviderStorage(): mixed
{
if (empty($this->getData())) {
throw new InvalidArgumentException(
"Data is empty"
);
}

return $this->data;
return $this->getData();
}

/**
Expand All @@ -112,14 +114,20 @@ public function getData()
$this->data = $this->config["data"];
}

if (empty($this->data)) {
throw new InvalidArgumentException(
"Data is empty"
);
}

return $this->data;
}

/**
* @param $data
* @return void
*/
public function setData($data)
public function setData(array $data): void
{
$this->data = $data;
}
Expand Down
5 changes: 3 additions & 2 deletions src/Guard/BasicHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Sinbadxiii\PhalconAuth\Guard;

use Phalcon\Http\Request;
use function var_dump;

/**
* Trait BasicHelper
Expand All @@ -23,7 +24,7 @@ public function basic(string $field = 'email', array $extraConditions = []): boo
return true;
}

if ($this->attemptBasic($this->getRequest(), $field, $extraConditions)) {
if ($this->attemptBasic($this->request, $field, $extraConditions)) {
return true;
}

Expand Down Expand Up @@ -67,7 +68,7 @@ protected function basicCredentials(Request $request, string $field): array
*/
public function onceBasic(string $field = 'email', array $extraConditions = []): mixed
{
$credentials = $this->basicCredentials($this->getRequest(), $field);
$credentials = $this->basicCredentials($this->request, $field);

if ($this->once(array_merge($credentials, $extraConditions))) {
return $this->getUser();
Expand Down
10 changes: 4 additions & 6 deletions src/Guard/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Sinbadxiii\PhalconAuth\Guard;

use Phalcon\Events\AbstractEventsAware;
use Phalcon\Events\EventsAwareInterface;
use Phalcon\Http\Response\Cookies;
use Phalcon\Http\Request;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;
Expand All @@ -14,16 +13,17 @@
use InvalidArgumentException;
use Sinbadxiii\PhalconAuth\RememberTokenInterface;
use Phalcon\Session\ManagerInterface as SessionManagerInterface;
use Phalcon\Events\ManagerInterface as EventsManagerInterface;;
use Phalcon\Events\ManagerInterface as EventsManagerInterface;

use function is_null;
use function var_dump;

/**
* Class Session
* @package Sinbadxiii\PhalconAuth\Guard
*/
class Session extends AbstractEventsAware implements
GuardInterface, GuardStatefulInterface, BasicAuthInterface, EventsAwareInterface
GuardInterface, GuardStatefulInterface, BasicAuthInterface
{
use GuardHelper;
use BasicHelper;
Expand Down Expand Up @@ -146,7 +146,7 @@ public function validate(array $credentials = []): bool
* @param $recaller
* @return mixed
*/
protected function userFromRecaller($recaller)
protected function userFromRecaller($recaller): ?AuthenticatableInterface
{
$this->viaRemember = ! is_null($user = $this->adapter->retrieveByToken(
$recaller->id(), $recaller->token(), $recaller->userAgent()
Expand Down Expand Up @@ -180,7 +180,6 @@ protected function getRememberData()
*/
public function getName(): string
{

return "auth-" . sha1(static::class . $this->adapter::class);
}

Expand All @@ -205,7 +204,6 @@ public function login(AuthenticatableInterface $user, bool $remember = false): v
$this->updateSession($user->getAuthIdentifier());

if ($remember) {

if (!$this->adapter instanceof AdapterWithRememberTokenInterface) {
throw new InvalidArgumentException(
"Adapter " . $this->adapter::class . " not instanceof AdapterWithRememberTokenInterface"
Expand Down
14 changes: 13 additions & 1 deletion src/Guard/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

namespace Sinbadxiii\PhalconAuth\Guard;

use Phalcon\Di\Di;
use Phalcon\Http\Request;
use Phalcon\Support\Helper\Str\StartsWith;
use Sinbadxiii\PhalconAuth\Adapter\AdapterInterface;
use Sinbadxiii\PhalconAuth\AuthenticatableInterface;

use function is_null;
use function var_dump;

/**
* Class Token
Expand Down Expand Up @@ -104,6 +104,10 @@ public function getTokenForRequest(): ?string
{
$token = $this->request->get($this->inputKey);

if (empty($token)) {
$token = $this->request->getPost($this->inputKey);;
}

if (empty($token)) {
$token = $this->bearerToken();
}
Expand Down Expand Up @@ -135,6 +139,14 @@ public function setRequest(Request $request)
return $this;
}

/**
* @return Request
*/
public function getRequest()
{
return $this->request;
}

/**
* @return AdapterInterface
*/
Expand Down
7 changes: 1 addition & 6 deletions src/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,6 @@ class Manager implements ManagerInterface
*/
protected $defaultGuard;

/**
* @var GuardInterface
*/
protected $guard;

/**
* @param string|null $name
* @return GuardInterface
Expand All @@ -51,7 +46,7 @@ public function guard(?string $name = null): GuardInterface
}

if (!isset($this->guards[$name])) {
throw new \Exception("Guard [{$name}] is not defined.");
throw new InvalidArgumentException("Auth guard [{$name}] is not defined.");
}

return $this->guards[$name];
Expand Down
Loading

0 comments on commit 646b899

Please sign in to comment.