Merge pull request #7057 from nextcloud/ldap-sync-split

Bring LDAP user attribute updates ("sync") to the background
This commit is contained in:
Lukas Reschke 2017-11-10 15:02:26 +01:00 committed by GitHub
commit d3e7dd1992
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 1273 additions and 588 deletions

View File

@ -64,9 +64,13 @@ $userManager = new \OCA\User_LDAP\User\Manager(
\OC::$server->getUserManager(),
\OC::$server->getNotificationManager());
$access = new \OCA\User_LDAP\Access($con, $ldapWrapper, $userManager, new \OCA\User_LDAP\Helper(
$access = new \OCA\User_LDAP\Access(
$con,
$ldapWrapper,
$userManager,
new \OCA\User_LDAP\Helper(\OC::$server->getConfig()),
\OC::$server->getConfig()
));
);
$wizard = new \OCA\User_LDAP\Wizard($configuration, $ldapWrapper, $access);

View File

@ -10,7 +10,7 @@ A user logs into Nextcloud with their LDAP or AD credentials, and is granted acc
<licence>AGPL</licence>
<author>Dominik Schmidt</author>
<author>Arthur Schiwon</author>
<version>1.3.0</version>
<version>1.3.1</version>
<types>
<authentication/>
</types>
@ -27,6 +27,7 @@ A user logs into Nextcloud with their LDAP or AD credentials, and is granted acc
<background-jobs>
<job>OCA\User_LDAP\Jobs\UpdateGroups</job>
<job>OCA\User_LDAP\Jobs\CleanUp</job>
<job>OCA\User_LDAP\Jobs\Sync</job>
</background-jobs>
<settings>

View File

