Skip to content

Commit bdf0a69

Browse files
committed
change interface adapter methods
1 parent 646b899 commit bdf0a69

File tree

14 files changed

+177
-237
lines changed

14 files changed

+177
-237
lines changed

README.md

Lines changed: 116 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,61 @@ return $auth;
121121

122122
Предположительно Сессии вы будете использовать в веб-приложениях после логина в личный кабинет,а Токен, например, в микро приложениях в качестве api сервисов. Но ничего вам не мешает применять или комбинировать охранников в нестандартных приложениях.
123123

124+
## Session Guard
125+
126+
```php
127+
use Sinbadxiii\PhalconAuth\Manager;
128+
use App\Models\User;
129+
use Sinbadxiii\PhalconAuth\Adapter\Model;
130+
use Sinbadxiii\PhalconAuth\Guard\Session;
131+
132+
$auth = new Manager();
133+
134+
$configAdapter = [
135+
'model' => User::class,
136+
];
137+
138+
$adapter = new Model($this->getSecurity(), $configAdapter);
139+
$guard = new Session(
140+
$adapter,
141+
$this->getSession(),
142+
$this->getCookies(),
143+
$this->getRequest(),
144+
$this->getEventsManager()
145+
);
146+
147+
$auth->addGuard("web", $guard, true);
148+
149+
return $auth;
150+
```
151+
152+
- public function <b>__construct</b>(AdapterInterface $adapter, SessionManagerInterface $session,
153+
Cookies $cookies, Request $request, EventsManagerInterface $eventsManager)
154+
- public function <b>attempt</b>(array $credentials = [], $remember = false) - попытка аутентификации
155+
- public function <b>user</b>() - получить аутентифицированного пользователя
156+
- public function <b>validate</b>(array $credentials = []) - валидация входных данных
157+
- public function <b>getName</b>() - получение имени сессии
158+
- public function <b>getRememberName</b>() - имя куки при запомнить меня
159+
- public function <b>login</b>(AuthenticatableInterface $user, bool $remember = false) - логин экземпляра пользователя
160+
- public function <b>loginById</b>($id, bool $remember = false) - логин по Id пользователя
161+
- public function <b>once</b>(array $credentials = []) - логин без сохранения пользователя в сессию
162+
- public function <b>logout</b>() - выход
163+
- public function <b>getLastUserAttempted</b>() - получение последнего попытавшегося залогиниться пользователя
164+
- public function <b>viaRemember</b>() - проверка что пользователь был вытащен из Запомнить меня
165+
- public function <b>getUser</b>() - получить пользователя
166+
- public function <b>setRequest</b>(Request $request)
167+
- public function <b>setSession</b>(SessionManagerInterface $session)
168+
- public function <b>setCookies</b>(Cookies $cookies)
169+
- public function <b>getAdapter</b>() - получить адаптер поставщика
170+
- public function <b>setAdapter</b>(AdapterInterface $adapter) - назначить адаптера поставшика
171+
172+
Basic
173+
174+
- public function <b>basic</b>(string $field = 'email', array $extraConditions = []) - аутентификация через Basic Auth
175+
- public function <b>onceBasic</b>(string $field = 'email', array $extraConditions = []) - аутентификация через Basic Auth без сохранения в сессию
176+
177+
## Token Guard
178+
124179
Чтобы воспользоваться `Sinbadxiii\PhalconAuth\Guard\Token`, необходимо в качестве второго аргумента передать конфиг с названиями имя параметра запроса и поля в хранилище данных пользователей, например, поле таблицы `users` в бд:
125180

126181
```php
@@ -131,7 +186,6 @@ return $auth;
131186
...
132187
]
133188
```
134-
135189
```php
136190
use Sinbadxiii\PhalconAuth\Manager;
137191
use App\Models\User;
@@ -186,6 +240,15 @@ https://yourapidomain/api/v2/users
186240

187241
> Помните, что каждый ваш запрос к приложению, должен сопровождаться параметром `auth_token` с токеном доступа.
188242
243+
- public function <b>__construct</b>(AdapterInterface $adapter, array $config, Request $request)
244+
- public function <b>user</b>() - аутентифицированный пользователь
245+
- public function <b>validate</b>(array $credentials = []) - валидация
246+
- public function <b>getTokenForRequest</b>() - поулчить токен из запросов (GET, POST, Headers)
247+
- public function <b>setRequest</b>(Request $request)
248+
- public function <b>getRequest</b>()
249+
- public function <b>getAdapter</b>()
250+
- public function <b>setAdapter</b>(AdapterInterface $adapter)
251+
189252
## Создание своего Охранника
190253

191254
```php
@@ -212,7 +275,7 @@ interface GuardInterface
212275

