This repository has been archived by the owner on Jun 29, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
AutoLogin.php
64 lines (54 loc) · 1.6 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
<?php
declare(strict_types=1);
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
*/
final 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.
*/
public function addCookie(AutoLoginIdentityInterface $identity, ResponseInterface $response): ResponseInterface
{
$data = json_encode([
$identity->getId(),
$identity->getAutoLoginKey()
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return (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): ResponseInterface
{
return (new Cookie($this->cookieName))
->expire()
->addToResponse($response);
}
public function getCookieName(): string
{
return $this->cookieName;
}
}