1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Jasny\Auth\Confirmation; |
||
6 | |||
7 | use Carbon\CarbonImmutable; |
||
8 | use Hashids\Hashids; |
||
9 | use Jasny\Auth\UserInterface as User; |
||
10 | use Jasny\Auth\StorageInterface as Storage; |
||
11 | use Jasny\Immutable; |
||
12 | use Psr\Log\LoggerInterface as Logger; |
||
13 | use Psr\Log\NullLogger; |
||
14 | |||
15 | /** |
||
16 | * Generate and verify confirmation tokens using the Hashids library. |
||
17 | * |
||
18 | * @link http://hashids.org/php/ |
||
19 | */ |
||
20 | class HashidsConfirmation implements ConfirmationInterface |
||
21 | { |
||
22 | use Immutable\With; |
||
23 | |||
24 | protected string $subject; |
||
25 | protected string $secret; |
||
26 | |||
27 | protected \Closure $createHashids; |
||
28 | protected Storage $storage; |
||
29 | |||
30 | /** @var \Closure&callable(string $uid):(string|false) */ |
||
31 | protected \Closure $encodeUid; |
||
32 | /** @var \Closure&callable(string $uid):(string|false) */ |
||
33 | protected \Closure $decodeUid; |
||
34 | |||
35 | protected Logger $logger; |
||
36 | |||
37 | /** |
||
38 | * HashidsConfirmation constructor. |
||
39 | * |
||
40 | * @param string $secret |
||
41 | * @param callable(string):Hashids $createHashids |
||
42 | */ |
||
43 | 9 | public function __construct(string $secret, ?callable $createHashids = null) |
|
44 | { |
||
45 | 9 | $this->secret = $secret; |
|
46 | |||
47 | 9 | $this->createHashids = $createHashids !== null |
|
48 | 8 | ? \Closure::fromCallable($createHashids) |
|
49 | 1 | : fn(string $salt) => new Hashids($salt); |
|
50 | |||
51 | 9 | $this->encodeUid = fn(string $uid) => unpack('H*', $uid)[1]; |
|
52 | 9 | $this->decodeUid = fn(string $hex) => pack('H*', $hex); |
|
53 | |||
54 | 9 | $this->logger = new NullLogger(); |
|
55 | 9 | } |
|
56 | |||
57 | /** |
||
58 | * Get copy with storage service. |
||
59 | * |
||
60 | * @param Storage $storage |
||
61 | * @return static |
||
62 | */ |
||
63 | 9 | public function withStorage(Storage $storage): self |
|
64 | { |
||
65 | 9 | return $this->withProperty('storage', $storage); |
|
66 | } |
||
67 | |||
68 | /** |
||
69 | * Get a copy with custom methods to encode/decode the uid. |
||
70 | * |
||
71 | * @param callable $encode |
||
72 | * @param callable $decode |
||
73 | * @return static |
||
74 | */ |
||
75 | 2 | public function withUidEncoded(callable $encode, callable $decode): self |
|
76 | { |
||
77 | return $this |
||
78 | 2 | ->withProperty('encodeUid', \Closure::fromCallable($encode)) |
|
79 | 2 | ->withProperty('decodeUid', \Closure::fromCallable($decode)); |
|
80 | } |
||
81 | |||
82 | /** |
||
83 | * Get copy with logger. |
||
84 | * |
||
85 | * @param Logger $logger |
||
86 | * @return static |
||
87 | */ |
||
88 | 6 | public function withLogger(Logger $logger): self |
|
89 | { |
||
90 | 6 | return $this->withProperty('logger', $logger); |
|
91 | } |
||
92 | |||
93 | /** |
||
94 | * Create a copy of this service with a specific subject. |
||
95 | * |
||
96 | * @param string $subject |
||
97 | * @return static |
||
98 | */ |
||
99 | 9 | public function withSubject(string $subject): self |
|
100 | { |
||
101 | 9 | return $this->withProperty('subject', $subject); |
|
102 | } |
||
103 | |||
104 | |||
105 | /** |
||
106 | * Generate a confirmation token. |
||
107 | */ |
||
108 | 1 | public function getToken(User $user, \DateTimeInterface $expire): string |
|
109 | { |
||
110 | 1 | $uidHex = $this->encodeUid($user->getAuthId()); |
|
111 | $expireHex = CarbonImmutable::instance($expire)->utc()->format('YmdHis'); |
||
112 | $checksum = $this->calcChecksum($user, $expire); |
||
113 | |||
114 | return $this->createHashids()->encodeHex($checksum . $expireHex . $uidHex); |
||
115 | } |
||
116 | |||
117 | |||
118 | /** |
||
119 | * Get user by confirmation token. |
||
120 | * |
||
121 | * @param string $token Confirmation token |
||
122 | * @return User |
||
123 | * @throws InvalidTokenException |
||
124 | */ |
||
125 | 6 | public function from(string $token): User |
|
126 | { |
||
127 | 6 | $hex = $this->createHashids()->decodeHex($token); |
|
128 | 6 | $info = $this->extractHex($hex); |
|
129 | |||
130 | 6 | $context = ['subject' => $this->subject, 'token' => self::partialToken($token)]; |
|
131 | |||
132 | 6 | if ($info === null) { |
|
133 | 3 | $this->logger->debug('Invalid confirmation token', $context); |
|
134 | 3 | throw new InvalidTokenException("Invalid confirmation token"); |
|
135 | } |
||
136 | |||
137 | /** @var CarbonImmutable $expire */ |
||
138 | 3 | ['checksum' => $checksum, 'expire' => $expire, 'uid' => $uid] = $info; |
|
139 | 3 | $context += ['user' => $uid, 'expire' => $expire->format('c')]; |
|
140 | |||
141 | 3 | $user = $this->fetchUserFromStorage($uid, $context); |
|
142 | 2 | $this->verifyChecksum($checksum, $user, $expire, $context); |
|
143 | $this->verifyNotExpired($expire, $context); |
||
144 | |||
145 | $this->logger->info('Verified confirmation token', $context); |
||
146 | |||
147 | return $user; |
||
148 | } |
||
149 | |||
150 | |||
151 | /** |
||
152 | * Extract uid, expire date and checksum from hex. |
||
153 | * |
||
154 | * @param string $hex |
||
155 | * @return null|array{checksum:string,expire:CarbonImmutable,uid:string} |
||
156 | */ |
||
157 | 6 | protected function extractHex(string $hex): ?array |
|
158 | { |
||
159 | 6 | if (strlen($hex) <= 78) { |
|
160 | 1 | return null; |
|
161 | } |
||
162 | |||
163 | 5 | $checksum = substr($hex, 0, 64); |
|
164 | 5 | $expireHex = substr($hex, 64, 14); |
|
165 | 5 | $uidHex = substr($hex, 78); |
|
166 | |||
167 | try { |
||
168 | 5 | $uid = $this->decodeUid($uidHex); |
|
169 | |||
170 | /** @var CarbonImmutable $expire */ |
||
171 | 4 | $expire = CarbonImmutable::createFromFormat('YmdHis', $expireHex, '+00:00'); |
|
172 | 2 | } catch (\Exception $exception) { |
|
173 | 2 | return null; |
|
174 | } |
||
175 | |||
176 | 3 | return ['checksum' => $checksum, 'expire' => $expire, 'uid' => $uid]; |
|
177 | } |
||
178 | |||
179 | /** |
||
180 | * Encode the uid to a hex value. |
||
181 | * |
||
182 | * @param string $uid |
||
183 | * @return string |
||
184 | */ |
||
185 | 1 | protected function encodeUid(string $uid): string |
|
186 | { |
||
187 | 1 | $hex = ($this->encodeUid)($uid); |
|
188 | |||
189 | 1 | if ($hex === false) { |
|
190 | 1 | throw new \RuntimeException("Failed to encode uid"); |
|
191 | } |
||
192 | |||
193 | return $hex; |
||
194 | } |
||
195 | |||
196 | /** |
||
197 | * Decode the uid to a hex value. |
||
198 | * |
||
199 | * @param string $hex |
||
200 | * @return string |
||
201 | */ |
||
202 | 5 | protected function decodeUid(string $hex): string |
|
203 | { |
||
204 | 5 | $uid = ($this->decodeUid)($hex); |
|
205 | |||
206 | 5 | if ($uid === false) { |
|
207 | 1 | throw new \RuntimeException("Failed to decode uid"); |
|
208 | } |
||
209 | |||
210 | 4 | return $uid; |
|
211 | } |
||
212 | |||
213 | /** |
||
214 | * Fetch user from storage by uid. |
||
215 | * |
||
216 | * @param string $uid |
||
217 | * @param string[] $context |
||
218 | * @return User |
||
219 | * @throws InvalidTokenException |
||
220 | */ |
||
221 | 3 | protected function fetchUserFromStorage(string $uid, array $context): User |
|
222 | { |
||
223 | 3 | $user = $this->storage->fetchUserById($uid); |
|
224 | |||
225 | 3 | if ($user === null) { |
|
226 | 1 | $this->logger->debug('Invalid confirmation token: user not available', $context); |
|
227 | 1 | throw new InvalidTokenException("Token has been revoked"); |
|
228 | } |
||
229 | |||
230 | 2 | return $user; |
|
231 | } |
||
232 | |||
233 | /** |
||
234 | * Check that the checksum from the token matches the expected checksum. |
||
235 | * |
||
236 | * @param string $checksum |
||
237 | * @param User $user |
||
238 | * @param CarbonImmutable $expire |
||
239 | * @param string[] $context |
||
240 | * @throws InvalidTokenException |
||
241 | */ |
||
242 | 2 | protected function verifyChecksum(string $checksum, User $user, CarbonImmutable $expire, array $context): void |
|
243 | { |
||
244 | 2 | $expected = $this->calcChecksum($user, $expire); |
|
245 | 2 | $expectedOld = $this->calcOldChecksum($user, $expire); |
|
246 | |||
247 | if ($checksum === $expected || $checksum === $expectedOld) { |
||
248 | return; |
||
249 | } |
||
250 | |||
251 | $this->logger->debug('Invalid confirmation token: bad checksum', $context); |
||
252 | throw new InvalidTokenException("Token has been revoked"); |
||
253 | } |
||
254 | |||
255 | /** |
||
256 | * Check that the token isn't expired. |
||
257 | * |
||
258 | * @param CarbonImmutable $expire |
||
259 | * @param string[] $context |
||
260 | * @throws InvalidTokenException |
||
261 | */ |
||
262 | protected function verifyNotExpired(CarbonImmutable $expire, array $context): void |
||
263 | { |
||
264 | if (!$expire->isPast()) { |
||
265 | return; |
||
266 | } |
||
267 | |||
268 | $this->logger->debug('Expired confirmation token', $context); |
||
269 | throw new InvalidTokenException("Token is expired"); |
||
270 | } |
||
271 | |||
272 | |||
273 | /** |
||
274 | * Calculate confirmation checksum. |
||
275 | */ |
||
276 | 2 | protected function calcChecksum(User $user, \DateTimeInterface $expire): string |
|
277 | { |
||
278 | $parts = [ |
||
279 | 2 | CarbonImmutable::instance($expire)->utc()->format('YmdHis'), |
|
280 | 2 | $user->getAuthId(), |
|
281 | 2 | $user->getAuthChecksum(), |
|
282 | ]; |
||
283 | |||
284 | 2 | return hash_hmac('sha256', join("\0", $parts), $this->secret); |
|
285 | } |
||
286 | |||
287 | /** |
||
288 | * Calculate confirmation checksum, before switching to hmac. |
||
289 | * Temporary so existing confirmation tokens will continue working. Will be removed. |
||
290 | * |
||
291 | * @deprecated |
||
292 | */ |
||
293 | 2 | protected function calcOldChecksum(User $user, \DateTimeInterface $expire): string |
|
294 | { |
||
295 | $parts = [ |
||
296 | 2 | CarbonImmutable::instance($expire)->utc()->format('YmdHis'), |
|
297 | 2 | $user->getAuthId(), |
|
298 | 2 | $user->getAuthChecksum(), |
|
299 | 2 | $this->secret, |
|
300 | ]; |
||
301 | |||
302 | 2 | return hash_hmac('sha256', join("\0", $parts)); |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
303 | } |
||
304 | |||
305 | |||
306 | /** |
||
307 | * Create a hashids service. |
||
308 | */ |
||
309 | 8 | public function createHashids(): Hashids |
|
310 | { |
||
311 | 8 | $salt = hash('sha256', $this->subject . $this->secret, true); |
|
312 | |||
313 | 8 | return ($this->createHashids)($salt); |
|
314 | } |
||
315 | |||
316 | /** |
||
317 | * Create a partial token for logging. |
||
318 | * |
||
319 | * @param string $token |
||
320 | * @return string |
||
321 | */ |
||
322 | 6 | protected static function partialToken(string $token): string |
|
323 | { |
||
324 | 6 | return substr($token, 0, 8) . '...'; |
|
325 | } |
||
326 | } |
||
327 |