213276
## Access
214277

215-
С помощью Доступов (Access) вы можете задавать определенный доступ к тем или иным областям приложения, например в контроллер профиля пользователя разрешен доступ только аутентифицированным пользователям.
278+
С помощью Доступов (Access) вы можете задавать и проверять требуемый доступ к тем или иным областям приложения, например в контроллер профиля пользователя разрешен доступ только аутентифицированным пользователям.
216279

217280
```php
218281
<?php
@@ -306,7 +369,6 @@ class Guest extends AbstractAccess
306369
}
307370
}
308371
```
309-
310372
В случае если метод `allowedIf()` вернет `true`, то пользователь сможет идти дальше, если же результат будет равен `false`, то сработает метод неудачи `redirectTo()`, и приложение перенаправит пользователя, т.к. у каждого приложение логика перенаправлений может быть разная, то вам следует создать свои классы Access `auth` и `guest`, наследовав от дефолтных классов и переопределить метод `redirectTo()`:
311373
```php
312374
<?php
@@ -343,7 +405,6 @@ class Guest extends GuestAccess
343405
}
344406
}
345407
```
346-
347408
Чтобы создать свой Access, можно имплементировать интерфейс `Sinbadxiii\PhalconAuth\Access\AccessInterface`:
348409

349410
```php
@@ -477,9 +538,7 @@ $di->setShared('dispatcher', function () use ($di) {
477538
return $dispatcher;
478539
});
479540
```
480-
481541
Свойство `$accessList` позволяет быстро добавлять новые уровни доступа в приложении, например, чтобы добавить новый доступ `admin`, достаточно создать класс с условием и добавить его в список `$accessList`:
482-
483542
```php
484543
<?php
485544

@@ -785,6 +844,52 @@ interface RememberingInterface
785844
return $manager;
786845
```
787846

847+
## Адаптер поставщика `memory`
848+
849+
Используя `setData()` можно задать массив данных с пользователями, который имеет вид:
850+
851+
```php
852+
[
853+
["username" =>"admin", "name" => "admin", 'password' => 'admin', "email" => "[email protected]"],
854+
["username" => "user", "name" => "user", 'password' => 'user', "email" => "[email protected]"],
855+
]
856+
```
857+
858+
```php
859+
$di->setShared("auth", function () {
860+
861+
$security = $this->getSecurity();
862+
863+
$data = [
864+
["auth_token" => '1', "name" => "admin", "username" => "admin", 'password' => 'admin', "email" => "[email protected]"],
865+
["auth_token" => '2', "name" => "admin1", "username" => "admin", 'password' => 'admin1', "email" => "[email protected]"],
866+
];
867+
868+
$adapter = new \Sinbadxiii\PhalconAuth\Adapter\Memory($security);
869+
$adapter->setModel(App\Models\UserSimple::class);
870+
$adapter->setData($data);
871+
872+
$configGuard = [
873+
'inputKey' => 'auth_token',
874+
'storageKey' => 'auth_token',
875+
];
876+
877+
$guard = new \Sinbadxiii\PhalconAuth\Guard\Token(
878+
$adapter,
879+
$configGuard,
880+
$this->getRequest()
881+
);
882+
883+
$manager = new Manager();
884+
$manager->addGuard("api", $guard, true);
885+
886+
return $manager;
887+
});
888+
```
889+
890+
- public <b>setData</b>(array $data) - массив с данными
891+
- public <b>getData</b>() - получить массив с данными
892+
788893
## Адаптер поставщика `Stream`
789894

790895
Если взять в качестве адаптера поставщиков `users` не `Sinbadxiii\PhalconAuth\Adapter\Model`, а файл `Sinbadxiii\PhalconAuth\Adapter\Stream`:
@@ -896,52 +1001,10 @@ class UserSimple implements AuthenticatableInterface
8961001

8971002
- public <b>setFileSource</b>(string $pathSrcFile) - указать путь к файлу
8981003
- public <b>getFileSource</b>() - получить путь к файлу
1004+
- public <b>setData</b>(array $data) - массив с данными пользователей
1005+
- public <b>getData</b>() - получить массив с данными пользователей
8991006

