AccessTokenMapper.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\OAuth2\Db;
  8. use OCA\OAuth2\Controller\OauthApiController;
  9. use OCA\OAuth2\Exceptions\AccessTokenNotFoundException;
  10. use OCP\AppFramework\Db\IMapperException;
  11. use OCP\AppFramework\Db\QBMapper;
  12. use OCP\AppFramework\Utility\ITimeFactory;
  13. use OCP\DB\Exception;
  14. use OCP\DB\QueryBuilder\IQueryBuilder;
  15. use OCP\IDBConnection;
  16. /**
  17. * @template-extends QBMapper<AccessToken>
  18. */
  19. class AccessTokenMapper extends QBMapper {
  20. public function __construct(
  21. IDBConnection $db,
  22. private ITimeFactory $timeFactory,
  23. ) {
  24. parent::__construct($db, 'oauth2_access_tokens');
  25. }
  26. /**
  27. * @param string $code
  28. * @return AccessToken
  29. * @throws AccessTokenNotFoundException
  30. */
  31. public function getByCode(string $code): AccessToken {
  32. $qb = $this->db->getQueryBuilder();
  33. $qb
  34. ->select('*')
  35. ->from($this->tableName)
  36. ->where($qb->expr()->eq('hashed_code', $qb->createNamedParameter(hash('sha512', $code))));
  37. try {
  38. $token = $this->findEntity($qb);
  39. } catch (IMapperException $e) {
  40. throw new AccessTokenNotFoundException('Could not find access token', 0, $e);
  41. }
  42. return $token;
  43. }
  44. /**
  45. * delete all access token from a given client
  46. *
  47. * @param int $id
  48. */
  49. public function deleteByClientId(int $id) {
  50. $qb = $this->db->getQueryBuilder();
  51. $qb
  52. ->delete($this->tableName)
  53. ->where($qb->expr()->eq('client_id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  54. $qb->executeStatement();
  55. }
  56. /**
  57. * Delete access tokens that have an expired authorization code
  58. * -> those that are old enough
  59. * and which never delivered any oauth token (still in authorization state)
  60. *
  61. * @return void
  62. * @throws Exception
  63. */
  64. public function cleanupExpiredAuthorizationCode(): void {
  65. $now = $this->timeFactory->now()->getTimestamp();
  66. $maxTokenCreationTs = $now - OauthApiController::AUTHORIZATION_CODE_EXPIRES_AFTER;
  67. $qb = $this->db->getQueryBuilder();
  68. $qb
  69. ->delete($this->tableName)
  70. ->where($qb->expr()->eq('token_count', $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
  71. ->andWhere($qb->expr()->lt('code_created_at', $qb->createNamedParameter($maxTokenCreationTs, IQueryBuilder::PARAM_INT)));
  72. $qb->executeStatement();
  73. }
  74. }