Completed
Push — master ( e3be9e...9444a3 )
by Morris
73:40 queued 52:27
created

ProviderLoader::getProviders()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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