|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of the Phalcon API. |
| 5 | + * |
| 6 | + * (c) Phalcon Team <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view |
| 9 | + * the LICENSE file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace Phalcon\Api\Domain\Components\Cache; |
| 15 | + |
| 16 | +use DateTimeImmutable; |
| 17 | +use Phalcon\Api\Domain\Components\Constants\Dates; |
| 18 | +use Phalcon\Api\Domain\Components\DataSource\User\UserTransport; |
| 19 | +use Phalcon\Api\Domain\Components\Env\EnvManager; |
| 20 | +use Phalcon\Cache\Cache as PhalconCache; |
| 21 | +use Psr\SimpleCache\InvalidArgumentException; |
| 22 | + |
| 23 | +use function sha1; |
| 24 | + |
| 25 | +class Cache extends PhalconCache |
| 26 | +{ |
| 27 | + /** @var int */ |
| 28 | + public const CACHE_LIFETIME_DAY = 86400; |
| 29 | + /** @var int */ |
| 30 | + public const CACHE_LIFETIME_HOUR = 3600; |
| 31 | + /** |
| 32 | + * Cache Timeouts |
| 33 | + */ |
| 34 | + /** @var int */ |
| 35 | + public const CACHE_LIFETIME_MINUTE = 60; |
| 36 | + /** @var int */ |
| 37 | + public const CACHE_LIFETIME_MONTH = 2592000; |
| 38 | + /** |
| 39 | + * Default token expiry - 4 hours |
| 40 | + */ |
| 41 | + /** @var int */ |
| 42 | + public const CACHE_TOKEN_EXPIRY = 14400; |
| 43 | + /** |
| 44 | + * Cache masks |
| 45 | + */ |
| 46 | + /** @var string */ |
| 47 | + private const MASK_TOKEN_USER = 'tk-%s-%s'; |
| 48 | + |
| 49 | + /** |
| 50 | + * @param UserTransport $domainUser |
| 51 | + * @param string $token |
| 52 | + * |
| 53 | + * @return string |
| 54 | + */ |
| 55 | + public function getCacheTokenKey(UserTransport $domainUser, string $token): string |
| 56 | + { |
| 57 | + return sprintf( |
| 58 | + self::MASK_TOKEN_USER, |
| 59 | + $domainUser->getId(), |
| 60 | + sha1($token) |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @param EnvManager $env |
| 66 | + * @param UserTransport $domainUser |
| 67 | + * @param string $token |
| 68 | + * |
| 69 | + * @return bool |
| 70 | + * @throws InvalidArgumentException |
| 71 | + */ |
| 72 | + public function storeTokenInCache( |
| 73 | + EnvManager $env, |
| 74 | + UserTransport $domainUser, |
| 75 | + string $token |
| 76 | + ): bool { |
| 77 | + $cacheKey = $this->getCacheTokenKey($domainUser, $token); |
| 78 | + /** @var int $expiration */ |
| 79 | + $expiration = $env->get('TOKEN_EXPIRATION', self::CACHE_TOKEN_EXPIRY, 'int'); |
| 80 | + $expirationDate = (new DateTimeImmutable()) |
| 81 | + ->modify('+' . $expiration . ' seconds') |
| 82 | + ->format(Dates::DATE_TIME_FORMAT) |
| 83 | + ; |
| 84 | + |
| 85 | + $payload = [ |
| 86 | + 'token' => $token, |
| 87 | + 'expiry' => $expirationDate, |
| 88 | + ]; |
| 89 | + |
| 90 | + return $this->set($cacheKey, $payload, $expiration); |
| 91 | + } |
| 92 | +} |
0 commit comments