@ -34,6 +34,7 @@ return array(
'OCA\\User_LDAP\\ILDAPWrapper' => $baseDir . '/../lib/ILDAPWrapper.php',
'OCA\\User_LDAP\\IUserLDAP' => $baseDir . '/../lib/IUserLDAP.php',
'OCA\\User_LDAP\\Jobs\\CleanUp' => $baseDir . '/../lib/Jobs/CleanUp.php',
'OCA\\User_LDAP\\Jobs\\Sync' => $baseDir . '/../lib/Jobs/Sync.php',
'OCA\\User_LDAP\\Jobs\\UpdateGroups' => $baseDir . '/../lib/Jobs/UpdateGroups.php',
'OCA\\User_LDAP\\LDAP' => $baseDir . '/../lib/LDAP.php',
'OCA\\User_LDAP\\LDAPProvider' => $baseDir . '/../lib/LDAPProvider.php',

View File

@ -49,6 +49,7 @@ class ComposerStaticInitUser_LDAP
'OCA\\User_LDAP\\ILDAPWrapper' => __DIR__ . '/..' . '/../lib/ILDAPWrapper.php',
'OCA\\User_LDAP\\IUserLDAP' => __DIR__ . '/..' . '/../lib/IUserLDAP.php',
'OCA\\User_LDAP\\Jobs\\CleanUp' => __DIR__ . '/..' . '/../lib/Jobs/CleanUp.php',
'OCA\\User_LDAP\\Jobs\\Sync' => __DIR__ . '/..' . '/../lib/Jobs/Sync.php',
'OCA\\User_LDAP\\Jobs\\UpdateGroups' => __DIR__ . '/..' . '/../lib/Jobs/UpdateGroups.php',
'OCA\\User_LDAP\\LDAP' => __DIR__ . '/..' . '/../lib/LDAP.php',
'OCA\\User_LDAP\\LDAPProvider' => __DIR__ . '/..' . '/../lib/LDAPProvider.php',

View File

@ -51,15 +51,16 @@ use OCA\User_LDAP\User\OfflineUser;
use OCA\User_LDAP\Mapping\AbstractMapping;
use OC\ServerNotAvailableException;
use OCP\IConfig;
/**
* Class Access
* @package OCA\User_LDAP
*/
class Access extends LDAPUtility implements IUserTools {
/**
* @var \OCA\User_LDAP\Connection
*/
const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
/** @var \OCA\User_LDAP\Connection */
public $connection;
/** @var Manager */
public $userManager;
@ -86,19 +87,27 @@ class Access extends LDAPUtility implements IUserTools {
* @var AbstractMapping $userMapper
*/
protected $groupMapper;
/**
* @var \OCA\User_LDAP\Helper
*/
private $helper;
/** @var IConfig */
private $config;
public function __construct(Connection $connection, ILDAPWrapper $ldap,
Manager $userManager, Helper $helper) {
public function __construct(
Connection $connection,
ILDAPWrapper $ldap,
Manager $userManager,
Helper $helper,
IConfig $config
) {
parent::__construct($ldap);
$this->connection = $connection;
$this->userManager = $userManager;
$this->userManager->setLdapAccess($this);
$this->helper = $helper;
$this->config = $config;
}
/**
@ -511,12 +520,16 @@ class Access extends LDAPUtility implements IUserTools {
/**
* returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
* @param string $dn the dn of the user object
* @param string $ldapName optional, the display name of the object
*
* @param string $fdn the dn of the user object
* @param string|null $ldapName optional, the display name of the object
* @param bool $isUser optional, whether it is a user object (otherwise group assumed)
* @return string|false with with the name to use in Nextcloud
* @param bool|null $newlyMapped
* @param array|null $record
* @return false|string with with the name to use in Nextcloud
*/
public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
$newlyMapped = false;
if($isUser) {
$mapper = $this->getUserMapper();
$nameAttribute = $this->connection->ldapUserDisplayName;
@ -526,18 +539,18 @@ class Access extends LDAPUtility implements IUserTools {
}
//let's try to retrieve the Nextcloud name from the mappings table
$ocName = $mapper->getNameByDN($fdn);
if(is_string($ocName)) {
return $ocName;
$ncName = $mapper->getNameByDN($fdn);
if(is_string($ncName)) {
return $ncName;
}
//second try: get the UUID and check if it is known. Then, update the DN and return the name.
$uuid = $this->getUUID($fdn, $isUser);
$uuid = $this->getUUID($fdn, $isUser, $record);
if(is_string($uuid)) {
$ocName = $mapper->getNameByUUID($uuid);
if(is_string($ocName)) {
$ncName = $mapper->getNameByUUID($uuid);
if(is_string($ncName)) {
$mapper->setDNbyUUID($fdn, $uuid);
return $ocName;
return $ncName;
}
} else {
//If the UUID can't be detected something is foul.
@ -577,6 +590,7 @@ class Access extends LDAPUtility implements IUserTools {
|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
if($mapper->map($fdn, $intName, $uuid)) {
$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
$newlyMapped = true;
return $intName;
}
}
@ -584,6 +598,7 @@ class Access extends LDAPUtility implements IUserTools {
$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
$newlyMapped = true;
return $altName;
}
@ -789,7 +804,7 @@ class Access extends LDAPUtility implements IUserTools {
* utilizing the login filter.
*
* @param string $loginName
* @return array
* @return int
*/
public function countUsersByLoginName($loginName) {
$loginName = $this->escapeFilterPart($loginName);
@ -803,11 +818,22 @@ class Access extends LDAPUtility implements IUserTools {
* @param string|string[] $attr
* @param int $limit
* @param int $offset
* @param bool $forceApplyAttributes
* @return array
*/
public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
$this->batchApplyUserAttributes($ldapRecords);
$recordsToUpdate = $ldapRecords;
if(!$forceApplyAttributes) {
$isBackgroundJobModeAjax = $this->config
->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
$newlyMapped = false;
$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
});
}
$this->batchApplyUserAttributes($recordsToUpdate);
return $this->fetchList($ldapRecords, (count($attr) > 1));
}
@ -824,7 +850,7 @@ class Access extends LDAPUtility implements IUserTools {
// displayName is obligatory
continue;
}
$ocName = $this->dn2ocname($userRecord['dn'][0]);
$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
if($ocName === false) {
continue;
}
@ -1221,7 +1247,9 @@ class Access extends LDAPUtility implements IUserTools {
if($key !== 'dn') {
$selection[$i][$key] = $this->resemblesDN($key) ?
$this->helper->sanitizeDN($item[$key])
: $item[$key];
: $key === 'objectguid' || $key === 'guid' ?
$selection[$i][$key] = $this->convertObjectGUID2Str($item[$key])
: $item[$key];
} else {
$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
}
@ -1513,12 +1541,14 @@ class Access extends LDAPUtility implements IUserTools {
/**
* auto-detects the directory's UUID attribute
*
* @param string $dn a known DN used to check against
* @param bool $isUser
* @param bool $force the detection should be run, even if it is not set to auto
* @param array|null $ldapRecord
* @return bool true on success, false otherwise
*/
private function detectUuidAttribute($dn, $isUser = true, $force = false) {
private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
if($isUser) {
$uuidAttr = 'ldapUuidUserAttribute';
$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
@ -1536,10 +1566,17 @@ class Access extends LDAPUtility implements IUserTools {
return true;
}
// for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
foreach(self::UUID_ATTRIBUTES as $attribute) {
if($ldapRecord !== null) {
// we have the info from LDAP already, we don't need to talk to the server again
if(isset($ldapRecord[$attribute])) {
$this->connection->$uuidAttr = $attribute;
return true;
} else {
continue;
}
}
foreach($testAttributes as $attribute) {
$value = $this->readAttribute($dn, $attribute);
if(is_array($value) && isset($value[0]) && !empty($value[0])) {
\OCP\Util::writeLog('user_ldap',
@ -1559,9 +1596,10 @@ class Access extends LDAPUtility implements IUserTools {
/**
* @param string $dn
* @param bool $isUser
* @return string|bool
* @param null $ldapRecord
* @return bool|string
*/
public function getUUID($dn, $isUser = true) {
public function getUUID($dn, $isUser = true, $ldapRecord = null) {
if($isUser) {
$uuidAttr = 'ldapUuidUserAttribute';
$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
@ -1571,13 +1609,16 @@ class Access extends LDAPUtility implements IUserTools {
}
$uuid = false;
if($this->detectUuidAttribute($dn, $isUser)) {
$uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
$attr = $this->connection->$uuidAttr;
$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
if( !is_array($uuid)
&& $uuidOverride !== ''
&& $this->detectUuidAttribute($dn, $isUser, true)) {
$uuid = $this->readAttribute($dn,
$this->connection->$uuidAttr);
&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
{
$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
? $ldapRecord[$this->connection->$uuidAttr]
: $this->readAttribute($dn, $this->connection->$uuidAttr);
}
if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
$uuid = $uuid[0];

View File

@ -282,6 +282,7 @@ class Configuration {
}
$this->saveValue($cta[$key], $value);
}
$this->saveValue('_lastChange', time());
$this->unsavedChanges = [];
}

View File

@ -54,6 +54,8 @@ use OC\ServerNotAvailableException;
* @property bool|mixed|void ldapGroupMemberAssocAttr
* @property string ldapUuidUserAttribute
* @property string ldapUuidGroupAttribute
* @property string ldapExpertUUIDUserAttr
* @property string ldapExpertUUIDGroupAttr
*/
class Connection extends LDAPUtility {
private $ldapConnectionRes = null;
@ -350,8 +352,8 @@ class Connection extends LDAPUtility {
if(!empty($uuidOverride)) {
$this->configuration->$effectiveSetting = $uuidOverride;
} else {
$uuidAttributes = array('auto', 'entryuuid', 'nsuniqueid',
'objectguid', 'guid', 'ipauniqueid');
$uuidAttributes = Access::UUID_ATTRIBUTES;
array_unshift($uuidAttributes, 'auto');
if(!in_array($this->configuration->$effectiveSetting,
$uuidAttributes)
&& (!is_null($this->configID))) {

View File

@ -0,0 +1,362 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 OCA\User_LDAP\Jobs;
use OC\BackgroundJob\TimedJob;
use OC\ServerNotAvailableException;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\Connection;
use OCA\User_LDAP\FilesystemHelper;
use OCA\User_LDAP\Helper;
use OCA\User_LDAP\LDAP;
use OCA\User_LDAP\LogWrapper;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\Manager;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\Image;
use OCP\IUserManager;
use OCP\Notification\IManager;
class Sync extends TimedJob {
const MAX_INTERVAL = 12 * 60 * 60; // 12h
const MIN_INTERVAL = 30 * 60; // 30min
/** @var Helper */
protected $ldapHelper;
/** @var LDAP */
protected $ldap;
/** @var Manager */
protected $userManager;
/** @var UserMapping */
protected $mapper;
/** @var IConfig */
protected $config;
/** @var IAvatarManager */
protected $avatarManager;
/** @var IDBConnection */
protected $dbc;
/** @var IUserManager */
protected $ncUserManager;
/** @var IManager */
protected $notificationManager;
public function __construct() {
$this->setInterval(
\OC::$server->getConfig()->getAppValue(
'user_ldap',
'background_sync_interval',
self::MIN_INTERVAL
)
);
}
/**
* updates the interval
*
* the idea is to adjust the interval depending on the amount of known users
* and the attempt to update each user one day. At most it would run every
* 30 minutes, and at least every 12 hours.
*/
public function updateInterval() {
$minPagingSize = $this->getMinPagingSize();
$mappedUsers = $this->mapper->count();
$runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
: $mappedUsers / $minPagingSize;
$interval = floor(24 * 60 * 60 / $runsPerDay);
$interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
$this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
}
/**
* returns the smallest configured paging size
* @return int
*/
protected function getMinPagingSize() {
$configKeys = $this->config->getAppKeys('user_ldap');
$configKeys = array_filter($configKeys, function($key) {
return strpos($key, 'ldap_paging_size') !== false;
});
$minPagingSize = null;
foreach ($configKeys as $configKey) {
$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
}
return (int)$minPagingSize;
}
/**
* @param array $argument
*/
protected function run($argument) {
$this->setArgument($argument);
$isBackgroundJobModeAjax = $this->config
->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
if($isBackgroundJobModeAjax) {
return;
}
$cycleData = $this->getCycle();
if($cycleData === null) {
$cycleData = $this->determineNextCycle();
if($cycleData === null) {
$this->updateInterval();
return;
}
}
if(!$this->qualifiesToRun($cycleData)) {
$this->updateInterval();
return;
}
try {
$expectMoreResults = $this->runCycle($cycleData);
if ($expectMoreResults) {
$this->increaseOffset($cycleData);
} else {
$this->determineNextCycle();
}
$this->updateInterval();
} catch (ServerNotAvailableException $e) {
$this->determineNextCycle();
}
}
/**
* @param array $cycleData
* @return bool whether more results are expected from the same configuration
*/
public function runCycle($cycleData) {
$connection = new Connection($this->ldap, $cycleData['prefix']);
$access = new Access($connection, $this->ldap, $this->userManager, $this->ldapHelper, $this->config);
$access->setUserMapper($this->mapper);
$filter = $access->combineFilterWithAnd(array(
$access->connection->ldapUserFilter,
$access->connection->ldapUserDisplayName . '=*',
$access->getFilterPartForUserSearch('')
));
$results = $access->fetchListOfUsers(
$filter,
$access->userManager->getAttributes(),
$connection->ldapPagingSize,
$cycleData['offset'],
true
);
if($connection->ldapPagingSize === 0) {
return true;
}
return count($results) !== $connection->ldapPagingSize;
}
/**
* returns the info about the current cycle that should be run, if any,
* otherwise null
*
* @return array|null
*/
public function getCycle() {
$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
if(count($prefixes) === 0) {
return null;
}
$cycleData = [
'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
];
if(
$cycleData['prefix'] !== null
&& in_array($cycleData['prefix'], $prefixes)
) {
return $cycleData;
}
return null;
}
/**
* Save the provided cycle information in the DB
*
* @param array $cycleData
*/
public function setCycle(array $cycleData) {
$this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
$this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
}
/**
* returns data about the next cycle that should run, if any, otherwise
* null. It also always goes for the next LDAP configuration!
*
* @param array|null $cycleData the old cycle
* @return array|null
*/
public function determineNextCycle(array $cycleData = null) {
$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
if(count($prefixes) === 0) {
return null;
}
// get the next prefix in line and remember it
$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
$prefix = $this->getNextPrefix($oldPrefix);
if($prefix === null) {
return null;
}
$cycleData['prefix'] = $prefix;
$cycleData['offset'] = 0;
$this->setCycle(['prefix' => $prefix, 'offset' => 0]);
return $cycleData;
}
/**
* Checks whether the provided cycle should be run. Currently only the
* last configuration change goes into account (at least one hour).
*
* @param $cycleData
* @return bool
*/
protected function qualifiesToRun($cycleData) {
$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
if((time() - $lastChange) > 60 * 30) {
return true;
}
return false;
}
/**
* increases the offset of the current cycle for the next run
*
* @param $cycleData
*/
protected function increaseOffset($cycleData) {
$ldapConfig = new Configuration($cycleData['prefix']);
$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
$this->setCycle($cycleData);
}
/**
* determines the next configuration prefix based on the last one (if any)
*
* @param string|null $lastPrefix
* @return string|null
*/
protected function getNextPrefix($lastPrefix) {
$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
$noOfPrefixes = count($prefixes);
if($noOfPrefixes === 0) {
return null;
}
$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
if($i === false) {
$i = -1;
} else {
$i++;
}
if(!isset($prefixes[$i])) {
$i = 0;
}
return $prefixes[$i];
}
/**
* "fixes" DI
*
* @param array $argument
*/
public function setArgument($argument) {
if(isset($argument['config'])) {
$this->config = $argument['config'];
} else {
$this->config = \OC::$server->getConfig();
}
if(isset($argument['helper'])) {
$this->ldapHelper = $argument['helper'];
} else {
$this->ldapHelper = new Helper($this->config);
}
if(isset($argument['ldapWrapper'])) {
$this->ldap = $argument['ldapWrapper'];
} else {
$this->ldap = new LDAP();
}
if(isset($argument['avatarManager'])) {
$this->avatarManager = $argument['avatarManager'];
} else {
$this->avatarManager = \OC::$server->getAvatarManager();
}
if(isset($argument['dbc'])) {
$this->dbc = $argument['dbc'];
} else {
$this->dbc = \OC::$server->getDatabaseConnection();
}
if(isset($argument['ncUserManager'])) {
$this->ncUserManager = $argument['ncUserManager'];
} else {
$this->ncUserManager = \OC::$server->getUserManager();
}
if(isset($argument['notificationManager'])) {
$this->notificationManager = $argument['notificationManager'];
} else {
$this->notificationManager = \OC::$server->getNotificationManager();
}
if(isset($argument['userManager'])) {
$this->userManager = $argument['userManager'];
} else {
$this->userManager = new Manager(
$this->config,
new FilesystemHelper(),
new LogWrapper(),
$this->avatarManager,
new Image(),
$this->dbc,
$this->ncUserManager,
$this->notificationManager
);
}
if(isset($argument['mapper'])) {
$this->mapper = $argument['mapper'];
} else {
$this->mapper = new UserMapping($this->dbc);
}
}
}

View File

@ -192,7 +192,7 @@ class UpdateGroups extends \OC\BackgroundJob\TimedJob {
\OC::$server->getUserManager(),
\OC::$server->getNotificationManager());
$connector = new Connection($ldapWrapper, $configPrefixes[0]);
$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper);
$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig());
$groupMapper = new GroupMapping($dbc);
$userMapper = new UserMapping($dbc);
$ldapAccess->setGroupMapper($groupMapper);

View File

@ -277,4 +277,19 @@ abstract class AbstractMapping {
->getTruncateTableSQL('`' . $this->getTableName() . '`');
return $this->dbc->prepare($sql)->execute();
}
/**
* returns the number of entries in the mappings table
*
* @return int
*/
public function count() {
$qb = $this->dbc->getQueryBuilder();
$query = $qb->select($qb->createFunction('COUNT(`ldap_dn`)'))
->from($this->getTableName());
$res = $query->execute();
$count = $res->fetchColumn();
$res->closeCursor();
return (int)$count;
}
}

View File

@ -82,7 +82,7 @@ abstract class Proxy {
new Manager($ocConfig, $fs, $log, $avatarM, new \OCP\Image(), $db,
$coreUserManager, $coreNotificationManager);
$connector = new Connection($this->ldap, $configPrefix);
$access = new Access($connector, $this->ldap, $userManager, new Helper(\OC::$server->getConfig()));
$access = new Access($connector, $this->ldap, $userManager, new Helper($ocConfig), $ocConfig);
$access->setUserMapper($userMap);
$access->setGroupMapper($groupMap);
self::$accesses[$configPrefix] = $access;

View File

@ -28,6 +28,7 @@
namespace OCA\User_LDAP\User;
use OC\Cache\CappedMemoryCache;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\LogWrapper;
use OCA\User_LDAP\FilesystemHelper;
use OCP\IAvatarManager;
@ -167,8 +168,9 @@ class Manager {
* @return string[]
*/
public function getAttributes($minimal = false) {
$attributes = array('dn', 'uid', 'samaccountname', 'memberof');
$attributes = array_merge(Access::UUID_ATTRIBUTES, ['dn', 'uid', 'samaccountname', 'memberof']);
$possible = array(
$this->access->getConnection()->ldapExpertUUIDUserAttr,
$this->access->getConnection()->ldapQuotaAttribute,
$this->access->getConnection()->ldapEmailAttribute,
$this->access->getConnection()->ldapUserDisplayName,

View File

@ -190,13 +190,6 @@ class User {
}
unset($attr);
//Email
$attr = strtolower($this->connection->ldapEmailAttribute);
if(isset($ldapEntry[$attr])) {
$this->updateEmail($ldapEntry[$attr][0]);
}
unset($attr);
//displayName
$displayName = $displayName2 = '';
$attr = strtolower($this->connection->ldapUserDisplayName);
@ -217,6 +210,15 @@ class User {
}
unset($attr);
//Email
//email must be stored after displayname, because it would cause a user
//change event that will trigger fetching the display name again
$attr = strtolower($this->connection->ldapEmailAttribute);
if(isset($ldapEntry[$attr])) {
$this->updateEmail($ldapEntry[$attr][0]);
}
unset($attr);
// LDAP Username, needed for s2s sharing
if(isset($ldapEntry['uid'])) {
$this->storeLDAPUserName($ldapEntry['uid'][0]);

View File

@ -278,7 +278,7 @@ class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserIn
Util::writeLog('user_ldap',
'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
Util::DEBUG);
//do the search and translate results to owncloud names
//do the search and translate results to Nextcloud names
$ldap_users = $this->access->fetchListOfUsers(
$filter,
$this->access->userManager->getAttributes(true),

View File

@ -41,13 +41,16 @@ use OCA\User_LDAP\Helper;
use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\LDAP;
use OCA\User_LDAP\LogWrapper;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\Manager;
use OCA\User_LDAP\User\User;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\Image;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
use Test\TestCase;
/**
* Class AccessTest
@ -56,7 +59,7 @@ use OCP\Notification\IManager as INotificationManager;
*
* @package OCA\User_LDAP\Tests
*/
class AccessTest extends \Test\TestCase {
class AccessTest extends TestCase {
/** @var Connection|\PHPUnit_Framework_MockObject_MockObject */
private $connection;
/** @var LDAP|\PHPUnit_Framework_MockObject_MockObject */
@ -65,6 +68,8 @@ class AccessTest extends \Test\TestCase {
private $userManager;
/** @var Helper|\PHPUnit_Framework_MockObject_MockObject */
private $helper;
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
private $config;
/** @var Access */
private $access;
@ -73,12 +78,14 @@ class AccessTest extends \Test\TestCase {
$this->ldap = $this->createMock(LDAP::class);
$this->userManager = $this->createMock(Manager::class);
$this->helper = $this->createMock(Helper::class);
$this->config = $this->createMock(IConfig::class);
$this->access = new Access(
$this->connection,
$this->ldap,
$this->userManager,
$this->helper
$this->helper,
$this->config
);
}
@ -104,38 +111,30 @@ class AccessTest extends \Test\TestCase {
}
public function testEscapeFilterPartValidChars() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$input = 'okay';
$this->assertTrue($input === $access->escapeFilterPart($input));
$this->assertTrue($input === $this->access->escapeFilterPart($input));
}
public function testEscapeFilterPartEscapeWildcard() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$input = '*';
$expected = '\\\\*';
$this->assertTrue($expected === $access->escapeFilterPart($input));
$this->assertTrue($expected === $this->access->escapeFilterPart($input));
}
public function testEscapeFilterPartEscapeWildcard2() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$input = 'foo*bar';
$expected = 'foo\\\\*bar';
$this->assertTrue($expected === $access->escapeFilterPart($input));
$this->assertTrue($expected === $this->access->escapeFilterPart($input));
}
/** @dataProvider convertSID2StrSuccessData */
/**
* @dataProvider convertSID2StrSuccessData
* @param array $sidArray
* @param $sidExpected
*/
public function testConvertSID2StrSuccess(array $sidArray, $sidExpected) {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$sidBinary = implode('', $sidArray);
$this->assertSame($sidExpected, $access->convertSID2Str($sidBinary));
$this->assertSame($sidExpected, $this->access->convertSID2Str($sidBinary));
}
public function convertSID2StrSuccessData() {
@ -166,48 +165,39 @@ class AccessTest extends \Test\TestCase {
}
public function testConvertSID2StrInputError() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$sidIllegal = 'foobar';
$sidExpected = '';
$this->assertSame($sidExpected, $access->convertSID2Str($sidIllegal));
$this->assertSame($sidExpected, $this->access->convertSID2Str($sidIllegal));
}
public function testGetDomainDNFromDNSuccess() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$inputDN = 'uid=zaphod,cn=foobar,dc=my,dc=server,dc=com';
$domainDN = 'dc=my,dc=server,dc=com';
$lw->expects($this->once())
$this->ldap->expects($this->once())
->method('explodeDN')
->with($inputDN, 0)
->will($this->returnValue(explode(',', $inputDN)));
$this->assertSame($domainDN, $access->getDomainDNFromDN($inputDN));
$this->assertSame($domainDN, $this->access->getDomainDNFromDN($inputDN));
}
public function testGetDomainDNFromDNError() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$inputDN = 'foobar';
$expected = '';
$lw->expects($this->once())
$this->ldap->expects($this->once())
->method('explodeDN')
->with($inputDN, 0)
->will($this->returnValue(false));
$this->assertSame($expected, $access->getDomainDNFromDN($inputDN));
$this->assertSame($expected, $this->access->getDomainDNFromDN($inputDN));
}
private function getResemblesDNInputData() {
return $cases = array(
array(
public function dnInputDataProvider() {
return [[
[
'input' => 'foo=bar,bar=foo,dc=foobar',
'interResult' => array(
'count' => 3,
@ -216,108 +206,194 @@ class AccessTest extends \Test\TestCase {
2 => 'dc=foobar'
),
'expectedResult' => true
),
array(
],
[
'input' => 'foobarbarfoodcfoobar',
'interResult' => false,
'expectedResult' => false
)
);
]
]];
}
public function testStringResemblesDN() {
/**
* @dataProvider dnInputDataProvider
*/
public function testStringResemblesDN($case) {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject $config */
$config = $this->createMock(IConfig::class);
$access = new Access($con, $lw, $um, $helper, $config);
$cases = $this->getResemblesDNInputData();
$lw->expects($this->exactly(2))
$lw->expects($this->exactly(1))
->method('explodeDN')
->will($this->returnCallback(function ($dn) use ($cases) {
foreach($cases as $case) {
if($dn === $case['input']) {
return $case['interResult'];
}
->will($this->returnCallback(function ($dn) use ($case) {
if($dn === $case['input']) {
return $case['interResult'];
}
return null;
}));
foreach($cases as $case) {
$this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
}
$this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
}
public function testStringResemblesDNLDAPmod() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$lw = new \OCA\User_LDAP\LDAP();
$access = new Access($con, $lw, $um, $helper);
/**
* @dataProvider dnInputDataProvider
* @param $case
*/
public function testStringResemblesDNLDAPmod($case) {
list(, $con, $um, $helper) = $this->getConnectorAndLdapMock();
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject $config */
$config = $this->createMock(IConfig::class);
$lw = new LDAP();
$access = new Access($con, $lw, $um, $helper, $config);
if(!function_exists('ldap_explode_dn')) {
$this->markTestSkipped('LDAP Module not available');
}
$cases = $this->getResemblesDNInputData();
foreach($cases as $case) {
$this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
}
$this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
}
public function testCacheUserHome() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$con->expects($this->once())
$this->connection->expects($this->once())
->method('writeToCache');
$access->cacheUserHome('foobar', '/foobars/path');
$this->access->cacheUserHome('foobar', '/foobars/path');
}
public function testBatchApplyUserAttributes() {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
$access = new Access($con, $lw, $um, $helper);
$mapperMock = $this->getMockBuilder('\OCA\User_LDAP\Mapping\UserMapping')
->disableOriginalConstructor()
->getMock();
$this->ldap->expects($this->any())
->method('isResource')
->willReturn(true);
$this->ldap->expects($this->any())
->method('getAttributes')
->willReturn(['displayname' => ['bar', 'count' => 1]]);
/** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
->will($this->returnValue('a_username'));
->willReturn(false);
$mapperMock->expects($this->any())
->method('map')
->willReturn(true);
$userMock = $this->getMockBuilder('\OCA\User_LDAP\User\User')
->disableOriginalConstructor()
->getMock();
$userMock = $this->createMock(User::class);
$access->connection->expects($this->any())
// also returns for userUuidAttribute
$this->access->connection->expects($this->any())
->method('__get')
->will($this->returnValue('displayName'));
$access->setUserMapper($mapperMock);
$this->access->setUserMapper($mapperMock);
$displayNameAttribute = strtolower($access->connection->ldapUserDisplayName);
$data = array(
array(
'dn' => 'foobar',
$displayNameAttribute = strtolower($this->access->connection->ldapUserDisplayName);
$data = [
[
'dn' => ['foobar'],
$displayNameAttribute => 'barfoo'
),
array(
'dn' => 'foo',
],
[
'dn' => ['foo'],
$displayNameAttribute => 'bar'
),
array(
'dn' => 'raboof',
],
[
'dn' => ['raboof'],
$displayNameAttribute => 'oofrab'
)
);
]
];
$userMock->expects($this->exactly(count($data)))
->method('processAttributes');
$um->expects($this->exactly(count($data)))
$this->userManager->expects($this->exactly(count($data)))
->method('get')
->will($this->returnValue($userMock));
$access->batchApplyUserAttributes($data);
$this->access->batchApplyUserAttributes($data);
}
public function testBatchApplyUserAttributesSkipped() {
/** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
->will($this->returnValue('a_username'));
$userMock = $this->createMock(User::class);
$this->access->connection->expects($this->any())
->method('__get')
->will($this->returnValue('displayName'));
$this->access->setUserMapper($mapperMock);
$displayNameAttribute = strtolower($this->access->connection->ldapUserDisplayName);
$data = [
[
'dn' => ['foobar'],
$displayNameAttribute => 'barfoo'
],
[
'dn' => ['foo'],
$displayNameAttribute => 'bar'
],
[
'dn' => ['raboof'],
$displayNameAttribute => 'oofrab'
]
];
$userMock->expects($this->never())
->method('processAttributes');
$this->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
$this->access->batchApplyUserAttributes($data);
}
public function testBatchApplyUserAttributesDontSkip() {
/** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
->will($this->returnValue('a_username'));
$userMock = $this->createMock(User::class);
$this->access->connection->expects($this->any())
->method('__get')
->will($this->returnValue('displayName'));
$this->access->setUserMapper($mapperMock);
$displayNameAttribute = strtolower($this->access->connection->ldapUserDisplayName);
$data = [
[
'dn' => ['foobar'],
$displayNameAttribute => 'barfoo'
],
[
'dn' => ['foo'],
$displayNameAttribute => 'bar'
],
[
'dn' => ['raboof'],
$displayNameAttribute => 'oofrab'
]
];
$userMock->expects($this->exactly(count($data)))
->method('processAttributes');
$this->userManager->expects($this->exactly(count($data)))
->method('get')
->will($this->returnValue($userMock));
$this->access->batchApplyUserAttributes($data);
}
public function dNAttributeProvider() {
@ -332,24 +408,25 @@ class AccessTest extends \Test\TestCase {
/**
* @dataProvider dNAttributeProvider
* @param $attribute
*/
public function testSanitizeDN($attribute) {
list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject $config */
$config = $this->createMock(IConfig::class);
$dnFromServer = 'cn=Mixed Cases,ou=Are Sufficient To,ou=Test,dc=example,dc=org';
$lw->expects($this->any())
->method('isResource')
->will($this->returnValue(true));
$lw->expects($this->any())
->method('getAttributes')
->will($this->returnValue(array(
$attribute => array('count' => 1, $dnFromServer)
)));
$access = new Access($con, $lw, $um, $helper);
$access = new Access($con, $lw, $um, $helper, $config);
$values = $access->readAttribute('uid=whoever,dc=example,dc=org', $attribute);
$this->assertSame($values[0], strtolower($dnFromServer));
}

View File

@ -32,9 +32,13 @@
namespace OCA\User_LDAP\Tests;
use OCA\User_LDAP\GroupPluginManager;
use OCP\GroupInterface;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
use OCA\User_LDAP\Group_LDAP as GroupLDAP;
use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\User\Manager;
/**
* Class GroupLDAPTest
@ -44,6 +48,9 @@ use OCA\User_LDAP\ILDAPWrapper;
* @package OCA\User_LDAP\Tests
*/
class Group_LDAPTest extends \Test\TestCase {
/**
* @return \PHPUnit_Framework_MockObject_MockObject|Access
*/
private function getAccessMock() {
static $conMethods;
static $accMethods;
@ -57,14 +64,8 @@ class Group_LDAPTest extends \Test\TestCase {
->setMethods($conMethods)
->setConstructorArgs([$lw, null, null])
->getMock();
$um = $this->getMockBuilder('\OCA\User_LDAP\User\Manager')
->disableOriginalConstructor()
->getMock();
$helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig());
$access = $this->getMockBuilder('\OCA\User_LDAP\Access')
->setMethods($accMethods)
->setConstructorArgs([$connector, $lw, $um, $helper])
->getMock();
$access = $this->createMock(Access::class);
$access->expects($this->any())
->method('getConnection')
@ -76,8 +77,13 @@ class Group_LDAPTest extends \Test\TestCase {
private function getPluginManagerMock() {
return $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')->getMock();
}
/**
* @param Access|\PHPUnit_Framework_MockObject_MockObject $access
*/
private function enableGroups($access) {
$access->connection = $this->createMock(Connection::class);
$access->connection->expects($this->any())
->method('__get')
->will($this->returnCallback(function($name) {
@ -154,6 +160,7 @@ class Group_LDAPTest extends \Test\TestCase {
}
public function testCountUsersWithPlugin() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions','countUsersInGroup'])
->getMock();
@ -168,10 +175,10 @@ class Group_LDAPTest extends \Test\TestCase {
->with('gid', 'search')
->willReturn(42);
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$this->assertEquals($ldap->countUsersInGroup('gid', 'search'),42);
}
@ -498,7 +505,6 @@ class Group_LDAPTest extends \Test\TestCase {
$access->connection->expects($this->any())
->method('getFromCache')
->will($this->returnValue(null));
$access->expects($this->any())
->method('readAttribute')
->will($this->returnCallback(function($dn, $attr) {
@ -509,14 +515,13 @@ class Group_LDAPTest extends \Test\TestCase {
}
return array();
}));
$access->expects($this->any())
->method('groupname2dn')
->will($this->returnValue('cn=foobar,dc=foo,dc=bar'));
$access->expects($this->exactly(2))
->method('nextcloudUserNames')
->willReturnOnConsecutiveCalls(['lisa', 'bart', 'kira', 'brad'], ['walle', 'dino', 'xenia']);
$access->userManager = $this->createMock(Manager::class);
$groupBackend = new GroupLDAP($access, $pluginManager);
$users = $groupBackend->usersInGroup('foobar');
@ -537,7 +542,6 @@ class Group_LDAPTest extends \Test\TestCase {
$access->connection->expects($this->any())
->method('getFromCache')
->will($this->returnValue(null));
$access->expects($this->any())
->method('readAttribute')
->will($this->returnCallback(function($dn, $attr) {
@ -546,14 +550,13 @@ class Group_LDAPTest extends \Test\TestCase {
}
return array();
}));
$access->expects($this->any())
->method('groupname2dn')
->will($this->returnValue('cn=foobar,dc=foo,dc=bar'));
$access->expects($this->once())
->method('nextcloudUserNames')
->will($this->returnValue(array('lisa', 'bart', 'kira', 'brad')));
$access->userManager = $this->createMock(Manager::class);
$groupBackend = new GroupLDAP($access, $pluginManager);
$users = $groupBackend->usersInGroup('foobar');
@ -635,6 +638,7 @@ class Group_LDAPTest extends \Test\TestCase {
$access = $this->getAccessMock();
$pluginManager = $this->getPluginManagerMock();
$access->connection = $this->createMock(Connection::class);
$access->connection->expects($this->any())
->method('__get')
->will($this->returnCallback(function($name) {
@ -671,6 +675,7 @@ class Group_LDAPTest extends \Test\TestCase {
$access = $this->getAccessMock();
$pluginManager = $this->getPluginManagerMock();
$access->connection = $this->createMock(Connection::class);
$access->connection->expects($this->any())
->method('__get')
->will($this->returnCallback(function($name) {
@ -724,6 +729,7 @@ class Group_LDAPTest extends \Test\TestCase {
}
public function testCreateGroupWithPlugin() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions','createGroup'])
->getMock();
@ -738,10 +744,10 @@ class Group_LDAPTest extends \Test\TestCase {
->with('gid')
->willReturn('result');
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$this->assertEquals($ldap->createGroup('gid'),true);
}
@ -750,6 +756,7 @@ class Group_LDAPTest extends \Test\TestCase {
* @expectedException \Exception
*/
public function testCreateGroupFailing() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions', 'createGroup'])
->getMock();
@ -759,15 +766,16 @@ class Group_LDAPTest extends \Test\TestCase {
->with(GroupInterface::CREATE_GROUP)
->willReturn(false);
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$ldap->createGroup('gid');
}
public function testDeleteGroupWithPlugin() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions','deleteGroup'])
->getMock();
@ -782,21 +790,19 @@ class Group_LDAPTest extends \Test\TestCase {
->with('gid')
->willReturn('result');
$access = $this->getAccessMock();
$mapper = $this->getMockBuilder('\OCA\User_LDAP\Mapping\GroupMapping')
->setMethods(['unmap'])
->disableOriginalConstructor()
->getMock();
$access = $this->getAccessMock();
$access->expects($this->any())
->method('getGroupMapper')
->will($this->returnValue($mapper));
$ldap = new GroupLDAP(
$access,
$pluginManager
);
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$this->assertEquals($ldap->deleteGroup('gid'),'result');
}
@ -805,6 +811,7 @@ class Group_LDAPTest extends \Test\TestCase {
* @expectedException \Exception
*/
public function testDeleteGroupFailing() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions', 'deleteGroup'])
->getMock();
@ -814,15 +821,16 @@ class Group_LDAPTest extends \Test\TestCase {
->with(GroupInterface::DELETE_GROUP)
->willReturn(false);
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$ldap->deleteGroup('gid');
}
public function testAddToGroupWithPlugin() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions','addToGroup'])
->getMock();
@ -837,10 +845,10 @@ class Group_LDAPTest extends \Test\TestCase {
->with('uid', 'gid')
->willReturn('result');
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$this->assertEquals($ldap->addToGroup('uid', 'gid'),'result');
}
@ -849,6 +857,7 @@ class Group_LDAPTest extends \Test\TestCase {
* @expectedException \Exception
*/
public function testAddToGroupFailing() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions', 'addToGroup'])
->getMock();
@ -858,15 +867,16 @@ class Group_LDAPTest extends \Test\TestCase {
->with(GroupInterface::ADD_TO_GROUP)
->willReturn(false);
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$ldap->addToGroup('uid', 'gid');
}
public function testRemoveFromGroupWithPlugin() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions','removeFromGroup'])
->getMock();
@ -881,10 +891,10 @@ class Group_LDAPTest extends \Test\TestCase {
->with('uid', 'gid')
->willReturn('result');
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$this->assertEquals($ldap->removeFromGroup('uid', 'gid'),'result');
}
@ -893,6 +903,7 @@ class Group_LDAPTest extends \Test\TestCase {
* @expectedException \Exception
*/
public function testRemoveFromGroupFailing() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions', 'removeFromGroup'])
->getMock();
@ -902,15 +913,16 @@ class Group_LDAPTest extends \Test\TestCase {
->with(GroupInterface::REMOVE_FROM_GROUP)
->willReturn(false);
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$ldap->removeFromGroup('uid', 'gid');
}
public function testGetGroupDetailsWithPlugin() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions','getGroupDetails'])
->getMock();
@ -925,10 +937,10 @@ class Group_LDAPTest extends \Test\TestCase {
->with('gid')
->willReturn('result');
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$this->assertEquals($ldap->getGroupDetails('gid'),'result');
}
@ -937,6 +949,7 @@ class Group_LDAPTest extends \Test\TestCase {
* @expectedException \Exception
*/
public function testGetGroupDetailsFailing() {
/** @var GroupPluginManager|\PHPUnit_Framework_MockObject_MockObject $pluginManager */
$pluginManager = $this->getMockBuilder('\OCA\User_LDAP\GroupPluginManager')
->setMethods(['implementsActions', 'getGroupDetails'])
->getMock();
@ -946,10 +959,10 @@ class Group_LDAPTest extends \Test\TestCase {
->with(GroupInterface::GROUP_DETAILS)
->willReturn(false);
$ldap = new GroupLDAP(
$this->getAccessMock(),
$pluginManager
);
$access = $this->getAccessMock();
$access->connection = $this->createMock(Connection::class);
$ldap = new GroupLDAP($access, $pluginManager);
$ldap->getGroupDetails('gid');
}

View File

@ -140,7 +140,7 @@ abstract class AbstractIntegrationTest {
* initializes the Access test instance
*/
protected function initAccess() {
$this->access = new Access($this->connection, $this->ldap, $this->userManager, $this->helper);
$this->access = new Access($this->connection, $this->ldap, $this->userManager, $this->helper, \OC::$server->getConfig());
}
/**

View File

@ -0,0 +1,144 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 OCA\User_LDAP\Tests\Jobs;
use OCA\User_LDAP\Helper;
use OCA\User_LDAP\Jobs\Sync;
use OCA\User_LDAP\LDAP;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\Manager;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IUserManager;
use OCP\Notification\IManager;
use Test\TestCase;
class SyncTest extends TestCase {
/** @var array */
protected $arguments;
/** @var Helper|\PHPUnit_Framework_MockObject_MockObject */
protected $helper;
/** @var LDAP|\PHPUnit_Framework_MockObject_MockObject */
protected $ldapWrapper;
/** @var Manager|\PHPUnit_Framework_MockObject_MockObject */
protected $userManager;
/** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject */
protected $mapper;
/** @var Sync */
protected $sync;
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
protected $config;
/** @var IAvatarManager|\PHPUnit_Framework_MockObject_MockObject */
protected $avatarManager;
/** @var IDBConnection|\PHPUnit_Framework_MockObject_MockObject */
protected $dbc;
/** @var IUserManager|\PHPUnit_Framework_MockObject_MockObject */
protected $ncUserManager;
/** @var IManager|\PHPUnit_Framework_MockObject_MockObject */
protected $notificationManager;
public function setUp() {
parent::setUp();
$this->helper = $this->createMock(Helper::class);
$this->ldapWrapper = $this->createMock(LDAP::class);
$this->userManager = $this->createMock(Manager::class);
$this->mapper = $this->createMock(UserMapping::class);
$this->config = $this->createMock(IConfig::class);
$this->avatarManager = $this->createMock(IAvatarManager::class);
$this->dbc = $this->createMock(IDBConnection::class);
$this->ncUserManager = $this->createMock(IUserManager::class);
$this->notificationManager = $this->createMock(IManager::class);
$this->arguments = [
'helper' => $this->helper,
'ldapWrapper' => $this->ldapWrapper,
'userManager' => $this->userManager,
'mapper' => $this->mapper,
'config' => $this->config,
'avatarManager' => $this->avatarManager,
'dbc' => $this->dbc,
'ncUserManager' => $this->ncUserManager,
'notificationManager' => $this->notificationManager,
];
$this->sync = new Sync();
}
public function intervalDataProvider() {
return [
[
0, 1000, 750
],
[
22, 0, 50
],
[
500, 500, 500
],
[
1357, 0, 0
],
[
421337, 2000, 3000
]
];
}
/**
* @dataProvider intervalDataProvider
*/
public function testUpdateInterval($userCount, $pagingSize1, $pagingSize2) {
$this->config->expects($this->once())
->method('setAppValue')
->with('user_ldap', 'background_sync_interval', $this->anything())
->willReturnCallback(function($a, $k, $interval) {
$this->assertTrue($interval >= SYNC::MIN_INTERVAL);
$this->assertTrue($interval <= SYNC::MAX_INTERVAL);
return true;
});
$this->config->expects($this->atLeastOnce())
->method('getAppKeys')
->willReturn([
'blabla',
'ldap_paging_size',
's07blabla',
'installed',
's07ldap_paging_size'
]);
$this->config->expects($this->exactly(2))
->method('getAppValue')
->willReturnOnConsecutiveCalls($pagingSize1, $pagingSize2);
$this->mapper->expects($this->atLeastOnce())
->method('count')
->willReturn($userCount);
$this->sync->setArgument($this->arguments);
$this->sync->updateInterval();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -81,12 +81,6 @@ class User_LDAPTest extends TestCase {
* @return \PHPUnit_Framework_MockObject_MockObject|Access
*/
private function getAccessMock() {
$lw = $this->createMock(ILDAPWrapper::class);
$connector = $this->getMockBuilder(Connection::class)
->setMethodsExcept(['getConnection'])
->setConstructorArgs([$lw, null, null])
->getMock();
$this->configMock = $this->createMock(IConfig::class);
$this->offlineUser = $this->createMock(OfflineUser::class);
@ -106,18 +100,16 @@ class User_LDAPTest extends TestCase {
])
->getMock();
$um->expects($this->any())
->method('getDeletedUser')
->will($this->returnValue($this->offlineUser));
/** @var Connection|\PHPUnit_Framework_MockObject_MockObject $connection */
$connection = $this->createMock(Connection::class);
$helper = new Helper(\OC::$server->getConfig());
/** @var Manager|\PHPUnit_Framework_MockObject_MockObject $userManager */
$userManager = $this->createMock(Manager::class);
$access = $this->getMockBuilder(Access::class)
->setMethodsExcept(['getConnection'])
->setConstructorArgs([$connector, $lw, $um, $helper])
->getMock();
$um->setLdapAccess($access);
/** @var Access|\PHPUnit_Framework_MockObject_MockObject $access */
$access = $this->createMock(Access::class);
$access->connection = $connection;
$access->userManager = $userManager;
return $access;
}
@ -211,11 +203,19 @@ class User_LDAPTest extends TestCase {
}
public function testCheckPasswordUidReturn() {
$access = $this->getAccessMock();
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
->willReturn('gunslinger');
$access = $this->getAccessMock();
$this->prepareAccessForCheckPassword($access);
$access->userManager->expects($this->any())
->method('get')
->willReturn($user);
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
\OC_User::useBackend($backend);
$result = $backend->checkPassword('roland', 'dt19');
@ -246,11 +246,12 @@ class User_LDAPTest extends TestCase {
public function testCheckPasswordNoDisplayName() {
$access = $this->getAccessMock();
$this->prepareAccessForCheckPassword($access, true);
$access->expects($this->once())
->method('username2dn')
->will($this->returnValue(false));
$this->prepareAccessForCheckPassword($access);
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn(null);
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
\OC_User::useBackend($backend);
@ -260,8 +261,17 @@ class User_LDAPTest extends TestCase {
}
public function testCheckPasswordPublicAPI() {
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
->willReturn('gunslinger');
$access = $this->getAccessMock();
$this->prepareAccessForCheckPassword($access);
$access->userManager->expects($this->any())
->method('get')
->willReturn($user);
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
\OC_User::useBackend($backend);
@ -308,6 +318,9 @@ class User_LDAPTest extends TestCase {
$access->expects($this->once())
->method('getUserMapper')
->will($this->returnValue($mapping));
$access->connection->expects($this->any())
->method('getConnectionResource')
->willReturn('this is an ldap link');
$this->configMock->expects($this->any())
->method('getUserValue')
@ -320,6 +333,9 @@ class User_LDAPTest extends TestCase {
$this->offlineUser->expects($this->once())
->method('getOCName')
->willReturn($uid);
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($this->offlineUser);
$backend = new UserLDAP($access, $this->configMock, $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
@ -516,6 +532,11 @@ class User_LDAPTest extends TestCase {
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
$this->prepareMockForUserExists($access);
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getDN')
->willReturn('dnOfRoland,dc=test');
$access->expects($this->any())
->method('readAttribute')
->will($this->returnCallback(function($dn) {
@ -524,6 +545,12 @@ class User_LDAPTest extends TestCase {
}
return false;
}));
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($user);
$access->expects($this->any())
->method('getUserMapper')
->willReturn($this->createMock(UserMapping::class));
//test for existing user
$result = $backend->userExists('gunslinger');
@ -547,8 +574,13 @@ class User_LDAPTest extends TestCase {
return false;
}));
$access->userManager = $this->createMock(Manager::class);
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($this->createMock(User::class));
//test for deleted user
$result = $backend->userExists('formerUser');
$backend->userExists('formerUser');
}
public function testUserExistsForNeverExisting() {
@ -576,6 +608,11 @@ class User_LDAPTest extends TestCase {
$this->prepareMockForUserExists($access);
\OC_User::useBackend($backend);
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getDN')
->willReturn('dnOfRoland,dc=test');
$access->expects($this->any())
->method('readAttribute')
->will($this->returnCallback(function($dn) {
@ -584,6 +621,12 @@ class User_LDAPTest extends TestCase {
}
return false;
}));
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($user);
$access->expects($this->any())
->method('getUserMapper')
->willReturn($this->createMock(UserMapping::class));
//test for existing user
$result = \OCP\User::userExists('gunslinger');
@ -607,9 +650,13 @@ class User_LDAPTest extends TestCase {
}
return false;
}));
$access->userManager = $this->createMock(Manager::class);
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($this->createMock(User::class));
//test for deleted user
$result = \OCP\User::userExists('formerUser');
\OCP\User::userExists('formerUser');
}
public function testUserExistsPublicAPIForNeverExisting() {
@ -672,7 +719,22 @@ class User_LDAPTest extends TestCase {
}
}));
//absolut path
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
->willReturn('gunslinger');
$user->expects($this->any())
->method('getDN')
->willReturn('dnOfRoland,dc=test');
$user->expects($this->any())
->method('getHomePath')
->willReturn('/tmp/rolandshome/');
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($user);
//absolute path
$result = $backend->getHome('gunslinger');
$this->assertEquals('/tmp/rolandshome/', $result);
}
@ -687,10 +749,6 @@ class User_LDAPTest extends TestCase {
$dataDir = \OC::$server->getConfig()->getSystemValue(
'datadirectory', \OC::$SERVERROOT.'/data');
$this->configMock->expects($this->once())
->method('getSystemValue')
->will($this->returnValue($dataDir));
$access->connection->expects($this->any())
->method('__get')
->will($this->returnCallback(function($name) {
@ -715,6 +773,21 @@ class User_LDAPTest extends TestCase {
}
}));
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
->willReturn('ladyofshadows');
$user->expects($this->any())
->method('getDN')
->willReturn('dnOfLadyOfShadows,dc=test');
$user->expects($this->any())
->method('getHomePath')
->willReturn($dataDir.'/susannah/');
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($user);
$result = $backend->getHome('ladyofshadows');
$this->assertEquals($dataDir.'/susannah/', $result);
}
@ -745,6 +818,18 @@ class User_LDAPTest extends TestCase {
}
}));
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
->willReturn('newyorker');
$user->expects($this->any())
->method('getHomePath')
->willThrowException(new \Exception());
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($user);
//no path at all triggers OC default behaviour
$result = $backend->getHome('newyorker');
$this->assertFalse($result);
@ -786,6 +871,10 @@ class User_LDAPTest extends TestCase {
$this->offlineUser->expects($this->never())
->method('getHomePath');
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($this->offlineUser);
$backend->getHome($uid);
}
@ -852,14 +941,6 @@ class User_LDAPTest extends TestCase {
}
}));
$userMapper = $this->getMockBuilder('\OCA\User_LDAP\Mapping\UserMapping')
->disableOriginalConstructor()
->getMock();
$access->expects($this->any())
->method('getUserMapper')
->will($this->returnValue($userMapper));
$access->method('fetchUsersByLoginName')
->willReturn([]);
}
@ -876,6 +957,42 @@ class User_LDAPTest extends TestCase {
return true;
}));
$user1 = $this->createMock(User::class);
$user1->expects($this->once())
->method('composeAndStoreDisplayName')
->willReturn('Roland Deschain');
$user1->expects($this->any())
->method('getDN')
->willReturn('dnOfRoland,dc=test');
$user2 = $this->createMock(User::class);
$user2->expects($this->never())
->method('composeAndStoreDisplayName');
$user2->expects($this->any())
->method('getDN')
->willReturn('another DN');
$mapper = $this->createMock(UserMapping::class);
$mapper->expects($this->any())
->method('getUUIDByDN')
->willReturnCallback(function($dn) { return $dn; });
$access->userManager->expects($this->any())
->method('get')
->willReturnCallback(function($uid) use ($user1, $user2) {
if($uid === 'gunslinger') {
return $user1;
} else if($uid === 'newyorker') {
return $user2;
}
});
$access->expects($this->any())
->method('getUserMapper')
->willReturn($mapper);
$access->expects($this->any())
->method('getUserDnByUuid')
->willReturnCallback(function($uuid) { return $uuid . '1'; });
//with displayName
$result = $backend->getDisplayName('gunslinger');
$this->assertEquals('Roland Deschain', $result);
@ -919,6 +1036,42 @@ class User_LDAPTest extends TestCase {
\OC_User::useBackend($backend);
$user1 = $this->createMock(User::class);
$user1->expects($this->once())
->method('composeAndStoreDisplayName')
->willReturn('Roland Deschain');
$user1->expects($this->any())
->method('getDN')
->willReturn('dnOfRoland,dc=test');
$user2 = $this->createMock(User::class);
$user2->expects($this->never())
->method('composeAndStoreDisplayName');
$user2->expects($this->any())
->method('getDN')
->willReturn('another DN');
$mapper = $this->createMock(UserMapping::class);
$mapper->expects($this->any())
->method('getUUIDByDN')
->willReturnCallback(function($dn) { return $dn; });
$access->userManager->expects($this->any())
->method('get')
->willReturnCallback(function($uid) use ($user1, $user2) {
if($uid === 'gunslinger') {
return $user1;
} else if($uid === 'newyorker') {
return $user2;
}
});
$access->expects($this->any())
->method('getUserMapper')
->willReturn($mapper);
$access->expects($this->any())
->method('getUserDnByUuid')
->willReturnCallback(function($uuid) { return $uuid . '1'; });
//with displayName
$result = \OCP\User::getDisplayName('gunslinger');
$this->assertEquals('Roland Deschain', $result);
@ -1028,11 +1181,11 @@ class User_LDAPTest extends TestCase {
->method('fetchUsersByLoginName')
->with($this->equalTo($loginName))
->willReturn([['dn' => [$dn]]]);
$access->expects($this->once())
$access->expects($this->any())
->method('stringResemblesDN')
->with($this->equalTo($dn))
->willReturn(true);
$access->expects($this->once())
$access->expects($this->any())
->method('dn2username')
->with($this->equalTo($dn))
->willReturn($username);
@ -1046,6 +1199,16 @@ class User_LDAPTest extends TestCase {
->with($this->equalTo('loginName2UserName-'.$loginName), $this->equalTo($username));
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
->willReturn('alice');
$access->userManager->expects($this->atLeastOnce())
->method('get')
->with($dn)
->willReturn($user);
$name = $backend->loginName2UserName($loginName);
$this->assertSame($username, $name);
@ -1084,7 +1247,6 @@ class User_LDAPTest extends TestCase {
public function testLoginName2UserNameOfflineUser() {
$loginName = 'Alice';
$username = 'alice';
$dn = 'uid=alice,dc=what,dc=ever';
$offlineUser = $this->getMockBuilder(OfflineUser::class)
@ -1096,13 +1258,6 @@ class User_LDAPTest extends TestCase {
->method('fetchUsersByLoginName')
->with($this->equalTo($loginName))
->willReturn([['dn' => [$dn]]]);
$access->expects($this->once())
->method('stringResemblesDN')
->with($this->equalTo($dn))
->willReturn(true);
$access->expects($this->once())
->method('dn2username')
->willReturn(false); // this is fake, but allows us to force-enter the OfflineUser path
$access->connection->expects($this->exactly(2))
->method('getFromCache')
@ -1112,14 +1267,10 @@ class User_LDAPTest extends TestCase {
->method('writeToCache')
->with($this->equalTo('loginName2UserName-'.$loginName), $this->equalTo(false));
$access->userManager->expects($this->once())
->method('getDeletedUser')
->will($this->returnValue($offlineUser));
//$config = $this->createMock(IConfig::class);
$this->configMock->expects($this->once())
->method('getUserValue')
->willReturn(1);
$access->userManager->expects($this->any())
->method('get')
->with($dn)
->willReturn($offlineUser);
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
$name = $backend->loginName2UserName($loginName);
@ -1192,6 +1343,10 @@ class User_LDAPTest extends TestCase {
}
return true;
}));
$access->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($this->createMock(User::class));
}
/**
@ -1212,7 +1367,16 @@ class User_LDAPTest extends TestCase {
$access = $this->getAccessMock();
$this->prepareAccessForSetPassword($access);
$access->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());
$access->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
\OC_User::useBackend($backend);
$this->assertTrue(\OC_User::setPassword('roland', 'dt12234$'));
@ -1220,6 +1384,9 @@ class User_LDAPTest extends TestCase {
public function testSetPasswordValidDisabled() {
$access = $this->getAccessMock();
$access->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
$this->prepareAccessForSetPassword($access, false);
$backend = new UserLDAP($access, $this->createMock(IConfig::class), $this->createMock(INotificationManager::class), $this->createMock(Session::class), $this->getDefaultPluginManagerMock());

View File

@ -28,8 +28,11 @@
namespace OCA\User_LDAP\Tests;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\ILDAPWrapper;
use \OCA\User_LDAP\Wizard;
use Test\TestCase;
/**
* Class Test_Wizard
@ -38,7 +41,7 @@ use \OCA\User_LDAP\Wizard;
*
* @package OCA\User_LDAP\Tests
*/
class WizardTest extends \Test\TestCase {
class WizardTest extends TestCase {
protected function setUp() {
parent::setUp();
//we need to make sure the consts are defined, otherwise tests will fail
@ -62,30 +65,22 @@ class WizardTest extends \Test\TestCase {
$connMethods = get_class_methods('\OCA\User_LDAP\Connection');
$accMethods = get_class_methods('\OCA\User_LDAP\Access');
}
/** @var ILDAPWrapper|\PHPUnit_Framework_MockObject_MockObject $lw */
$lw = $this->createMock(ILDAPWrapper::class);
$conf = $this->getMockBuilder('\OCA\User_LDAP\Configuration')
/** @var Configuration|\PHPUnit_Framework_MockObject_MockObject $conf */
$conf = $this->getMockBuilder(Configuration::class)
->setMethods($confMethods)
->setConstructorArgs([$lw, null, null])
->getMock();
$connector = $this->getMockBuilder('\OCA\User_LDAP\Connection')
->setMethods($connMethods)
->setConstructorArgs([$lw, null, null])
->getMock();
$um = $this->getMockBuilder('\OCA\User_LDAP\User\Manager')
->disableOriginalConstructor()
->getMock();
$helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig());
$access = $this->getMockBuilder('\OCA\User_LDAP\Access')
->setMethods($accMethods)
->setConstructorArgs([$connector, $lw, $um, $helper])
->getMock();
/** @var Access|\PHPUnit_Framework_MockObject_MockObject $access */
$access = $this->createMock(Access::class);
return array(new Wizard($conf, $lw, $access), $conf, $lw, $access);
}
private function prepareLdapWrapperForConnections(&$ldap) {
private function prepareLdapWrapperForConnections(\PHPUnit_Framework_MockObject_MockObject &$ldap) {
$ldap->expects($this->once())
->method('connect')
//dummy value, usually invalid