900-
## Адаптер поставщика `memory`
901-
902-
Используя `setData()` можно задать массив данных с пользователями, который имеет вид:
903-
904-
```php
905-
[
906-
["username" =>"admin", "name" => "admin", 'password' => 'admin', "email" => "[email protected]"],
907-
["username" => "user", "name" => "user", 'password' => 'user', "email" => "[email protected]"],
908-
]
909-
```
910-
911-
```php
912-
$di->setShared("auth", function () {
913-
914-
$security = $this->getSecurity();
915-
916-
$data = [
917-
["auth_token" => '1', "name" => "admin", "username" => "admin", 'password' => 'admin', "email" => "[email protected]"],
918-
["auth_token" => '2', "name" => "admin1", "username" => "admin", 'password' => 'admin1', "email" => "[email protected]"],
919-
];
920-
921-
$adapter = new \Sinbadxiii\PhalconAuth\Adapter\Memory($security);
922-
$adapter->setModel(App\Models\UserSimple::class);
923-
$adapter->setData($data);
924-
925-
$configGuard = [
926-
'inputKey' => 'auth_token',
927-
'storageKey' => 'auth_token',
928-
];
9291007

930-
$guard = new \Sinbadxiii\PhalconAuth\Guard\Token(
931-
$adapter,
932-
$configGuard,
933-
$this->getRequest()
934-
);
935-
936-
$manager = new Manager();
937-
$manager->addGuard("api", $guard, true);
938-
939-
return $manager;
940-
});
941-
```
942-
943-
- public <b>setData</b>(array $data) - массив с данными
944-
- public <b>getData</b>() - получить массив с данными
9451008

9461009
> Не рекомендуется использовать адаптеры `stream` и `memory` в реальных приложениях из-за их функциональной ограниченности и сложности управления пользователями. Это может быть полезно в прототипах приложений и для ограниченных приложений, которые не хранят пользователей в базах данных.
9471010
@@ -958,8 +1021,8 @@ use Sinbadxiii\PhalconAuth\AuthenticatableInterface;
9581021

9591022
interface AdapterInterface
9601023
{
961-
public function retrieveByCredentials(array $credentials);
962-
public function retrieveById($id);
1024+
public function findFirstByCredentials(array $credentials);
1025+
public function findFirstById($id);
9631026
public function validateCredentials(AuthenticatableInterface $user, array $credentials): bool;
9641027
}
9651028
```
@@ -979,7 +1042,7 @@ use Sinbadxiii\PhalconAuth\RememberTokenInterface;
9791042

9801043
interface AdapterWithRememberTokenInterface
9811044
{
982-
public function retrieveByToken($identifier, $token, $user_agent): ?AuthenticatableInterface;
1045+
public function findFirstByToken($identifier, $token, $user_agent): ?AuthenticatableInterface;
9831046
public function createRememberToken(RememberingInterface $user): RememberTokenInterface;
9841047
}
9851048
```

src/Adapter/AdapterInterface.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
interface AdapterInterface
1010
{
11-
public function retrieveByCredentials(array $credentials): ?AuthenticatableInterface;
12-
public function retrieveById($id): ?AuthenticatableInterface;
11+
public function findFirstByCredentials(array $credentials): ?AuthenticatableInterface;
12+
public function findFirstById($id): ?AuthenticatableInterface;
1313
public function validateCredentials(AuthenticatableInterface $user, array $credentials): bool;
1414
}

src/Adapter/AdapterWithRememberTokenInterface.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@
1010

1111
interface AdapterWithRememberTokenInterface
1212
{
13-
public function retrieveByToken($identifier, $token, $user_agent): ?AuthenticatableInterface;
13+
public function findFirstByToken($identifier, $token, $user_agent): ?AuthenticatableInterface;
1414
public function createRememberToken(RememberingInterface $user): RememberTokenInterface;
1515
}

src/Adapter/Memory.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99

1010
use function array_column;
1111
use function array_search;
12-
use function var_dump;
1312

