Passed
Push — master ( cc80b9...1640e1 )
by Divine Niiquaye
12:24
created

RememberMeHandler::getUsersIdCookie()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Biurad opensource projects.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 *
17
 */
18
19
namespace Biurad\Security\Handler;
20
21
use Psr\Http\Message\ServerRequestInterface;
22
use Symfony\Component\HttpFoundation\Cookie;
23
use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider;
24
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
25
use Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface;
26
use Symfony\Component\Security\Core\Authentication\RememberMe\TokenVerifierInterface;
27
use Symfony\Component\Security\Core\Exception\AuthenticationException;
28
use Symfony\Component\Security\Core\Exception\CookieTheftException;
29
use Symfony\Component\Security\Core\Signature\Exception\ExpiredSignatureException;
30
use Symfony\Component\Security\Core\Signature\Exception\InvalidSignatureException;
31
use Symfony\Component\Security\Core\Signature\SignatureHasher;
32
use Symfony\Component\Security\Core\User\UserInterface;
33
use Symfony\Component\Security\Core\User\UserProviderInterface;
34
35
/**
36
 * A remember handler to create and valid a user via a cookie.
37
 *
38
 * @author Divine Niiquaye Ibok <[email protected]>
39
 */
40
class RememberMeHandler
41
{
42
    public const COOKIE_DELIMITER = ':';
43
    public const REMEMBER_ME = '_security.remember_me';
44
    public const USERS_ID = '_remember_user_id';
45
46
    private ?TokenProviderInterface $tokenProvider;
47
    private ?TokenVerifierInterface $tokenVerifier;
48
    private ?SignatureHasher $signatureHasher;
49
    private Cookie $cookie;
50
    private string $secret, $parameterName, $usersIdCookie;
51
52
    public function __construct(
53
        string $secret,
54
        TokenProviderInterface $tokenProvider = null,
55
        TokenVerifierInterface $tokenVerifier = null,
56
        SignatureHasher $signatureHasher = null,
57
        string $requestParameter = '_remember_me',
58
        string $usersIdCookie = '_remember_user_id',
59
        array $options = []
60
    ) {
61
        $this->secret = $secret;
62
        $this->usersIdCookie = $usersIdCookie;
63
        $this->parameterName = $requestParameter;
64
        $this->tokenProvider = $tokenProvider ?? new InMemoryTokenProvider();
65
        $this->tokenVerifier = $tokenVerifier ?? ($this->tokenProvider instanceof TokenVerifierInterface ? $this->tokenProvider : null);
66
        $this->signatureHasher = $signatureHasher;
67
        $this->cookie = new Cookie(
68
            $options['name'] ?? 'REMEMBER_ME',
69
            null,
70
            $options['lifetime'] ?? 31536000,
71
            $options['path'] ?? '/',
72
            $options['domain'] ?? null,
73
            $options['secure'] ?? false,
74
            $options['httponly'] ?? true,
75
            false,
76
            $options['samesite'] ?? null
77
        );
78
    }
79
80
    public function getSecret(): string
81
    {
82
        return $this->secret;
83
    }
84
85
    public function getParameterName(): string
86
    {
87
        return $this->parameterName;
88
    }
89
90
    public function getCookieName(): string
91
    {
92
        return $this->cookie->getName();
93
    }
94
95
    public function getUsersIdCookie(): string
96
    {
97
        return $this->usersIdCookie;
98
    }
99
100
    /**
101
     * Returns the user and for every 2 minutes a new remember me cookie is included.
102
     *
103
     * @return array $user {0: UserInterface, 1: Cookie|null}
104
     */
105
    public function consumeRememberMeCookie(string $rawCookie, UserProviderInterface $userProvider): array
106
    {
107
        [, $identifier, $expires, $value] = self::fromRawCookie($rawCookie);
108
109
        if (!\str_contains($value, ':')) {
110
            throw new AuthenticationException('The cookie is incorrectly formatted.');
111
        }
112
        $user = $userProvider->loadUserByIdentifier($identifier);
113
114
        if (null !== $this->signatureHasher) {
115
            try {
116
                $this->signatureHasher->verifySignatureHash($user, $expires, $value);
117
            } catch (InvalidSignatureException $e) {
118
                throw new AuthenticationException('The cookie\'s hash is invalid.', 0, $e);
119
            } catch (ExpiredSignatureException $e) {
120
                throw new AuthenticationException('The cookie has expired.', 0, $e);
121
            }
122
        } elseif (null !== $this->tokenProvider) {
123
            [$series, $tokenValue] = \explode(':', $value);
124
            $persistentToken = $this->tokenProvider->loadTokenBySeries($series);
125
126
            if (null !== $this->tokenVerifier) {
127
                $isTokenValid = $this->tokenVerifier->verifyToken($persistentToken, $tokenValue);
128
            } else {
129
                $isTokenValid = \hash_equals($persistentToken->getTokenValue(), $tokenValue);
130
            }
131
132
            if (!$isTokenValid) {
133
                throw new CookieTheftException('This token was already used. The account is possibly compromised.');
134
            }
135
136
            if ($persistentToken->getLastUsed()->getTimestamp() + $this->cookie->getExpiresTime() < \time()) {
137
                throw new AuthenticationException('The cookie has expired.');
138
            }
139
140
            // if a token was regenerated less than 2 minutes ago, there is no need to regenerate it
141
            // if multiple concurrent requests reauthenticate a user we do not want to update the token several times
142
            if ($persistentToken->getLastUsed()->getTimestamp() + (60 * 2) < \time()) {
143
                $tokenValue = $this->generateHash();
144
                $tokenLastUsed = new \DateTime();
145
146
                if ($this->tokenVerifier) {
147
                    $this->tokenVerifier->updateExistingToken($persistentToken, $tokenValue, $tokenLastUsed);
148
                }
149
                $this->tokenProvider->updateToken($series, $tokenValue, $tokenLastUsed);
150
151
                return [$user, $this->createRememberMeCookie($user, $series . ':' . $tokenValue)];
152
            }
153
        } else {
154
            throw new \LogicException(\sprintf('Expected one of %s or %s class.', TokenProviderInterface::class, SignatureHasher::class));
155
        }
156
157
        return [$user, null];
158
    }
159
160
    public function createRememberMeCookie(UserInterface $user, string $value = null): Cookie
161
    {
162
        $expires = \time() + $this->cookie->getExpiresTime();
163
        $class = \get_class($user);
164
        $identifier = $user->getUserIdentifier();
165
166
        if (null !== $this->signatureHasher) {
167
            $value = $this->signatureHasher->computeSignatureHash($user, $expires);
168
        } elseif (null === $value) {
169
            if (null === $this->tokenProvider) {
170
                throw new \LogicException(\sprintf('Expected one of %s or %s class.', TokenProviderInterface::class, SignatureHasher::class));
171
            }
172
173
            $series = \base64_encode(\random_bytes(64));
174
            $tokenValue = $this->generateHash();
175
            $this->tokenProvider->createNewToken($token = new PersistentToken($class, $identifier, $series, $tokenValue, new \DateTime()));
176
            $value = $token->getSeries() . ':' . $token->getTokenValue();
177
        }
178
179
        $cookie = clone $this->cookie
180
            ->withValue(\base64_encode(\implode(self::COOKIE_DELIMITER, [$class, \base64_encode($identifier), $expires, $value])))
181
            ->withExpires($expires);
182
183
        return $this->setCookieName($cookie, $user->getUserIdentifier());
184
    }
185
186
    /**
187
     * @return array<int,Cookie>
188
     */
189
    public function clearRememberMeCookies(ServerRequestInterface $request): array
190
    {
191
        $cookies = [];
192
        $identifiers = \explode('|', \urldecode($request->getCookieParams()[$this->usersIdCookie] ?? '')) ?: [];
193
194
        foreach ($identifiers as $identifier) {
195
            $clearCookie = $this->cookie;
196
197
            if (null === $cookie = $request->getCookieParams()[$clearCookie->getName() . $identifier] ?? null) {
198
                continue;
199
            }
200
201
            if (null !== $this->tokenProvider) {
202
                $rememberMeDetails = self::fromRawCookie($cookie);
203
                [$series, ] = \explode(':', $rememberMeDetails[3]);
204
                $this->tokenProvider->deleteTokenBySeries($series);
205
            }
206
207
            $cookies[] = $this->setCookieName($clearCookie->withExpires(1)->withValue(null), $identifier);
208
        }
209
210
        return $cookies;
211
    }
212
213
    private static function fromRawCookie(string $rawCookie): array
214
    {
215
        $cookieParts = \explode(self::COOKIE_DELIMITER, \base64_decode($rawCookie), 4);
216
217
        if (false === $cookieParts[1] = \base64_decode($cookieParts[1], true)) {
218
            throw new AuthenticationException('The user identifier contains a character from outside the base64 alphabet.');
219
        }
220
221
        if (4 !== \count($cookieParts)) {
222
            throw new AuthenticationException('The cookie contains invalid data.');
223
        }
224
225
        return $cookieParts;
226
    }
227
228
    private function setCookieName(Cookie $cookie, string $userId): Cookie
229
    {
230
        return \Closure::bind(function (Cookie $cookie) use ($userId) {
231
            $cookie->name .= $userId;
0 ignored issues
show
Bug introduced by
The property name is declared protected in Symfony\Component\HttpFoundation\Cookie and cannot be accessed from this context.
Loading history...
232
233
            return $cookie;
234
        }, $cookie, $cookie)($cookie);
235
    }
236
237
    private function generateHash(): string
238
    {
239
        return hash_hmac('sha256', \base64_encode(\random_bytes(64)), $this->secret);
240
    }
241
}
242