forked from yiisoft/yii-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoLoginMiddleware.php
81 lines (67 loc) · 2.27 KB
/
AutoLoginMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace Yiisoft\Yii\Web\User;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Yiisoft\Auth\IdentityRepositoryInterface;
use Yiisoft\Yii\Web\User\User;
/**
* AutoLoginMiddleware automatically logs user in based on "remember me" cookie
*/
final class AutoLoginMiddleware implements MiddlewareInterface
{
private User $user;
private IdentityRepositoryInterface $identityRepository;
public function __construct(
User $user,
IdentityRepositoryInterface $identityRepository
) {
$this->user = $user;
$this->identityRepository = $identityRepository;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if (!$this->userIsAuth($request)) {
throw new \Exception('Error authentication');
}
return $handler->handle($request);
}
/**
* Parse and determines if an identity cookie has a valid format.
* @param ServerRequestInterface $request Request to handle
* @return array Returns an array of 'identity' and 'duration' if valid, otherwise [].
*/
private function parseCredentials(ServerRequestInterface $request): array
{
try {
$cookies = $request->getCookieParams();
$data = json_decode($cookies['remember'], true, 512);
} catch (\Exception $e) {
return [];
}
if (!is_array($data) || count($data) !== 3) {
return [];
}
[$id, , $duration] = $data;
$identity = $this->identityRepository->findIdentity($id);
if ($identity === null) {
return [];
}
return ['identity' => $identity, 'duration' => $duration];
}
/**
* Check if the user can be authenticated
* @param ServerRequestInterface $request Request to handle
* @return bool
*/
private function userIsAuth(ServerRequestInterface $request): bool
{
$data = $this->parseCredentials($request);
if ($data === []) {
return false;
}
return $this->user->login($data['identity'], $data['duration']);
}
}