1413
/**
1514
* Class Memory
@@ -26,7 +25,7 @@ class Memory extends AbstractAdapter
2625
* @param array $credentials
2726
* @return AuthenticatableInterface|null
2827
*/
29-
public function retrieveByCredentials(array $credentials): ?AuthenticatableInterface
28+
public function findFirstByCredentials(array $credentials): ?AuthenticatableInterface
3029
{
3130
$providerStorage = $this->getProviderStorage();
3231

@@ -37,7 +36,7 @@ public function retrieveByCredentials(array $credentials): ?AuthenticatableInter
3736
* @param $identifier
3837
* @return AuthenticatableInterface|null
3938
*/
40-
public function retrieveById($identifier): ?AuthenticatableInterface
39+
public function findFirstById($identifier): ?AuthenticatableInterface
4140
{
4241
if (empty($this->model)) {
4342
throw new InvalidArgumentException("Сonfig with key 'model' is empty");

src/Adapter/Model.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ protected function getProviderStorage(): mixed
3232
* @param array $credentials
3333
* @return AuthenticatableInterface|null
3434
*/
35-
public function retrieveByCredentials(array $credentials): ?AuthenticatableInterface
35+
public function findFirstByCredentials(array $credentials): ?AuthenticatableInterface
3636
{
3737
$builder = Di::getDefault()->get('modelsManager')
3838
->createBuilder()
@@ -53,7 +53,7 @@ public function retrieveByCredentials(array $credentials): ?AuthenticatableInter
5353
* @param $identifier
5454
* @return AuthenticatableInterface|null
5555
*/
56-
public function retrieveById($identifier): ?AuthenticatableInterface
56+
public function findFirstById($identifier): ?AuthenticatableInterface
5757
{
5858
return $this->getProviderStorage()::findFirst($identifier);
5959
}
@@ -64,7 +64,7 @@ public function retrieveById($identifier): ?AuthenticatableInterface
6464
* @param $user_agent
6565
* @return AuthenticatableInterface|null
6666
*/
67-
public function retrieveByToken($identifier, $token, $user_agent): ?AuthenticatableInterface
67+
public function findFirstByToken($identifier, $token, $user_agent): ?AuthenticatableInterface
6868
{
6969
$retrievedModel = $this->getProviderStorage()::findFirst($identifier);
7070

src/Guard/BasicHelper.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
namespace Sinbadxiii\PhalconAuth\Guard;
66

77
use Phalcon\Http\Request;
8-
use function var_dump;
98

109
/**
1110
* Trait BasicHelper

src/Guard/Session.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
use Phalcon\Events\ManagerInterface as EventsManagerInterface;
1717

1818
use function is_null;
19-
use function var_dump;
2019

2120
/**
2221
* Class Session
@@ -83,7 +82,7 @@ public function __construct(
8382
*/
8483
public function attempt(array $credentials = [], $remember = false): bool
8584
{
86-
$this->lastUserAttempted = $this->adapter->retrieveByCredentials($credentials);
85+
$this->lastUserAttempted = $this->adapter->findFirstByCredentials($credentials);
8786

8887
if ($this->hasValidCredentials($this->lastUserAttempted, $credentials)) {
8988
$this->login($this->lastUserAttempted, $remember);
@@ -107,7 +106,7 @@ public function user()
107106
$id = $this->session->get($this->getName());
108107

109108
if (!is_null($id)) {
110-
$this->user = $this->adapter->retrieveById($id);
109+
$this->user = $this->adapter->findFirstById($id);
111110
}
112111

113112
if (is_null($this->user) && !is_null($recaller = $this->recaller())) {
@@ -137,7 +136,7 @@ protected function hasValidCredentials($user, array $credentials): bool
137136
*/
138137
public function validate(array $credentials = []): bool
139138
{
140-
$this->lastUserAttempted = $this->adapter->retrieveByCredentials($credentials);
139+
$this->lastUserAttempted = $this->adapter->findFirstByCredentials($credentials);
141140

142141
return $this->hasValidCredentials($this->lastUserAttempted, $credentials);
143142
}
@@ -148,7 +147,7 @@ public function validate(array $credentials = []): bool
148147
*/
149148
protected function userFromRecaller($recaller): ?AuthenticatableInterface
150149
{
151-
$this->viaRemember = ! is_null($user = $this->adapter->retrieveByToken(
150+
$this->viaRemember = ! is_null($user = $this->adapter->findFirstByToken(
152151
$recaller->id(), $recaller->token(), $recaller->userAgent()
153152
));
154153

@@ -226,7 +225,7 @@ public function login(AuthenticatableInterface $user, bool $remember = false): v
226225
*/
227226
public function loginById($id, bool $remember = false)
228227
{
229-
if ( ! is_null($user = $this->adapter->retrieveById($id))) {
228+
if ( ! is_null($user = $this->adapter->findFirstById($id))) {
230229
$this->login($user, $remember);
231230

232231
return $user;

0 commit comments

Comments
 (0)