Skip to content

Commit c6fd933

Browse files
committed
refactor: move to ITimeFactory
Signed-off-by: Git'Fellow <12234510+solracsf@users.noreply.github.com>
1 parent 93e7593 commit c6fd933

6 files changed

Lines changed: 27 additions & 20 deletions

File tree

lib/Controller/Id4meController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ public function code(string $state = '', string $code = '', string $scope = '')
322322
}
323323

324324
// Set last password confirm to the future as we don't have passwords to confirm against with SSO
325-
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
325+
$this->session->set('last-password-confirm', $this->timeFactory->getTime() + 4 * 365 * 24 * 3600);
326326

327327
return new RedirectResponse($this->serverVersion->getMajorVersion() >= 32 ? $this->urlGenerator->linkToDefaultPageUrl() : \OC_Util::getDefaultPageUrl());
328328
}

lib/Controller/LoginController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -667,7 +667,7 @@ public function code(string $state = '', string $code = '', string $scope = '',
667667
$this->config->setUserValue($user->getUID(), Application::APP_ID, 'had_token_once', '1');
668668

669669
// Set last password confirm to the future as we don't have passwords to confirm against with SSO
670-
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
670+
$this->session->set('last-password-confirm', $this->timeFactory->getTime() + 4 * 365 * 24 * 3600);
671671

672672
// for backchannel logout
673673
try {

lib/Model/Token.php

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
namespace OCA\UserOIDC\Model;
1010

1111
use JsonSerializable;
12+
use OCP\AppFramework\Utility\ITimeFactory;
1213

1314
class Token implements JsonSerializable {
1415

@@ -20,13 +21,13 @@ class Token implements JsonSerializable {
2021
private int $createdAt;
2122
private ?int $providerId;
2223

23-
public function __construct(array $tokenData) {
24+
public function __construct(array $tokenData, private ITimeFactory $timeFactory) {
2425
$this->idToken = $tokenData['id_token'] ?? null;
2526
$this->accessToken = $tokenData['access_token'];
2627
$this->expiresIn = $tokenData['expires_in'];
2728
$this->refreshExpiresIn = $tokenData['refresh_expires_in'] ?? null;
2829
$this->refreshToken = $tokenData['refresh_token'] ?? null;
29-
$this->createdAt = $tokenData['created_at'] ?? time();
30+
$this->createdAt = $tokenData['created_at'] ?? $this->timeFactory->getTime();
3031
$this->providerId = $tokenData['provider_id'] ?? null;
3132
}
3233

@@ -44,7 +45,7 @@ public function getExpiresIn(): int {
4445

4546
public function getExpiresInFromNow(): int {
4647
$expiresAt = $this->createdAt + $this->expiresIn;
47-
return $expiresAt - time();
48+
return $expiresAt - $this->timeFactory->getTime();
4849
}
4950

5051
public function getRefreshExpiresIn(): ?int {
@@ -58,7 +59,7 @@ public function getRefreshExpiresInFromNow(): int {
5859
return 0;
5960
}
6061
$refreshExpiresAt = $this->createdAt + $this->refreshExpiresIn;
61-
return $refreshExpiresAt - time();
62+
return $refreshExpiresAt - $this->timeFactory->getTime();
6263
}
6364

6465
public function getRefreshToken(): ?string {
@@ -70,27 +71,27 @@ public function getProviderId(): ?int {
7071
}
7172

7273
public function isExpired(): bool {
73-
return time() > ($this->createdAt + $this->expiresIn);
74+
return $this->timeFactory->getTime() > ($this->createdAt + $this->expiresIn);
7475
}
7576

7677
public function isExpiring(): bool {
77-
return time() > ($this->createdAt + (int)($this->expiresIn / 2));
78+
return $this->timeFactory->getTime() > ($this->createdAt + (int)($this->expiresIn / 2));
7879
}
7980

8081
public function refreshIsExpired(): bool {
8182
// if there is no refresh_expires_in, we assume the refresh token never expires
8283
if ($this->refreshExpiresIn === null) {
8384
return false;
8485
}
85-
return time() > ($this->createdAt + $this->refreshExpiresIn);
86+
return $this->timeFactory->getTime() > ($this->createdAt + $this->refreshExpiresIn);
8687
}
8788

8889
public function refreshIsExpiring(): bool {
8990
// if there is no refresh_expires_in, we assume the refresh token never expires
9091
if ($this->refreshExpiresIn === null) {
9192
return false;
9293
}
93-
return time() > ($this->createdAt + (int)($this->refreshExpiresIn / 2));
94+
return $this->timeFactory->getTime() > ($this->createdAt + (int)($this->refreshExpiresIn / 2));
9495
}
9596

9697
public function getCreatedAt() {

lib/Service/DiscoveryService.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use OCA\UserOIDC\Helper\HttpClientHelper;
1414
use OCA\UserOIDC\Vendor\Firebase\JWT\JWK;
1515
use OCA\UserOIDC\Vendor\Firebase\JWT\JWT;
16+
use OCP\AppFramework\Utility\ITimeFactory;
1617
use OCP\ICache;
1718
use OCP\ICacheFactory;
1819
use OCP\IConfig;
@@ -44,6 +45,7 @@ public function __construct(
4445
private HttpClientHelper $clientService,
4546
private ProviderService $providerService,
4647
private IConfig $config,
48+
private ITimeFactory $timeFactory,
4749
ICacheFactory $cacheFactory,
4850
) {
4951
$this->cache = $cacheFactory->createDistributed('user_oidc');
@@ -75,7 +77,7 @@ public function obtainDiscovery(Provider $provider): array {
7577
*/
7678
public function obtainJWK(Provider $provider, string $tokenToDecode, bool $useCache = true): array {
7779
$lastJwksRefresh = $this->providerService->getSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE_TIMESTAMP);
78-
if ($lastJwksRefresh !== '' && $useCache && (int)$lastJwksRefresh > time() - self::INVALIDATE_JWKS_CACHE_AFTER_SECONDS) {
80+
if ($lastJwksRefresh !== '' && $useCache && (int)$lastJwksRefresh > $this->timeFactory->getTime() - self::INVALIDATE_JWKS_CACHE_AFTER_SECONDS) {
7981
$rawJwks = $this->providerService->getSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE);
8082
$rawJwks = json_decode($rawJwks, true);
8183
$this->logger->debug('[obtainJWK] jwks cache content', ['jwks_cache' => $rawJwks]);
@@ -87,7 +89,7 @@ public function obtainJWK(Provider $provider, string $tokenToDecode, bool $useCa
8789
// cache jwks
8890
$this->providerService->setSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE, $responseBody);
8991
$this->logger->debug('[obtainJWK] setting cache', ['jwks_cache' => $responseBody]);
90-
$this->providerService->setSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE_TIMESTAMP, strval(time()));
92+
$this->providerService->setSetting($provider->getId(), ProviderService::SETTING_JWKS_CACHE_TIMESTAMP, strval($this->timeFactory->getTime()));
9193
}
9294

9395
$fixedJwks = $this->fixJwksAlg($rawJwks, $tokenToDecode);

lib/Service/TokenService.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
use OCP\ISession;
3333
use OCP\IURLGenerator;
3434
use OCP\IUserSession;
35+
use OCP\AppFramework\Utility\ITimeFactory;
3536
use OCP\Lock\ILockingProvider;
3637
use OCP\Lock\LockedException;
3738
use OCP\PreConditionNotMetException;
@@ -67,11 +68,12 @@ public function __construct(
6768
private DiscoveryService $discoveryService,
6869
private ProviderMapper $providerMapper,
6970
private ILockingProvider $lockingProvider,
71+
private ITimeFactory $timeFactory,
7072
) {
7173
}
7274

7375
public function storeToken(array $tokenData): Token {
74-
$token = new Token($tokenData);
76+
$token = new Token($tokenData, $this->timeFactory);
7577
$this->session->set(self::SESSION_TOKEN_KEY, json_encode($token, JSON_THROW_ON_ERROR));
7678
$this->logger->debug('[TokenService] Store token in the session', ['session_id' => $this->session->getId()]);
7779
return $token;
@@ -93,7 +95,7 @@ public function getToken(bool $refreshIfExpired = true): ?Token {
9395
return null;
9496
}
9597

96-
$token = new Token(json_decode($sessionData, true, 512, JSON_THROW_ON_ERROR));
98+
$token = new Token(json_decode($sessionData, true, 512, JSON_THROW_ON_ERROR), $this->timeFactory);
9799
// token is still valid
98100
if (!$token->isExpired()) {
99101
$this->logger->debug('[TokenService] getToken: token is still valid, it expires in ' . strval($token->getExpiresInFromNow()) . ' and refresh expires in ' . strval($token->getRefreshExpiresInFromNow()));
@@ -225,7 +227,7 @@ public function refresh(Token $token): Token {
225227
// the token expiration and the moment it attempted to acquire the lock
226228
$sessionData = $this->session->get(self::SESSION_TOKEN_KEY);
227229
if ($sessionData) {
228-
$currentToken = new Token(json_decode($sessionData, true, 512, JSON_THROW_ON_ERROR));
230+
$currentToken = new Token(json_decode($sessionData, true, 512, JSON_THROW_ON_ERROR), $this->timeFactory);
229231
if (!$currentToken->isExpired()) {
230232
$this->logger->debug('[TokenService] Token already refreshed by another request');
231233
return $currentToken;
@@ -368,7 +370,7 @@ public function getExchangedToken(string $targetAudience, array $extraScopes = [
368370
$bodyArray,
369371
['provider_id' => $loginToken->getProviderId()],
370372
);
371-
return new Token($tokenData);
373+
return new Token($tokenData, $this->timeFactory);
372374
} catch (ClientException|ServerException $e) {
373375
$response = $e->getResponse();
374376
$body = (string)$response->getBody();
@@ -439,6 +441,6 @@ public function getTokenFromOidcProviderApp(string $userId, string $targetAudien
439441
'refresh_expires_in' => method_exists($generationEvent, 'getRefreshExpiresIn')
440442
? $generationEvent->getRefreshExpiresIn()
441443
: $generationEvent->getExpiresIn(),
442-
]);
444+
], $this->timeFactory);
443445
}
444446
}

lib/User/Backend.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use OCA\UserOIDC\User\Validator\SelfEncodedValidator;
2323
use OCA\UserOIDC\User\Validator\UserInfoValidator;
2424
use OCP\AppFramework\Db\DoesNotExistException;
25+
use OCP\AppFramework\Utility\ITimeFactory;
2526
use OCP\Authentication\IApacheBackend;
2627
use OCP\DB\Exception;
2728
use OCP\EventDispatcher\GenericEvent;
@@ -69,6 +70,7 @@ public function __construct(
6970
private LdapService $ldapService,
7071
private IUserManager $userManager,
7172
private ServerVersion $serverVersion,
73+
private ITimeFactory $timeFactory,
7274
) {
7375
}
7476

@@ -348,12 +350,12 @@ public function getCurrentUserId(): string {
348350
}
349351
}
350352

351-
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
353+
$this->session->set('last-password-confirm', $this->timeFactory->getTime() + 4 * 365 * 24 * 3600);
352354
$this->setSessionUser($userId);
353355
return $userId;
354356
} elseif ($this->userExists($tokenUserId)) {
355357
$this->checkFirstLogin($tokenUserId);
356-
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
358+
$this->session->set('last-password-confirm', $this->timeFactory->getTime() + 4 * 365 * 24 * 3600);
357359
$this->setSessionUser($tokenUserId);
358360
return $tokenUserId;
359361
} else {
@@ -375,7 +377,7 @@ public function getCurrentUserId(): string {
375377
return '';
376378
}
377379
$this->checkFirstLogin($tokenUserId);
378-
$this->session->set('last-password-confirm', strtotime('+4 year', time()));
380+
$this->session->set('last-password-confirm', $this->timeFactory->getTime() + 4 * 365 * 24 * 3600);
379381
$this->setSessionUser($tokenUserId);
380382
return $tokenUserId;
381383
}

0 commit comments

Comments
 (0)