Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
cookiesessionhandler.php
1<?php
2
4
12
13class CookieSessionHandler implements \SessionHandlerInterface
14{
16 private $request;
18 private $response;
20 private $lifetime;
21
22 public function __construct(int $lifetime, Request $request = null)
23 {
24 $this->request = $request ?: Context::getCurrent()->getRequest();
25 $this->lifetime = $lifetime;
26 }
27
28 public function close(): bool
29 {
30 return true;
31 }
32
33 private function setSecureAttribute(Cookie $cookie): Cookie
34 {
35 $context = Context::getCurrent();
36 if (!$context)
37 {
38 return $cookie;
39 }
40
41 $request = $context->getRequest();
42 $secure = (Option::get('main', 'use_secure_password_cookies', 'N') === 'Y' && $request->isHttps());
43 $cookie
44 ->setHttpOnly(true)
45 ->setSecure($secure)
46 ;
47
48 return $cookie;
49 }
50
51 public function destroy($sessionId): bool
52 {
53 $cookie = new Cookie($sessionId, null, -2628000);
54 $cookie = $this->setSecureAttribute($cookie);
55
56 $this->getResponse()->addCookie($cookie);
57
58 return true;
59 }
60
61 public function gc($maxlifetime): int
62 {
63 return 0;
64 }
65
66 public function open($savePath, $name): bool
67 {
68 return true;
69 }
70
71 #[\ReturnTypeWillChange]
72 public function read($sessionId)
73 {
74 $value = $this->request->getCookie($sessionId) ?: '';
75 if (!$value)
76 {
77 return '';
78 }
79
80 try
81 {
82 $decoded = Json::decode($value);
83 }
84 catch (ArgumentException $exception)
85 {
86 return '';
87 }
88
89 if (is_array($decoded))
90 {
91 if (!isset($decoded['expires']))
92 {
93 return $decoded['data'];
94 }
95 if (time() <= $decoded['expires'])
96 {
97 return $decoded['data'];
98 }
99 }
100
101 return '';
102 }
103
104 public function write($sessionId, $sessionData): bool
105 {
106 $expires = $this->lifetime ? (time() + $this->lifetime) : 0;
107
108 $value = Json::encode([
109 'data' => $sessionData,
110 'createdAt' => time(),
111 'expires' => $expires?: null,
112 ]);
113
114 $cookie = new CryptoCookie($sessionId, $value, $expires);
115 $cookie = $this->setSecureAttribute($cookie);
116
117 $this->getResponse()->addCookie($cookie);
118
119 return true;
120 }
121
125 public function getResponse(): \Bitrix\Main\HttpResponse
126 {
127 return $this->response?: Context::getCurrent()->getResponse();
128 }
129
134 public function setResponse($response)
135 {
136 $this->response = $response;
137
138 return $this;
139 }
140}
static getCurrent()
Definition context.php:241
static decode($data)
Definition json.php:53
static encode($data, $options=null)
Definition json.php:24