Passed
Push — master ( 3c8625...c93166 )
by Divine Niiquaye
12:46
created

RememberMeHandler::getCookieName()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 1
b 0
f 0
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;
51
    private string $parameterName;
52
53
    public function __construct(
54
        string $secret,
55
        TokenProviderInterface $tokenProvider = null,
56
        TokenVerifierInterface $tokenVerifier = null,
57
        SignatureHasher $signatureHasher = null,
58
        string $requestParameter = '_remember_me',
59
        array $options = []
60
    ) {
61
        $this->secret = $secret;
62
        $this->parameterName = $requestParameter;
63
        $this->tokenProvider = $tokenProvider ?? new InMemoryTokenProvider();
64
        $this->tokenVerifier = $tokenVerifier ?? ($this->tokenProvider instanceof TokenVerifierInterface ? $this->tokenProvider : null);
65
        $this->signatureHasher = $signatureHasher;
66
        $this->cookie = new Cookie(
67
            $options['name'] ?? 'REMEMBER_ME',
68
            null,
69
            $options['lifetime'] ?? 31536000,
70
            $options['path'] ?? '/',
71
            $options['domain'] ?? null,
72
            $options['secure'] ?? false,
73
            $options['httponly'] ?? true,
74
            false,
75
            $options['samesite'] ?? null
76
        );
77
    }
78
79
    public function getSecret(): string
80
    {
81
        return $this->secret;
82
    }
83
84
    public function getParameterName(): string
85
    {
86
        return $this->parameterName;
87
    }
88
89
    public function getCookieName(): string
90
    {
91
        return $this->cookie->getName();
92
    }
93
94
    /**
95
     * Returns the user and for every 2 minutes a new remember me cookie is included.
96
     *
97
     * @return UserInterface|array $user
98
     */
99
    public function consumeRememberMeCookie(string $rawCookie, UserProviderInterface $userProvider): array
100
    {
101
        [, $identifier, $expires, $value] = self::fromRawCookie($rawCookie);
102
103
        if (!\str_contains($value, ':')) {
104
            throw new AuthenticationException('The cookie is incorrectly formatted.');
105
        }
106
        $user = $userProvider->loadUserByIdentifier($identifier);
107
108
        if (null !== $this->signatureHasher) {
109
            try {
110
                $this->signatureHasher->verifySignatureHash($user, $expires, $value);
111
            } catch (InvalidSignatureException $e) {
112
                throw new AuthenticationException('The cookie\'s hash is invalid.', 0, $e);
113
            } catch (ExpiredSignatureException $e) {
114
                throw new AuthenticationException('The cookie has expired.', 0, $e);
115
            }
116
        } elseif (null !== $this->tokenProvider) {
117
            [$series, $tokenValue] = \explode(':', $value);
118
            $persistentToken = $this->tokenProvider->loadTokenBySeries($series);
119
120
            if (null !== $this->tokenVerifier) {
121
                $isTokenValid = $this->tokenVerifier->verifyToken($persistentToken, $tokenValue);
122
            } else {
123
                $isTokenValid = \hash_equals($persistentToken->getTokenValue(), $tokenValue);
124
            }
125
126
            if (!$isTokenValid) {
127
                throw new CookieTheftException('This token was already used. The account is possibly compromised.');
128
            }
129
130
            if ($persistentToken->getLastUsed()->getTimestamp() + $this->cookie->getExpiresTime() < \time()) {
131
                throw new AuthenticationException('The cookie has expired.');
132
            }
133
134
            // if a token was regenerated less than 2 minutes ago, there is no need to regenerate it
135
            // if multiple concurrent requests reauthenticate a user we do not want to update the token several times
136
            if ($persistentToken->getLastUsed()->getTimestamp() + (60 * 2) < \time()) {
137
                $tokenValue = $this->generateHash();
138
                $tokenLastUsed = new \DateTime();
139
140
                if ($this->tokenVerifier) {
141
                    $this->tokenVerifier->updateExistingToken($persistentToken, $tokenValue, $tokenLastUsed);
142
                }
143
                $this->tokenProvider->updateToken($series, $tokenValue, $tokenLastUsed);
144
145
                return [$user, $this->createRememberMeCookie($user, $series . ':' . $tokenValue)];
146
            }
147
        } else {
148
            throw new \LogicException(\sprintf('Expected one of %s or %s class.', TokenProviderInterface::class, SignatureHasher::class));
149
        }
150
151
        return [$user, null];
152
    }
