ProviderLoader.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
  5. *
  6. * @author 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OC\Authentication\TwoFactorAuth;
  25. use Exception;
  26. use OC;
  27. use OC_App;
  28. use OCP\App\IAppManager;
  29. use OCP\AppFramework\QueryException;
  30. use OCP\Authentication\TwoFactorAuth\IProvider;
  31. use OCP\IUser;
  32. class ProviderLoader {
  33. const BACKUP_CODES_APP_ID = 'twofactor_backupcodes';
  34. /** @var IAppManager */
  35. private $appManager;
  36. public function __construct(IAppManager $appManager) {
  37. $this->appManager = $appManager;
  38. }
  39. /**
  40. * Get the list of 2FA providers for the given user
  41. *
  42. * @return IProvider[]
  43. * @throws Exception
  44. */
  45. public function getProviders(IUser $user): array {
  46. $allApps = $this->appManager->getEnabledAppsForUser($user);
  47. $providers = [];
  48. foreach ($allApps as $appId) {
  49. $info = $this->appManager->getAppInfo($appId);
  50. if (isset($info['two-factor-providers'])) {
  51. /** @var string[] $providerClasses */
  52. $providerClasses = $info['two-factor-providers'];
  53. foreach ($providerClasses as $class) {
  54. try {
  55. $this->loadTwoFactorApp($appId);
  56. $provider = OC::$server->query($class);
  57. $providers[$provider->getId()] = $provider;
  58. } catch (QueryException $exc) {
  59. // Provider class can not be resolved
  60. throw new Exception("Could not load two-factor auth provider $class");
  61. }
  62. }
  63. }
  64. }
  65. return $providers;
  66. }
  67. /**
  68. * Load an app by ID if it has not been loaded yet
  69. *
  70. * @param string $appId
  71. */
  72. protected function loadTwoFactorApp(string $appId) {
  73. if (!OC_App::isAppLoaded($appId)) {
  74. OC_App::loadApp($appId);
  75. }
  76. }
  77. }