RememberBackupCodesJob.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\TwoFactorBackupCodes\BackgroundJob;
  8. use OCP\AppFramework\Utility\ITimeFactory;
  9. use OCP\Authentication\TwoFactorAuth\IRegistry;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\BackgroundJob\TimedJob;
  12. use OCP\IUserManager;
  13. use OCP\Notification\IManager;
  14. class RememberBackupCodesJob extends TimedJob {
  15. public function __construct(
  16. private IRegistry $registry,
  17. private IUserManager $userManager,
  18. ITimeFactory $timeFactory,
  19. private IManager $notificationManager,
  20. private IJobList $jobList,
  21. ) {
  22. parent::__construct($timeFactory);
  23. $this->time = $timeFactory;
  24. $this->setInterval(60 * 60 * 24 * 14);
  25. $this->setTimeSensitivity(self::TIME_INSENSITIVE);
  26. }
  27. protected function run($argument) {
  28. $uid = $argument['uid'];
  29. $user = $this->userManager->get($uid);
  30. if ($user === null) {
  31. // We can't run with an invalid user
  32. $this->jobList->remove(self::class, $argument);
  33. return;
  34. }
  35. $providers = $this->registry->getProviderStates($user);
  36. $state2fa = array_reduce($providers, function (bool $carry, bool $state) {
  37. return $carry || $state;
  38. }, false);
  39. /*
  40. * If no provider is active or if the backup codes are already generate
  41. * we can remove the job
  42. */
  43. if ($state2fa === false || (isset($providers['backup_codes']) && $providers['backup_codes'] === true)) {
  44. // Backup codes already generated lets remove this job
  45. $this->jobList->remove(self::class, $argument);
  46. return;
  47. }
  48. $date = new \DateTime();
  49. $date->setTimestamp($this->time->getTime());
  50. $notification = $this->notificationManager->createNotification();
  51. $notification->setApp('twofactor_backupcodes')
  52. ->setUser($user->getUID())
  53. ->setObject('create', 'codes')
  54. ->setSubject('create_backupcodes');
  55. $this->notificationManager->markProcessed($notification);
  56. if (!$user->isEnabled()) {
  57. // Don't recreate a notification for a user that can not read it
  58. $this->jobList->remove(self::class, $argument);
  59. return;
  60. }
  61. $notification->setDateTime($date);
  62. $this->notificationManager->notify($notification);
  63. }
  64. }