-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathResetPasswordHelper.php
200 lines (159 loc) · 6.74 KB
/
ResetPasswordHelper.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
<?php
/*
* This file is part of the SymfonyCasts ResetPasswordBundle package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SymfonyCasts\Bundle\ResetPassword;
use SymfonyCasts\Bundle\ResetPassword\Exception\ExpiredResetPasswordTokenException;
use SymfonyCasts\Bundle\ResetPassword\Exception\InvalidResetPasswordTokenException;
use SymfonyCasts\Bundle\ResetPassword\Exception\TooManyPasswordRequestsException;
use SymfonyCasts\Bundle\ResetPassword\Generator\ResetPasswordTokenGenerator;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordToken;
use SymfonyCasts\Bundle\ResetPassword\Persistence\ResetPasswordRequestRepositoryInterface;
use SymfonyCasts\Bundle\ResetPassword\Util\ResetPasswordCleaner;
/**
* @author Jesse Rushlow <jr@rushlow.dev>
* @author Ryan Weaver <ryan@symfonycasts.com>
*
* @final
*/
class ResetPasswordHelper implements ResetPasswordHelperInterface
{
/**
* The first 20 characters of the token are a "selector".
*/
private const SELECTOR_LENGTH = 20;
private $tokenGenerator;
private $resetPasswordCleaner;
private $repository;
/**
* @var int How long a token is valid in seconds
*/
private $resetRequestLifetime;
/**
* @var int Another password reset cannot be made faster than this throttle time in seconds
*/
private $requestThrottleTime;
public function __construct(ResetPasswordTokenGenerator $generator, ResetPasswordCleaner $cleaner, ResetPasswordRequestRepositoryInterface $repository, int $resetRequestLifetime, int $requestThrottleTime)
{
$this->tokenGenerator = $generator;
$this->resetPasswordCleaner = $cleaner;
$this->repository = $repository;
$this->resetRequestLifetime = $resetRequestLifetime;
$this->requestThrottleTime = $requestThrottleTime;
}
/**
* {@inheritdoc}
*
* Some of the cryptographic strategies were taken from
* https://paragonie.com/blog/2017/02/split-tokens-token-based-authentication-protocols-without-side-channels
*
* @throws TooManyPasswordRequestsException
*/
public function generateResetToken(object $user, ?int $resetRequestLifetime = null): ResetPasswordToken
{
$this->resetPasswordCleaner->handleGarbageCollection();
if ($availableAt = $this->hasUserHitThrottling($user)) {
throw new TooManyPasswordRequestsException($availableAt);
}
$resetRequestLifetime = $resetRequestLifetime ?? $this->resetRequestLifetime;
$expiresAt = new \DateTimeImmutable(\sprintf('+%d seconds', $resetRequestLifetime));
$generatedAt = ($expiresAt->getTimestamp() - $resetRequestLifetime);
$tokenComponents = $this->tokenGenerator->createToken($expiresAt, $this->repository->getUserIdentifier($user));
$passwordResetRequest = $this->repository->createResetPasswordRequest(
$user,
$expiresAt,
$tokenComponents->getSelector(),
$tokenComponents->getHashedToken()
);
$this->repository->persistResetPasswordRequest($passwordResetRequest);
// final "public" token is the selector + non-hashed verifier token
return new ResetPasswordToken(
$tokenComponents->getPublicToken(),
$expiresAt,
$generatedAt
);
}
/**
* @throws ExpiredResetPasswordTokenException
* @throws InvalidResetPasswordTokenException
*/
public function validateTokenAndFetchUser(string $fullToken): object
{
$this->resetPasswordCleaner->handleGarbageCollection();
if (40 !== \strlen($fullToken)) {
throw new InvalidResetPasswordTokenException();
}
$resetRequest = $this->findResetPasswordRequest($fullToken);
if (null === $resetRequest) {
throw new InvalidResetPasswordTokenException();
}
if ($resetRequest->isExpired()) {
throw new ExpiredResetPasswordTokenException();
}
$user = $resetRequest->getUser();
$hashedVerifierToken = $this->tokenGenerator->createToken(
$resetRequest->getExpiresAt(),
$this->repository->getUserIdentifier($user),
substr($fullToken, self::SELECTOR_LENGTH)
);
if (false === hash_equals($resetRequest->getHashedToken(), $hashedVerifierToken->getHashedToken())) {
throw new InvalidResetPasswordTokenException();
}
return $user;
}
/**
* @throws InvalidResetPasswordTokenException
*/
public function removeResetRequest(string $fullToken): void
{
$request = $this->findResetPasswordRequest($fullToken);
if (null === $request) {
throw new InvalidResetPasswordTokenException();
}
$this->repository->removeResetPasswordRequest($request);
}
public function getTokenLifetime(): int
{
return $this->resetRequestLifetime;
}
/**
* Generate a fake reset token.
*
* Use this to generate a fake token so that you can, for example, show a
* "reset confirmation email sent" page that includes a valid "expiration date",
* even if the email was not actually found (and so, a true ResetPasswordToken
* was not actually created).
*
* This method should not be used when timing attacks are a concern.
*/
public function generateFakeResetToken(?int $resetRequestLifetime = null): ResetPasswordToken
{
$resetRequestLifetime = $resetRequestLifetime ?? $this->resetRequestLifetime;
$expiresAt = new \DateTimeImmutable(\sprintf('+%d seconds', $resetRequestLifetime));
$generatedAt = ($expiresAt->getTimestamp() - $resetRequestLifetime);
$fakeToken = bin2hex(random_bytes(16));
return new ResetPasswordToken($fakeToken, $expiresAt, $generatedAt);
}
private function findResetPasswordRequest(string $token): ?ResetPasswordRequestInterface
{
$selector = substr($token, 0, self::SELECTOR_LENGTH);
return $this->repository->findResetPasswordRequest($selector);
}
private function hasUserHitThrottling(object $user): ?\DateTimeInterface
{
/** @var \DateTime|\DateTimeImmutable|null $lastRequestDate */
$lastRequestDate = $this->repository->getMostRecentNonExpiredRequestDate($user);
if (null === $lastRequestDate) {
return null;
}
$availableAt = (clone $lastRequestDate)->add(new \DateInterval("PT{$this->requestThrottleTime}S"));
if ($availableAt > new \DateTime('now')) {
return $availableAt;
}
return null;
}
}