153
154
    public function createRememberMeCookie(UserInterface $user, string $value = null): Cookie
155
    {
156
        $expires = \time() + $this->cookie->getExpiresTime();
157
        $class = \get_class($user);
158
        $identifier = $user->getUserIdentifier();
159
160
        if (null !== $this->signatureHasher) {
161
            $value = $this->signatureHasher->computeSignatureHash($user, $expires);
162
        } elseif (null === $value) {
163
            if (null === $this->tokenProvider) {
164
                throw new \LogicException(\sprintf('Expected one of %s or %s class.', TokenProviderInterface::class, SignatureHasher::class));
165
            }
166
167
            $series = \base64_encode(\random_bytes(64));
168
            $tokenValue = $this->generateHash();
169
            $this->tokenProvider->createNewToken($token = new PersistentToken($class, $identifier, $series, $tokenValue, new \DateTime()));
170
            $value = $token->getSeries() . ':' . $token->getTokenValue();
171
        }
172
173
        $cookie = clone $this->cookie
174
            ->withValue(\base64_encode(\implode(self::COOKIE_DELIMITER, [$class, \base64_encode($identifier), $expires, $value])))
175
            ->withExpires($expires);
176
177
        return $this->setCookieName($cookie, $user->getUserIdentifier());
178
    }
179
180
    /**
181
     * @return array<int,Cookie>
182
     */
183
    public function clearRememberMeCookies(ServerRequestInterface $request): array
184
    {
185
        $cookies = [];
186
        $identifiers = urldecode($request->getCookieParams()[self::USERS_ID] ?? '');
187
188
        if (\str_contains($identifiers, '|')) {
189
            $identifiers = \explode('|', $identifiers);
190
        }
191
192
        foreach ((array) $identifiers as $identifier) {
193
            $clearCookie = $this->cookie;
194
195
            if (null === $cookie = $request->getCookieParams()[$clearCookie->getName() . $identifier] ?? null) {
196
                continue;
197
            }
198
199
            if (null !== $this->tokenProvider) {
200
                $rememberMeDetails = self::fromRawCookie($cookie);
201
                [$series, ] = \explode(':', $rememberMeDetails[3]);
202
                $this->tokenProvider->deleteTokenBySeries($series);
203
            }
204
205
            $cookies[] = $this->setCookieName($clearCookie->withExpires(1)->withValue(null), $identifier);
206
        }
207
208
        return $cookies;
209
    }
210
211
    private static function fromRawCookie(string $rawCookie): array
212
    {
213
        $cookieParts = \explode(self::COOKIE_DELIMITER, \base64_decode($rawCookie), 4);
214
215
        if (false === $cookieParts[1] = \base64_decode($cookieParts[1], true)) {
216
            throw new AuthenticationException('The user identifier contains a character from outside the base64 alphabet.');
217
        }
218
219
        if (4 !== \count($cookieParts)) {
220
            throw new AuthenticationException('The cookie contains invalid data.');
221
        }
222
223
        return $cookieParts;
224
    }
225
226
    private function setCookieName(Cookie $cookie, string $userId): Cookie
227
    {
228
        return \Closure::bind(function (Cookie $cookie) use ($userId) {
229
            $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...
230
231
            return $cookie;
232
        }, $cookie, $cookie)($cookie);
233
    }
234
235
    private function generateHash(): string
236
    {
237
        return hash_hmac('sha256', \base64_encode(\random_bytes(64)), $this->secret);
238
    }
239
}
240