forked from yiisoft/yii-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoLogin.php
66 lines (56 loc) · 1.65 KB
/
AutoLogin.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
<?php
namespace Yiisoft\Yii\Web\User;
use DateInterval;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Yii\Web\Cookie;
/**
* The service is used to send or remove auto-login cookie.
*
* @see AutoLoginIdentityInterface
* @see AutoLoginMiddleware
*/
class AutoLogin
{
private string $cookieName = 'autoLogin';
private DateInterval $duration;
public function __construct(DateInterval $duration)
{
$this->duration = $duration;
}
public function withCookieName(string $name): self
{
$new = clone $this;
$new->cookieName = $name;
return $new;
}
/**
* Add auto-login cookie to response so the user is logged in automatically based on cookie even if session
* is expired.
*
* @param AutoLoginIdentityInterface $identity
* @param ResponseInterface $response Response to handle
*/
public function addCookie(AutoLoginIdentityInterface $identity, ResponseInterface $response): void
{
$data = json_encode([
$identity->getId(),
$identity->getAutoLoginKey()
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
(new Cookie($this->cookieName, $data))
->withMaxAge($this->duration)
->addToResponse($response);
}
/**
* Expire auto-login cookie so user is not logged in automatically anymore.
*/
public function expireCookie(ResponseInterface $response): void
{
(new Cookie($this->cookieName))
->expire()
->addToResponse($response);
}
public function getCookieName(): string
{
return $this->cookieName;
}
}