migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth\Db;
use OCP\IDBConnection;
use function array_map;
/**
* Data access object to query and assign (provider_id, uid, enabled) tuples of
* 2FA providers
*/
class ProviderUserAssignmentDao {
public const TABLE_NAME = 'twofactor_providers';
/** @var IDBConnection */
private $conn;
public function __construct(IDBConnection $dbConn) {
$this->conn = $dbConn;
}
/**
* Get all assigned provider IDs for the given user ID
*
* @return array<string, bool> where the array key is the provider ID (string) and the
* value is the enabled state (bool)
*/
public function getState(string $uid): array {
$qb = $this->conn->getQueryBuilder();
$query = $qb->select('provider_id', 'enabled')
->from(self::TABLE_NAME)
->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)));
$result = $query->execute();
$providers = [];
foreach ($result->fetchAll() as $row) {
$providers[(string)$row['provider_id']] = 1 === (int)$row['enabled'];
}
$result->closeCursor();
return $providers;
}
/**
* Persist a new/updated (provider_id, uid, enabled) tuple
*/
public function persist(string $providerId, string $uid, int $enabled): void {
$conn = $this->conn;
// Insert a new entry
if ($conn->insertIgnoreConflict(self::TABLE_NAME, [
'provider_id' => $providerId,
'uid' => $uid,
'enabled' => $enabled,
])) {
return;
}
// There is already an entry -> update it
$qb = $conn->getQueryBuilder();
$updateQuery = $qb->update(self::TABLE_NAME)
->set('enabled', $qb->createNamedParameter($enabled))
->where($qb->expr()->eq('provider_id', $qb->createNamedParameter($providerId)))
->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)));
$updateQuery->executeStatement();
}
/**
* Delete all provider states of a user and return the provider IDs
*
* @param string $uid
*
* @return list<array{provider_id: string, uid: string, enabled: bool}>
*/
public function deleteByUser(string $uid): array {
$qb1 = $this->conn->getQueryBuilder();
$selectQuery = $qb1->select('*')
->from(self::TABLE_NAME)
->where($qb1->expr()->eq('uid', $qb1->createNamedParameter($uid)));
$selectResult = $selectQuery->execute();
$rows = $selectResult->fetchAll();
$selectResult->closeCursor();
$qb2 = $this->conn->getQueryBuilder();
$deleteQuery = $qb2
->delete(self::TABLE_NAME)
->where($qb2->expr()->eq('uid', $qb2->createNamedParameter($uid)));
$deleteQuery->execute();
return array_map(function (array $row) {
return [
'provider_id' => $row['provider_id'],
'uid' => $row['uid'],
'enabled' => 1 === (int) $row['enabled'],
];
}, $rows);
}
public function deleteAll(string $providerId): void {
$qb = $this->conn->getQueryBuilder();
$deleteQuery = $qb->delete(self::TABLE_NAME)
->where($qb->expr()->eq('provider_id', $qb->createNamedParameter($providerId)));
$deleteQuery->execute();
}
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth;
use JsonSerializable;
class EnforcementState implements JsonSerializable {
/** @var bool */
private $enforced;
/** @var array */
private $enforcedGroups;
/** @var array */
private $excludedGroups;
/**
* EnforcementState constructor.
*
* @param bool $enforced
* @param string[] $enforcedGroups
* @param string[] $excludedGroups
*/
public function __construct(bool $enforced,
array $enforcedGroups = [],
array $excludedGroups = []) {
$this->enforced = $enforced;
$this->enforcedGroups = $enforcedGroups;
$this->excludedGroups = $excludedGroups;
}
/**
* @return bool
*/
public function isEnforced(): bool {
return $this->enforced;
}
/**
* @return string[]
*/
public function getEnforcedGroups(): array {
return $this->enforcedGroups;
}
/**
* @return string[]
*/
public function getExcludedGroups(): array {
return $this->excludedGroups;
}
public function jsonSerialize(): array {
return [
'enforced' => $this->enforced,
'enforcedGroups' => $this->enforcedGroups,
'excludedGroups' => $this->excludedGroups,
];
}
}
@@ -0,0 +1,391 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Authentication\TwoFactorAuth;
use BadMethodCallException;
use Exception;
use OC\Authentication\Token\IProvider as TokenProvider;
use OCP\Activity\IManager;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Authentication\Exceptions\InvalidTokenException;
use OCP\Authentication\TwoFactorAuth\IActivatableAtLogin;
use OCP\Authentication\TwoFactorAuth\IProvider;
use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderChallengeFailed;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderChallengePassed;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserDisabled;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserEnabled;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\ISession;
use OCP\IUser;
use OCP\Session\Exceptions\SessionNotAvailableException;
use Psr\Log\LoggerInterface;
use function array_diff;
use function array_filter;
class Manager {
public const SESSION_UID_KEY = 'two_factor_auth_uid';
public const SESSION_UID_DONE = 'two_factor_auth_passed';
public const REMEMBER_LOGIN = 'two_factor_remember_login';
public const BACKUP_CODES_PROVIDER_ID = 'backup_codes';
/** @var ProviderLoader */
private $providerLoader;
/** @var IRegistry */
private $providerRegistry;
/** @var MandatoryTwoFactor */
private $mandatoryTwoFactor;
/** @var ISession */
private $session;
/** @var IConfig */
private $config;
/** @var IManager */
private $activityManager;
/** @var LoggerInterface */
private $logger;
/** @var TokenProvider */
private $tokenProvider;
/** @var ITimeFactory */
private $timeFactory;
/** @var IEventDispatcher */
private $dispatcher;
/** @psalm-var array<string, bool> */
private $userIsTwoFactorAuthenticated = [];
public function __construct(ProviderLoader $providerLoader,
IRegistry $providerRegistry,
MandatoryTwoFactor $mandatoryTwoFactor,
ISession $session,
IConfig $config,
IManager $activityManager,
LoggerInterface $logger,
TokenProvider $tokenProvider,
ITimeFactory $timeFactory,
IEventDispatcher $eventDispatcher) {
$this->providerLoader = $providerLoader;
$this->providerRegistry = $providerRegistry;
$this->mandatoryTwoFactor = $mandatoryTwoFactor;
$this->session = $session;
$this->config = $config;
$this->activityManager = $activityManager;
$this->logger = $logger;
$this->tokenProvider = $tokenProvider;
$this->timeFactory = $timeFactory;
$this->dispatcher = $eventDispatcher;
}
/**
* Determine whether the user must provide a second factor challenge
*/
public function isTwoFactorAuthenticated(IUser $user): bool {
if (isset($this->userIsTwoFactorAuthenticated[$user->getUID()])) {
return $this->userIsTwoFactorAuthenticated[$user->getUID()];
}
if ($this->mandatoryTwoFactor->isEnforcedFor($user)) {
return true;
}
$providerStates = $this->providerRegistry->getProviderStates($user);
$providers = $this->providerLoader->getProviders($user);
$fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
$enabled = array_filter($fixedStates);
$providerIds = array_keys($enabled);
$providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);
$this->userIsTwoFactorAuthenticated[$user->getUID()] = !empty($providerIdsWithoutBackupCodes);
return $this->userIsTwoFactorAuthenticated[$user->getUID()];
}
/**
* Get a 2FA provider by its ID
*/
public function getProvider(IUser $user, string $challengeProviderId): ?IProvider {
$providers = $this->getProviderSet($user)->getProviders();
return $providers[$challengeProviderId] ?? null;
}
/**
* @return IActivatableAtLogin[]
* @throws Exception
*/
public function getLoginSetupProviders(IUser $user): array {
$providers = $this->providerLoader->getProviders($user);
return array_filter($providers, function (IProvider $provider) {
return ($provider instanceof IActivatableAtLogin);
});
}
/**
* Check if the persistant mapping of enabled/disabled state of each available
* provider is missing an entry and add it to the registry in that case.
*
* @todo remove in Nextcloud 17 as by then all providers should have been updated
*
* @param array<string, bool> $providerStates
* @param IProvider[] $providers
* @param IUser $user
* @return array<string, bool> the updated $providerStates variable
*/
private function fixMissingProviderStates(array $providerStates,
array $providers, IUser $user): array {
foreach ($providers as $provider) {
if (isset($providerStates[$provider->getId()])) {
// All good
continue;
}
$enabled = $provider->isTwoFactorAuthEnabledForUser($user);
if ($enabled) {
$this->providerRegistry->enableProviderFor($provider, $user);
} else {
$this->providerRegistry->disableProviderFor($provider, $user);
}
$providerStates[$provider->getId()] = $enabled;
}
return $providerStates;
}
/**
* @param array $states
* @param IProvider[] $providers
*/
private function isProviderMissing(array $states, array $providers): bool {
$indexed = [];
foreach ($providers as $provider) {
$indexed[$provider->getId()] = $provider;
}
$missing = [];
foreach ($states as $providerId => $enabled) {
if (!$enabled) {
// Don't care
continue;
}
if (!isset($indexed[$providerId])) {
$missing[] = $providerId;
$this->logger->alert("two-factor auth provider '$providerId' failed to load",
[
'app' => 'core',
]);
}
}
if (!empty($missing)) {
// There was at least one provider missing
$this->logger->alert(count($missing) . " two-factor auth providers failed to load", ['app' => 'core']);
return true;
}
// If we reach this, there was not a single provider missing
return false;
}
/**
* Get the list of 2FA providers for the given user
*
* @param IUser $user
* @throws Exception
*/
public function getProviderSet(IUser $user): ProviderSet {
$providerStates = $this->providerRegistry->getProviderStates($user);
$providers = $this->providerLoader->getProviders($user);
$fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
$isProviderMissing = $this->isProviderMissing($fixedStates, $providers);
$enabled = array_filter($providers, function (IProvider $provider) use ($fixedStates) {
return $fixedStates[$provider->getId()];
});
return new ProviderSet($enabled, $isProviderMissing);
}
/**
* Verify the given challenge
*
* @param string $providerId
* @param IUser $user
* @param string $challenge
* @return boolean
*/
public function verifyChallenge(string $providerId, IUser $user, string $challenge): bool {
$provider = $this->getProvider($user, $providerId);
if ($provider === null) {
return false;
}
$passed = $provider->verifyChallenge($user, $challenge);
if ($passed) {
if ($this->session->get(self::REMEMBER_LOGIN) === true) {
// TODO: resolve cyclic dependency and use DI
\OC::$server->getUserSession()->createRememberMeToken($user);
}
$this->session->remove(self::SESSION_UID_KEY);
$this->session->remove(self::REMEMBER_LOGIN);
$this->session->set(self::SESSION_UID_DONE, $user->getUID());
// Clear token from db
$sessionId = $this->session->getId();
$token = $this->tokenProvider->getToken($sessionId);
$tokenId = $token->getId();
$this->config->deleteUserValue($user->getUID(), 'login_token_2fa', (string)$tokenId);
$this->dispatcher->dispatchTyped(new TwoFactorProviderForUserEnabled($user, $provider));
$this->dispatcher->dispatchTyped(new TwoFactorProviderChallengePassed($user, $provider));
$this->publishEvent($user, 'twofactor_success', [
'provider' => $provider->getDisplayName(),
]);
} else {
$this->dispatcher->dispatchTyped(new TwoFactorProviderForUserDisabled($user, $provider));
$this->dispatcher->dispatchTyped(new TwoFactorProviderChallengeFailed($user, $provider));
$this->publishEvent($user, 'twofactor_failed', [
'provider' => $provider->getDisplayName(),
]);
}
return $passed;
}
/**
* Push a 2fa event the user's activity stream
*
* @param IUser $user
* @param string $event
* @param array $params
*/
private function publishEvent(IUser $user, string $event, array $params) {
$activity = $this->activityManager->generateEvent();
$activity->setApp('core')
->setType('security')
->setAuthor($user->getUID())
->setAffectedUser($user->getUID())
->setSubject($event, $params);
try {
$this->activityManager->publish($activity);
} catch (BadMethodCallException $e) {
$this->logger->warning('could not publish activity', ['app' => 'core', 'exception' => $e]);
}
}
/**
* Check if the currently logged in user needs to pass 2FA
*
* @param IUser $user the currently logged in user
* @return boolean
*/
public function needsSecondFactor(IUser $user = null): bool {
if ($user === null) {
return false;
}
// If we are authenticated using an app password or AppAPI Auth, skip all this
if ($this->session->exists('app_password') || $this->session->get('app_api') === true) {
return false;
}
// First check if the session tells us we should do 2FA (99% case)
if (!$this->session->exists(self::SESSION_UID_KEY)) {
// Check if the session tells us it is 2FA authenticated already
if ($this->session->exists(self::SESSION_UID_DONE) &&
$this->session->get(self::SESSION_UID_DONE) === $user->getUID()) {
return false;
}
/*
* If the session is expired check if we are not logged in by a token
* that still needs 2FA auth
*/
try {
$sessionId = $this->session->getId();
$token = $this->tokenProvider->getToken($sessionId);
$tokenId = $token->getId();
$tokensNeeding2FA = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
if (!\in_array((string) $tokenId, $tokensNeeding2FA, true)) {
$this->session->set(self::SESSION_UID_DONE, $user->getUID());
return false;
}
} catch (InvalidTokenException|SessionNotAvailableException $e) {
}
}
if (!$this->isTwoFactorAuthenticated($user)) {
// There is no second factor any more -> let the user pass
// This prevents infinite redirect loops when a user is about
// to solve the 2FA challenge, and the provider app is
// disabled the same time
$this->session->remove(self::SESSION_UID_KEY);
$keys = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
foreach ($keys as $key) {
$this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $key);
}
return false;
}
return true;
}
/**
* Prepare the 2FA login
*
* @param IUser $user
* @param boolean $rememberMe
*/
public function prepareTwoFactorLogin(IUser $user, bool $rememberMe) {
$this->session->set(self::SESSION_UID_KEY, $user->getUID());
$this->session->set(self::REMEMBER_LOGIN, $rememberMe);
$id = $this->session->getId();
$token = $this->tokenProvider->getToken($id);
$this->config->setUserValue($user->getUID(), 'login_token_2fa', (string) $token->getId(), (string)$this->timeFactory->getTime());
}
public function clearTwoFactorPending(string $userId) {
$tokensNeeding2FA = $this->config->getUserKeys($userId, 'login_token_2fa');
foreach ($tokensNeeding2FA as $tokenId) {
$this->tokenProvider->invalidateTokenById($userId, (int)$tokenId);
}
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IUser;
class MandatoryTwoFactor {
/** @var IConfig */
private $config;
/** @var IGroupManager */
private $groupManager;
public function __construct(IConfig $config, IGroupManager $groupManager) {
$this->config = $config;
$this->groupManager = $groupManager;
}
/**
* Get the state of enforced two-factor auth
*/
public function getState(): EnforcementState {
return new EnforcementState(
$this->config->getSystemValue('twofactor_enforced', 'false') === 'true',
$this->config->getSystemValue('twofactor_enforced_groups', []),
$this->config->getSystemValue('twofactor_enforced_excluded_groups', [])
);
}
/**
* Set the state of enforced two-factor auth
*/
public function setState(EnforcementState $state) {
$this->config->setSystemValue('twofactor_enforced', $state->isEnforced() ? 'true' : 'false');
$this->config->setSystemValue('twofactor_enforced_groups', $state->getEnforcedGroups());
$this->config->setSystemValue('twofactor_enforced_excluded_groups', $state->getExcludedGroups());
}
/**
* Check if two-factor auth is enforced for a specific user
*
* The admin(s) can enforce two-factor auth system-wide, for certain groups only
* and also have the option to exclude users of certain groups. This method will
* check their membership of those groups.
*
* @param IUser $user
*
* @return bool
*/
public function isEnforcedFor(IUser $user): bool {
$state = $this->getState();
if (!$state->isEnforced()) {
return false;
}
$uid = $user->getUID();
/*
* If there is a list of enforced groups, we only enforce 2FA for members of those groups.
* For all the other users it is not enforced (overruling the excluded groups list).
*/
if (!empty($state->getEnforcedGroups())) {
foreach ($state->getEnforcedGroups() as $group) {
if ($this->groupManager->isInGroup($uid, $group)) {
return true;
}
}
// Not a member of any of these groups -> no 2FA enforced
return false;
}
/**
* If the user is member of an excluded group, 2FA won't be enforced.
*/
foreach ($state->getExcludedGroups() as $group) {
if ($this->groupManager->isInGroup($uid, $group)) {
return false;
}
}
/**
* No enforced groups configured and user not member of an excluded groups,
* so 2FA is enforced.
*/
return true;
}
}
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth;
use Exception;
use OC;
use OC_App;
use OCP\App\IAppManager;
use OCP\AppFramework\QueryException;
use OCP\Authentication\TwoFactorAuth\IProvider;
use OCP\IUser;
class ProviderLoader {
public const BACKUP_CODES_APP_ID = 'twofactor_backupcodes';
/** @var IAppManager */
private $appManager;
/** @var OC\AppFramework\Bootstrap\Coordinator */
private $coordinator;
public function __construct(IAppManager $appManager, OC\AppFramework\Bootstrap\Coordinator $coordinator) {
$this->appManager = $appManager;
$this->coordinator = $coordinator;
}
/**
* Get the list of 2FA providers for the given user
*
* @return IProvider[]
* @throws Exception
*/
public function getProviders(IUser $user): array {
$allApps = $this->appManager->getEnabledAppsForUser($user);
$providers = [];
foreach ($allApps as $appId) {
$info = $this->appManager->getAppInfo($appId);
if (isset($info['two-factor-providers'])) {
/** @var string[] $providerClasses */
$providerClasses = $info['two-factor-providers'];
foreach ($providerClasses as $class) {
try {
$this->loadTwoFactorApp($appId);
$provider = \OCP\Server::get($class);
$providers[$provider->getId()] = $provider;
} catch (QueryException $exc) {
// Provider class can not be resolved
throw new Exception("Could not load two-factor auth provider $class");
}
}
}
}
$registeredProviders = $this->coordinator->getRegistrationContext()->getTwoFactorProviders();
foreach ($registeredProviders as $provider) {
try {
$this->loadTwoFactorApp($provider->getAppId());
$provider = \OCP\Server::get($provider->getService());
$providers[$provider->getId()] = $provider;
} catch (QueryException $exc) {
// Provider class can not be resolved
throw new Exception('Could not load two-factor auth provider ' . $provider->getService());
}
}
return $providers;
}
/**
* Load an app by ID if it has not been loaded yet
*
* @param string $appId
*/
protected function loadTwoFactorApp(string $appId) {
if (!OC_App::isAppLoaded($appId)) {
OC_App::loadApp($appId);
}
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth;
use OC\Authentication\Exceptions\InvalidProviderException;
use OCP\Authentication\TwoFactorAuth\IActivatableByAdmin;
use OCP\Authentication\TwoFactorAuth\IDeactivatableByAdmin;
use OCP\Authentication\TwoFactorAuth\IProvider;
use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\IUser;
class ProviderManager {
/** @var ProviderLoader */
private $providerLoader;
/** @var IRegistry */
private $providerRegistry;
public function __construct(ProviderLoader $providerLoader, IRegistry $providerRegistry) {
$this->providerLoader = $providerLoader;
$this->providerRegistry = $providerRegistry;
}
private function getProvider(string $providerId, IUser $user): IProvider {
$providers = $this->providerLoader->getProviders($user);
if (!isset($providers[$providerId])) {
throw new InvalidProviderException($providerId);
}
return $providers[$providerId];
}
/**
* Try to enable the provider with the given id for the given user
*
* @param IUser $user
*
* @return bool whether the provider supports this operation
*/
public function tryEnableProviderFor(string $providerId, IUser $user): bool {
$provider = $this->getProvider($providerId, $user);
if ($provider instanceof IActivatableByAdmin) {
$provider->enableFor($user);
$this->providerRegistry->enableProviderFor($provider, $user);
return true;
} else {
return false;
}
}
/**
* Try to disable the provider with the given id for the given user
*
* @param IUser $user
*
* @return bool whether the provider supports this operation
*/
public function tryDisableProviderFor(string $providerId, IUser $user): bool {
$provider = $this->getProvider($providerId, $user);
if ($provider instanceof IDeactivatableByAdmin) {
$provider->disableFor($user);
$this->providerRegistry->disableProviderFor($provider, $user);
return true;
} else {
return false;
}
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth;
use OCA\TwoFactorBackupCodes\Provider\BackupCodesProvider;
use OCP\Authentication\TwoFactorAuth\IProvider;
use function array_filter;
/**
* Contains all two-factor provider information for the two-factor login challenge
*/
class ProviderSet {
/** @var IProvider */
private $providers;
/** @var bool */
private $providerMissing;
/**
* @param IProvider[] $providers
* @param bool $providerMissing
*/
public function __construct(array $providers, bool $providerMissing) {
$this->providers = [];
foreach ($providers as $provider) {
$this->providers[$provider->getId()] = $provider;
}
$this->providerMissing = $providerMissing;
}
/**
* @param string $providerId
* @return IProvider|null
*/
public function getProvider(string $providerId) {
return $this->providers[$providerId] ?? null;
}
/**
* @return IProvider[]
*/
public function getProviders(): array {
return $this->providers;
}
/**
* @return IProvider[]
*/
public function getPrimaryProviders(): array {
return array_filter($this->providers, function (IProvider $provider) {
return !($provider instanceof BackupCodesProvider);
});
}
public function isProviderMissing(): bool {
return $this->providerMissing;
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Authentication\TwoFactorAuth;
use OC\Authentication\TwoFactorAuth\Db\ProviderUserAssignmentDao;
use OCP\Authentication\TwoFactorAuth\IProvider;
use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\Authentication\TwoFactorAuth\RegistryEvent;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderDisabled;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserRegistered;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserUnregistered;
use OCP\Authentication\TwoFactorAuth\TwoFactorProviderUserDeleted;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IUser;
class Registry implements IRegistry {
/** @var ProviderUserAssignmentDao */
private $assignmentDao;
/** @var IEventDispatcher */
private $dispatcher;
public function __construct(ProviderUserAssignmentDao $assignmentDao,
IEventDispatcher $dispatcher) {
$this->assignmentDao = $assignmentDao;
$this->dispatcher = $dispatcher;
}
public function getProviderStates(IUser $user): array {
return $this->assignmentDao->getState($user->getUID());
}
public function enableProviderFor(IProvider $provider, IUser $user) {
$this->assignmentDao->persist($provider->getId(), $user->getUID(), 1);
$event = new RegistryEvent($provider, $user);
$this->dispatcher->dispatch(self::EVENT_PROVIDER_ENABLED, $event);
$this->dispatcher->dispatchTyped(new TwoFactorProviderForUserRegistered($user, $provider));
}
public function disableProviderFor(IProvider $provider, IUser $user) {
$this->assignmentDao->persist($provider->getId(), $user->getUID(), 0);
$event = new RegistryEvent($provider, $user);
$this->dispatcher->dispatch(self::EVENT_PROVIDER_DISABLED, $event);
$this->dispatcher->dispatchTyped(new TwoFactorProviderForUserUnregistered($user, $provider));
}
public function deleteUserData(IUser $user): void {
foreach ($this->assignmentDao->deleteByUser($user->getUID()) as $provider) {
$event = new TwoFactorProviderDisabled($provider['provider_id']);
$this->dispatcher->dispatchTyped($event);
$this->dispatcher->dispatchTyped(new TwoFactorProviderUserDeleted($user, $provider['provider_id']));
}
}
public function cleanUp(string $providerId) {
$this->assignmentDao->deleteAll($providerId);
}
}