|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors |
| 7 | + * SPDX-License-Identifier: AGPL-3.0-or-later |
| 8 | + */ |
| 9 | + |
| 10 | +namespace OCA\CloudFederationAPI\Service; |
| 11 | + |
| 12 | +use OC\Authentication\Exceptions\ExpiredTokenException; |
| 13 | +use OC\Authentication\Exceptions\InvalidTokenException; |
| 14 | +use OC\Authentication\Exceptions\WipeTokenException; |
| 15 | +use OC\Authentication\Token\IProvider; |
| 16 | +use OCA\CloudFederationAPI\Db\OcmTokenMap; |
| 17 | +use OCA\CloudFederationAPI\Db\OcmTokenMapMapper; |
| 18 | + |
| 19 | +/** |
| 20 | + * Revokes OCM access tokens together with their ocm_token_map rows, so a |
| 21 | + * removed or expired mapping never leaves an orphaned oc_authtoken entry. |
| 22 | + */ |
| 23 | +class OcmTokenService { |
| 24 | + public function __construct( |
| 25 | + private readonly OcmTokenMapMapper $mapper, |
| 26 | + private readonly IProvider $tokenProvider, |
| 27 | + ) { |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Revoke every access token whose mapping expired before $time. |
| 32 | + */ |
| 33 | + public function revokeExpired(int $time): void { |
| 34 | + foreach ($this->mapper->findExpired($time) as $mapping) { |
| 35 | + $this->revokeMapping($mapping); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Revoke every access token issued for the given refresh token. Tolerates |
| 41 | + * the duplicate rows a concurrent exchange can leave behind. |
| 42 | + */ |
| 43 | + public function revokeByRefreshToken(string $refreshToken): void { |
| 44 | + foreach ($this->mapper->findAllByRefreshToken($refreshToken) as $mapping) { |
| 45 | + $this->revokeMapping($mapping); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + private function revokeMapping(OcmTokenMap $mapping): void { |
| 50 | + $this->revokeAccessToken($mapping->getAccessTokenId()); |
| 51 | + $this->mapper->delete($mapping); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Delete the access token from oc_authtoken. getTokenById throws for an |
| 56 | + * expired token but still carries it, so the owner uid required by |
| 57 | + * invalidateTokenById is recoverable. |
| 58 | + */ |
| 59 | + private function revokeAccessToken(int $accessTokenId): void { |
| 60 | + try { |
| 61 | + $token = $this->tokenProvider->getTokenById($accessTokenId); |
| 62 | + } catch (ExpiredTokenException|WipeTokenException $e) { |
| 63 | + $token = $e->getToken(); |
| 64 | + } catch (InvalidTokenException) { |
| 65 | + // Access token already gone; nothing left to revoke. |
| 66 | + return; |
| 67 | + } |
| 68 | + $this->tokenProvider->invalidateTokenById($token->getUID(), $accessTokenId); |
| 69 | + } |
| 70 | +} |
0 commit comments