1
0

CredentialRepository.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Authentication\WebAuthn;
  8. use OC\Authentication\WebAuthn\Db\PublicKeyCredentialEntity;
  9. use OC\Authentication\WebAuthn\Db\PublicKeyCredentialMapper;
  10. use OCP\AppFramework\Db\IMapperException;
  11. use Webauthn\PublicKeyCredentialSource;
  12. use Webauthn\PublicKeyCredentialSourceRepository;
  13. use Webauthn\PublicKeyCredentialUserEntity;
  14. class CredentialRepository implements PublicKeyCredentialSourceRepository {
  15. /** @var PublicKeyCredentialMapper */
  16. private $credentialMapper;
  17. public function __construct(PublicKeyCredentialMapper $credentialMapper) {
  18. $this->credentialMapper = $credentialMapper;
  19. }
  20. public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKeyCredentialSource {
  21. try {
  22. $entity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialId);
  23. return $entity->toPublicKeyCredentialSource();
  24. } catch (IMapperException $e) {
  25. return null;
  26. }
  27. }
  28. /**
  29. * @return PublicKeyCredentialSource[]
  30. */
  31. public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array {
  32. $uid = $publicKeyCredentialUserEntity->getId();
  33. $entities = $this->credentialMapper->findAllForUid($uid);
  34. return array_map(function (PublicKeyCredentialEntity $entity) {
  35. return $entity->toPublicKeyCredentialSource();
  36. }, $entities);
  37. }
  38. public function saveAndReturnCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, ?string $name = null): PublicKeyCredentialEntity {
  39. $oldEntity = null;
  40. try {
  41. $oldEntity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialSource->getPublicKeyCredentialId());
  42. } catch (IMapperException $e) {
  43. }
  44. $defaultName = false;
  45. if ($name === null) {
  46. $defaultName = true;
  47. $name = 'default';
  48. }
  49. $entity = PublicKeyCredentialEntity::fromPublicKeyCrendentialSource($name, $publicKeyCredentialSource);
  50. if ($oldEntity) {
  51. $entity->setId($oldEntity->getId());
  52. if ($defaultName) {
  53. $entity->setName($oldEntity->getName());
  54. }
  55. }
  56. return $this->credentialMapper->insertOrUpdate($entity);
  57. }
  58. public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, ?string $name = null): void {
  59. $this->saveAndReturnCredentialSource($publicKeyCredentialSource, $name);
  60. }
  61. }