You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

User.php 24KB

8 years ago
8 years ago
LDAP User Cleanup: Port from stable7 without further adjustements LDAP User Cleanup background job for user clean up adjust user backend for clean up register background job remove dead code dependency injection make Helper non-static for proper testing check whether it is OK to run clean up job. Do not forget to pass arguments. use correct method to get the config from server methods can be private, proper indirect testing is given no automatic user deletion make limit readable for test purposes make method less complex add first tests let preferences accept limit and offset for getUsersForValue DI via constructor does not work for background jobs after detecting, now we have retrieving deleted users and their details we need this method to be public for now finalize export method, add missing getter clean up namespaces and get rid of unnecessary files helper is not static anymore cleanup according to scrutinizer add cli tool to show deleted users uses are necessary after recent namespace change also remove user from mappings table on deletion add occ command to delete users fix use statement improve output big fixes / improvements PHP doc return true in userExists early for cleaning up deleted users bump version control state and interval with one config.php setting, now ldapUserCleanupInterval. 0 will disable it. enabled by default. improve doc rename cli method to be consistent with others introduce ldapUserCleanupInterval in sample config don't show last login as unix epoche start when no login happend less log output consistent namespace for OfflineUser rename GarbageCollector to DeletedUsersIndex and move it to user subdir fix unit tests add tests for deleteUser more test adjustements Conflicts: apps/user_ldap/ajax/clearMappings.php apps/user_ldap/appinfo/app.php apps/user_ldap/lib/access.php apps/user_ldap/lib/helper.php apps/user_ldap/tests/helper.php core/register_command.php lib/private/preferences.php lib/private/user.php add ldap:check-user to check user existance on the fly Conflicts: apps/user_ldap/lib/helper.php forgotten file PHPdoc fixes, no code change and don't forget to adjust tests
9 years ago
LDAP User Cleanup: Port from stable7 without further adjustements LDAP User Cleanup background job for user clean up adjust user backend for clean up register background job remove dead code dependency injection make Helper non-static for proper testing check whether it is OK to run clean up job. Do not forget to pass arguments. use correct method to get the config from server methods can be private, proper indirect testing is given no automatic user deletion make limit readable for test purposes make method less complex add first tests let preferences accept limit and offset for getUsersForValue DI via constructor does not work for background jobs after detecting, now we have retrieving deleted users and their details we need this method to be public for now finalize export method, add missing getter clean up namespaces and get rid of unnecessary files helper is not static anymore cleanup according to scrutinizer add cli tool to show deleted users uses are necessary after recent namespace change also remove user from mappings table on deletion add occ command to delete users fix use statement improve output big fixes / improvements PHP doc return true in userExists early for cleaning up deleted users bump version control state and interval with one config.php setting, now ldapUserCleanupInterval. 0 will disable it. enabled by default. improve doc rename cli method to be consistent with others introduce ldapUserCleanupInterval in sample config don't show last login as unix epoche start when no login happend less log output consistent namespace for OfflineUser rename GarbageCollector to DeletedUsersIndex and move it to user subdir fix unit tests add tests for deleteUser more test adjustements Conflicts: apps/user_ldap/ajax/clearMappings.php apps/user_ldap/appinfo/app.php apps/user_ldap/lib/access.php apps/user_ldap/lib/helper.php apps/user_ldap/tests/helper.php core/register_command.php lib/private/preferences.php lib/private/user.php add ldap:check-user to check user existance on the fly Conflicts: apps/user_ldap/lib/helper.php forgotten file PHPdoc fixes, no code change and don't forget to adjust tests
9 years ago
LDAP User Cleanup: Port from stable7 without further adjustements LDAP User Cleanup background job for user clean up adjust user backend for clean up register background job remove dead code dependency injection make Helper non-static for proper testing check whether it is OK to run clean up job. Do not forget to pass arguments. use correct method to get the config from server methods can be private, proper indirect testing is given no automatic user deletion make limit readable for test purposes make method less complex add first tests let preferences accept limit and offset for getUsersForValue DI via constructor does not work for background jobs after detecting, now we have retrieving deleted users and their details we need this method to be public for now finalize export method, add missing getter clean up namespaces and get rid of unnecessary files helper is not static anymore cleanup according to scrutinizer add cli tool to show deleted users uses are necessary after recent namespace change also remove user from mappings table on deletion add occ command to delete users fix use statement improve output big fixes / improvements PHP doc return true in userExists early for cleaning up deleted users bump version control state and interval with one config.php setting, now ldapUserCleanupInterval. 0 will disable it. enabled by default. improve doc rename cli method to be consistent with others introduce ldapUserCleanupInterval in sample config don't show last login as unix epoche start when no login happend less log output consistent namespace for OfflineUser rename GarbageCollector to DeletedUsersIndex and move it to user subdir fix unit tests add tests for deleteUser more test adjustements Conflicts: apps/user_ldap/ajax/clearMappings.php apps/user_ldap/appinfo/app.php apps/user_ldap/lib/access.php apps/user_ldap/lib/helper.php apps/user_ldap/tests/helper.php core/register_command.php lib/private/preferences.php lib/private/user.php add ldap:check-user to check user existance on the fly Conflicts: apps/user_ldap/lib/helper.php forgotten file PHPdoc fixes, no code change and don't forget to adjust tests
9 years ago
LDAP User Cleanup: Port from stable7 without further adjustements LDAP User Cleanup background job for user clean up adjust user backend for clean up register background job remove dead code dependency injection make Helper non-static for proper testing check whether it is OK to run clean up job. Do not forget to pass arguments. use correct method to get the config from server methods can be private, proper indirect testing is given no automatic user deletion make limit readable for test purposes make method less complex add first tests let preferences accept limit and offset for getUsersForValue DI via constructor does not work for background jobs after detecting, now we have retrieving deleted users and their details we need this method to be public for now finalize export method, add missing getter clean up namespaces and get rid of unnecessary files helper is not static anymore cleanup according to scrutinizer add cli tool to show deleted users uses are necessary after recent namespace change also remove user from mappings table on deletion add occ command to delete users fix use statement improve output big fixes / improvements PHP doc return true in userExists early for cleaning up deleted users bump version control state and interval with one config.php setting, now ldapUserCleanupInterval. 0 will disable it. enabled by default. improve doc rename cli method to be consistent with others introduce ldapUserCleanupInterval in sample config don't show last login as unix epoche start when no login happend less log output consistent namespace for OfflineUser rename GarbageCollector to DeletedUsersIndex and move it to user subdir fix unit tests add tests for deleteUser more test adjustements Conflicts: apps/user_ldap/ajax/clearMappings.php apps/user_ldap/appinfo/app.php apps/user_ldap/lib/access.php apps/user_ldap/lib/helper.php apps/user_ldap/tests/helper.php core/register_command.php lib/private/preferences.php lib/private/user.php add ldap:check-user to check user existance on the fly Conflicts: apps/user_ldap/lib/helper.php forgotten file PHPdoc fixes, no code change and don't forget to adjust tests
9 years ago
LDAP User Cleanup: Port from stable7 without further adjustements LDAP User Cleanup background job for user clean up adjust user backend for clean up register background job remove dead code dependency injection make Helper non-static for proper testing check whether it is OK to run clean up job. Do not forget to pass arguments. use correct method to get the config from server methods can be private, proper indirect testing is given no automatic user deletion make limit readable for test purposes make method less complex add first tests let preferences accept limit and offset for getUsersForValue DI via constructor does not work for background jobs after detecting, now we have retrieving deleted users and their details we need this method to be public for now finalize export method, add missing getter clean up namespaces and get rid of unnecessary files helper is not static anymore cleanup according to scrutinizer add cli tool to show deleted users uses are necessary after recent namespace change also remove user from mappings table on deletion add occ command to delete users fix use statement improve output big fixes / improvements PHP doc return true in userExists early for cleaning up deleted users bump version control state and interval with one config.php setting, now ldapUserCleanupInterval. 0 will disable it. enabled by default. improve doc rename cli method to be consistent with others introduce ldapUserCleanupInterval in sample config don't show last login as unix epoche start when no login happend less log output consistent namespace for OfflineUser rename GarbageCollector to DeletedUsersIndex and move it to user subdir fix unit tests add tests for deleteUser more test adjustements Conflicts: apps/user_ldap/ajax/clearMappings.php apps/user_ldap/appinfo/app.php apps/user_ldap/lib/access.php apps/user_ldap/lib/helper.php apps/user_ldap/tests/helper.php core/register_command.php lib/private/preferences.php lib/private/user.php add ldap:check-user to check user existance on the fly Conflicts: apps/user_ldap/lib/helper.php forgotten file PHPdoc fixes, no code change and don't forget to adjust tests
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Philipp Staiger <philipp@staiger.it>
  12. * @author Roger Szabo <roger.szabo@web.de>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  15. * @author Vincent Petry <vincent@nextcloud.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OCA\User_LDAP\User;
  33. use OCA\User_LDAP\Access;
  34. use OCA\User_LDAP\Connection;
  35. use OCA\User_LDAP\Exceptions\AttributeNotSet;
  36. use OCA\User_LDAP\FilesystemHelper;
  37. use OCP\IAvatarManager;
  38. use OCP\IConfig;
  39. use OCP\ILogger;
  40. use OCP\Image;
  41. use OCP\IUser;
  42. use OCP\IUserManager;
  43. use OCP\Notification\IManager as INotificationManager;
  44. use Psr\Log\LoggerInterface;
  45. /**
  46. * User
  47. *
  48. * represents an LDAP user, gets and holds user-specific information from LDAP
  49. */
  50. class User {
  51. /**
  52. * @var Access
  53. */
  54. protected $access;
  55. /**
  56. * @var Connection
  57. */
  58. protected $connection;
  59. /**
  60. * @var IConfig
  61. */
  62. protected $config;
  63. /**
  64. * @var FilesystemHelper
  65. */
  66. protected $fs;
  67. /**
  68. * @var Image
  69. */
  70. protected $image;
  71. /**
  72. * @var LoggerInterface
  73. */
  74. protected $logger;
  75. /**
  76. * @var IAvatarManager
  77. */
  78. protected $avatarManager;
  79. /**
  80. * @var IUserManager
  81. */
  82. protected $userManager;
  83. /**
  84. * @var INotificationManager
  85. */
  86. protected $notificationManager;
  87. /**
  88. * @var string
  89. */
  90. protected $dn;
  91. /**
  92. * @var string
  93. */
  94. protected $uid;
  95. /**
  96. * @var string[]
  97. */
  98. protected $refreshedFeatures = [];
  99. /**
  100. * @var string
  101. */
  102. protected $avatarImage;
  103. /**
  104. * DB config keys for user preferences
  105. */
  106. public const USER_PREFKEY_FIRSTLOGIN = 'firstLoginAccomplished';
  107. /**
  108. * @brief constructor, make sure the subclasses call this one!
  109. * @param string $username the internal username
  110. * @param string $dn the LDAP DN
  111. */
  112. public function __construct($username, $dn, Access $access,
  113. IConfig $config, FilesystemHelper $fs, Image $image,
  114. LoggerInterface $logger, IAvatarManager $avatarManager, IUserManager $userManager,
  115. INotificationManager $notificationManager) {
  116. if ($username === null) {
  117. $logger->error("uid for '$dn' must not be null!", ['app' => 'user_ldap']);
  118. throw new \InvalidArgumentException('uid must not be null!');
  119. } elseif ($username === '') {
  120. $logger->error("uid for '$dn' must not be an empty string", ['app' => 'user_ldap']);
  121. throw new \InvalidArgumentException('uid must not be an empty string!');
  122. }
  123. $this->access = $access;
  124. $this->connection = $access->getConnection();
  125. $this->config = $config;
  126. $this->fs = $fs;
  127. $this->dn = $dn;
  128. $this->uid = $username;
  129. $this->image = $image;
  130. $this->logger = $logger;
  131. $this->avatarManager = $avatarManager;
  132. $this->userManager = $userManager;
  133. $this->notificationManager = $notificationManager;
  134. \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
  135. }
  136. /**
  137. * marks a user as deleted
  138. *
  139. * @throws \OCP\PreConditionNotMetException
  140. */
  141. public function markUser() {
  142. $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
  143. if ($curValue === '1') {
  144. // the user is already marked, do not write to DB again
  145. return;
  146. }
  147. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
  148. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
  149. }
  150. /**
  151. * processes results from LDAP for attributes as returned by getAttributesToRead()
  152. * @param array $ldapEntry the user entry as retrieved from LDAP
  153. */
  154. public function processAttributes($ldapEntry) {
  155. //Quota
  156. $attr = strtolower($this->connection->ldapQuotaAttribute);
  157. if (isset($ldapEntry[$attr])) {
  158. $this->updateQuota($ldapEntry[$attr][0]);
  159. } else {
  160. if ($this->connection->ldapQuotaDefault !== '') {
  161. $this->updateQuota();
  162. }
  163. }
  164. unset($attr);
  165. //displayName
  166. $displayName = $displayName2 = '';
  167. $attr = strtolower($this->connection->ldapUserDisplayName);
  168. if (isset($ldapEntry[$attr])) {
  169. $displayName = (string)$ldapEntry[$attr][0];
  170. }
  171. $attr = strtolower($this->connection->ldapUserDisplayName2);
  172. if (isset($ldapEntry[$attr])) {
  173. $displayName2 = (string)$ldapEntry[$attr][0];
  174. }
  175. if ($displayName !== '') {
  176. $this->composeAndStoreDisplayName($displayName, $displayName2);
  177. $this->access->cacheUserDisplayName(
  178. $this->getUsername(),
  179. $displayName,
  180. $displayName2
  181. );
  182. }
  183. unset($attr);
  184. //Email
  185. //email must be stored after displayname, because it would cause a user
  186. //change event that will trigger fetching the display name again
  187. $attr = strtolower($this->connection->ldapEmailAttribute);
  188. if (isset($ldapEntry[$attr])) {
  189. $this->updateEmail($ldapEntry[$attr][0]);
  190. }
  191. unset($attr);
  192. // LDAP Username, needed for s2s sharing
  193. if (isset($ldapEntry['uid'])) {
  194. $this->storeLDAPUserName($ldapEntry['uid'][0]);
  195. } elseif (isset($ldapEntry['samaccountname'])) {
  196. $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
  197. }
  198. //homePath
  199. if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
  200. $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
  201. if (isset($ldapEntry[$attr])) {
  202. $this->access->cacheUserHome(
  203. $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
  204. }
  205. }
  206. //memberOf groups
  207. $cacheKey = 'getMemberOf'.$this->getUsername();
  208. $groups = false;
  209. if (isset($ldapEntry['memberof'])) {
  210. $groups = $ldapEntry['memberof'];
  211. }
  212. $this->connection->writeToCache($cacheKey, $groups);
  213. //external storage var
  214. $attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
  215. if (isset($ldapEntry[$attr])) {
  216. $this->updateExtStorageHome($ldapEntry[$attr][0]);
  217. }
  218. unset($attr);
  219. //Avatar
  220. /** @var Connection $connection */
  221. $connection = $this->access->getConnection();
  222. $attributes = $connection->resolveRule('avatar');
  223. foreach ($attributes as $attribute) {
  224. if (isset($ldapEntry[$attribute])) {
  225. $this->avatarImage = $ldapEntry[$attribute][0];
  226. // the call to the method that saves the avatar in the file
  227. // system must be postponed after the login. It is to ensure
  228. // external mounts are mounted properly (e.g. with login
  229. // credentials from the session).
  230. \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
  231. break;
  232. }
  233. }
  234. }
  235. /**
  236. * @brief returns the LDAP DN of the user
  237. * @return string
  238. */
  239. public function getDN() {
  240. return $this->dn;
  241. }
  242. /**
  243. * @brief returns the Nextcloud internal username of the user
  244. * @return string
  245. */
  246. public function getUsername() {
  247. return $this->uid;
  248. }
  249. /**
  250. * returns the home directory of the user if specified by LDAP settings
  251. * @param string $valueFromLDAP
  252. * @return bool|string
  253. * @throws \Exception
  254. */
  255. public function getHomePath($valueFromLDAP = null) {
  256. $path = (string)$valueFromLDAP;
  257. $attr = null;
  258. if (is_null($valueFromLDAP)
  259. && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
  260. && $this->access->connection->homeFolderNamingRule !== 'attr:') {
  261. $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
  262. $homedir = $this->access->readAttribute(
  263. $this->access->username2dn($this->getUsername()), $attr);
  264. if ($homedir && isset($homedir[0])) {
  265. $path = $homedir[0];
  266. }
  267. }
  268. if ($path !== '') {
  269. //if attribute's value is an absolute path take this, otherwise append it to data dir
  270. //check for / at the beginning or pattern c:\ resp. c:/
  271. if ('/' !== $path[0]
  272. && !(3 < strlen($path) && ctype_alpha($path[0])
  273. && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
  274. ) {
  275. $path = $this->config->getSystemValue('datadirectory',
  276. \OC::$SERVERROOT.'/data') . '/' . $path;
  277. }
  278. //we need it to store it in the DB as well in case a user gets
  279. //deleted so we can clean up afterwards
  280. $this->config->setUserValue(
  281. $this->getUsername(), 'user_ldap', 'homePath', $path
  282. );
  283. return $path;
  284. }
  285. if (!is_null($attr)
  286. && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
  287. ) {
  288. // a naming rule attribute is defined, but it doesn't exist for that LDAP user
  289. throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
  290. }
  291. //false will apply default behaviour as defined and done by OC_User
  292. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
  293. return false;
  294. }
  295. public function getMemberOfGroups() {
  296. $cacheKey = 'getMemberOf'.$this->getUsername();
  297. $memberOfGroups = $this->connection->getFromCache($cacheKey);
  298. if (!is_null($memberOfGroups)) {
  299. return $memberOfGroups;
  300. }
  301. $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
  302. $this->connection->writeToCache($cacheKey, $groupDNs);
  303. return $groupDNs;
  304. }
  305. /**
  306. * @brief reads the image from LDAP that shall be used as Avatar
  307. * @return string data (provided by LDAP) | false
  308. */
  309. public function getAvatarImage() {
  310. if (!is_null($this->avatarImage)) {
  311. return $this->avatarImage;
  312. }
  313. $this->avatarImage = false;
  314. /** @var Connection $connection */
  315. $connection = $this->access->getConnection();
  316. $attributes = $connection->resolveRule('avatar');
  317. foreach ($attributes as $attribute) {
  318. $result = $this->access->readAttribute($this->dn, $attribute);
  319. if ($result !== false && is_array($result) && isset($result[0])) {
  320. $this->avatarImage = $result[0];
  321. break;
  322. }
  323. }
  324. return $this->avatarImage;
  325. }
  326. /**
  327. * @brief marks the user as having logged in at least once
  328. * @return null
  329. */
  330. public function markLogin() {
  331. $this->config->setUserValue(
  332. $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
  333. }
  334. /**
  335. * Stores a key-value pair in relation to this user
  336. *
  337. * @param string $key
  338. * @param string $value
  339. */
  340. private function store($key, $value) {
  341. $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
  342. }
  343. /**
  344. * Composes the display name and stores it in the database. The final
  345. * display name is returned.
  346. *
  347. * @param string $displayName
  348. * @param string $displayName2
  349. * @return string the effective display name
  350. */
  351. public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
  352. $displayName2 = (string)$displayName2;
  353. if ($displayName2 !== '') {
  354. $displayName .= ' (' . $displayName2 . ')';
  355. }
  356. $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
  357. if ($oldName !== $displayName) {
  358. $this->store('displayName', $displayName);
  359. $user = $this->userManager->get($this->getUsername());
  360. if (!empty($oldName) && $user instanceof \OC\User\User) {
  361. // if it was empty, it would be a new record, not a change emitting the trigger could
  362. // potentially cause a UniqueConstraintViolationException, depending on some factors.
  363. $user->triggerChange('displayName', $displayName, $oldName);
  364. }
  365. }
  366. return $displayName;
  367. }
  368. /**
  369. * Stores the LDAP Username in the Database
  370. * @param string $userName
  371. */
  372. public function storeLDAPUserName($userName) {
  373. $this->store('uid', $userName);
  374. }
  375. /**
  376. * @brief checks whether an update method specified by feature was run
  377. * already. If not, it will marked like this, because it is expected that
  378. * the method will be run, when false is returned.
  379. * @param string $feature email | quota | avatar (can be extended)
  380. * @return bool
  381. */
  382. private function wasRefreshed($feature) {
  383. if (isset($this->refreshedFeatures[$feature])) {
  384. return true;
  385. }
  386. $this->refreshedFeatures[$feature] = 1;
  387. return false;
  388. }
  389. /**
  390. * fetches the email from LDAP and stores it as Nextcloud user value
  391. * @param string $valueFromLDAP if known, to save an LDAP read request
  392. * @return null
  393. */
  394. public function updateEmail($valueFromLDAP = null) {
  395. if ($this->wasRefreshed('email')) {
  396. return;
  397. }
  398. $email = (string)$valueFromLDAP;
  399. if (is_null($valueFromLDAP)) {
  400. $emailAttribute = $this->connection->ldapEmailAttribute;
  401. if ($emailAttribute !== '') {
  402. $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
  403. if (is_array($aEmail) && (count($aEmail) > 0)) {
  404. $email = (string)$aEmail[0];
  405. }
  406. }
  407. }
  408. if ($email !== '') {
  409. $user = $this->userManager->get($this->uid);
  410. if (!is_null($user)) {
  411. $currentEmail = (string)$user->getSystemEMailAddress();
  412. if ($currentEmail !== $email) {
  413. $user->setEMailAddress($email);
  414. }
  415. }
  416. }
  417. }
  418. /**
  419. * Overall process goes as follow:
  420. * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
  421. * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
  422. * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
  423. * 4. check if the target user exists and set the quota for the user.
  424. *
  425. * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
  426. * parameter can be passed with the value of the attribute. This value will be considered as the
  427. * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
  428. * fetch all the user's attributes in one call and use the fetched values in this function.
  429. * The expected value for that parameter is a string describing the quota for the user. Valid
  430. * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
  431. * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
  432. *
  433. * fetches the quota from LDAP and stores it as Nextcloud user value
  434. * @param ?string $valueFromLDAP the quota attribute's value can be passed,
  435. * to save the readAttribute request
  436. * @return void
  437. */
  438. public function updateQuota($valueFromLDAP = null) {
  439. if ($this->wasRefreshed('quota')) {
  440. return;
  441. }
  442. $quotaAttribute = $this->connection->ldapQuotaAttribute;
  443. $defaultQuota = $this->connection->ldapQuotaDefault;
  444. if ($quotaAttribute === '' && $defaultQuota === '') {
  445. return;
  446. }
  447. $quota = false;
  448. if (is_null($valueFromLDAP) && $quotaAttribute !== '') {
  449. $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
  450. if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
  451. $quota = $aQuota[0];
  452. } elseif (is_array($aQuota) && isset($aQuota[0])) {
  453. $this->logger->debug('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ['app' => 'user_ldap']);
  454. }
  455. } elseif (!is_null($valueFromLDAP) && $this->verifyQuotaValue($valueFromLDAP)) {
  456. $quota = $valueFromLDAP;
  457. } else {
  458. $this->logger->debug('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ['app' => 'user_ldap']);
  459. }
  460. if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
  461. // quota not found using the LDAP attribute (or not parseable). Try the default quota
  462. $quota = $defaultQuota;
  463. } elseif ($quota === false) {
  464. $this->logger->debug('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ['app' => 'user_ldap']);
  465. return;
  466. }
  467. $targetUser = $this->userManager->get($this->uid);
  468. if ($targetUser instanceof IUser) {
  469. $targetUser->setQuota($quota);
  470. } else {
  471. $this->logger->info('trying to set a quota for user ' . $this->uid . ' but the user is missing', ['app' => 'user_ldap']);
  472. }
  473. }
  474. private function verifyQuotaValue(string $quotaValue) {
  475. return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
  476. }
  477. /**
  478. * called by a post_login hook to save the avatar picture
  479. *
  480. * @param array $params
  481. */
  482. public function updateAvatarPostLogin($params) {
  483. if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
  484. $this->updateAvatar();
  485. }
  486. }
  487. /**
  488. * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
  489. * @return bool
  490. */
  491. public function updateAvatar($force = false) {
  492. if (!$force && $this->wasRefreshed('avatar')) {
  493. return false;
  494. }
  495. $avatarImage = $this->getAvatarImage();
  496. if ($avatarImage === false) {
  497. //not set, nothing left to do;
  498. return false;
  499. }
  500. if (!$this->image->loadFromBase64(base64_encode($avatarImage))) {
  501. return false;
  502. }
  503. // use the checksum before modifications
  504. $checksum = md5($this->image->data());
  505. if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
  506. return true;
  507. }
  508. $isSet = $this->setOwnCloudAvatar();
  509. if ($isSet) {
  510. // save checksum only after successful setting
  511. $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
  512. }
  513. return $isSet;
  514. }
  515. /**
  516. * @brief sets an image as Nextcloud avatar
  517. * @return bool
  518. */
  519. private function setOwnCloudAvatar() {
  520. if (!$this->image->valid()) {
  521. $this->logger->error('avatar image data from LDAP invalid for '.$this->dn, ['app' => 'user_ldap']);
  522. return false;
  523. }
  524. //make sure it is a square and not bigger than 128x128
  525. $size = min([$this->image->width(), $this->image->height(), 128]);
  526. if (!$this->image->centerCrop($size)) {
  527. $this->logger->error('croping image for avatar failed for '.$this->dn, ['app' => 'user_ldap']);
  528. return false;
  529. }
  530. if (!$this->fs->isLoaded()) {
  531. $this->fs->setup($this->uid);
  532. }
  533. try {
  534. $avatar = $this->avatarManager->getAvatar($this->uid);
  535. $avatar->set($this->image);
  536. return true;
  537. } catch (\Exception $e) {
  538. \OC::$server->getLogger()->logException($e, [
  539. 'message' => 'Could not set avatar for ' . $this->dn,
  540. 'level' => ILogger::INFO,
  541. 'app' => 'user_ldap',
  542. ]);
  543. }
  544. return false;
  545. }
  546. /**
  547. * @throws AttributeNotSet
  548. * @throws \OC\ServerNotAvailableException
  549. * @throws \OCP\PreConditionNotMetException
  550. */
  551. public function getExtStorageHome():string {
  552. $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
  553. if ($value !== '') {
  554. return $value;
  555. }
  556. $value = $this->updateExtStorageHome();
  557. if ($value !== '') {
  558. return $value;
  559. }
  560. throw new AttributeNotSet(sprintf(
  561. 'external home storage attribute yield no value for %s', $this->getUsername()
  562. ));
  563. }
  564. /**
  565. * @throws \OCP\PreConditionNotMetException
  566. * @throws \OC\ServerNotAvailableException
  567. */
  568. public function updateExtStorageHome(string $valueFromLDAP = null):string {
  569. if ($valueFromLDAP === null) {
  570. $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
  571. } else {
  572. $extHomeValues = [$valueFromLDAP];
  573. }
  574. if ($extHomeValues && isset($extHomeValues[0])) {
  575. $extHome = $extHomeValues[0];
  576. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
  577. return $extHome;
  578. } else {
  579. $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
  580. return '';
  581. }
  582. }
  583. /**
  584. * called by a post_login hook to handle password expiry
  585. *
  586. * @param array $params
  587. */
  588. public function handlePasswordExpiry($params) {
  589. $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
  590. if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
  591. return;//password expiry handling disabled
  592. }
  593. $uid = $params['uid'];
  594. if (isset($uid) && $uid === $this->getUsername()) {
  595. //retrieve relevant user attributes
  596. $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
  597. if (array_key_exists('pwdpolicysubentry', $result[0])) {
  598. $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
  599. if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
  600. $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
  601. }
  602. }
  603. $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
  604. $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
  605. $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
  606. //retrieve relevant password policy attributes
  607. $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
  608. $result = $this->connection->getFromCache($cacheKey);
  609. if (is_null($result)) {
  610. $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
  611. $this->connection->writeToCache($cacheKey, $result);
  612. }
  613. $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
  614. $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
  615. $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
  616. //handle grace login
  617. if (!empty($pwdGraceUseTime)) { //was this a grace login?
  618. if (!empty($pwdGraceAuthNLimit)
  619. && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
  620. $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
  621. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  622. 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
  623. } else { //no more grace login available
  624. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  625. 'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
  626. }
  627. exit();
  628. }
  629. //handle pwdReset attribute
  630. if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
  631. $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
  632. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  633. 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
  634. exit();
  635. }
  636. //handle password expiry warning
  637. if (!empty($pwdChangedTime)) {
  638. if (!empty($pwdMaxAge)
  639. && !empty($pwdExpireWarning)) {
  640. $pwdMaxAgeInt = (int)$pwdMaxAge[0];
  641. $pwdExpireWarningInt = (int)$pwdExpireWarning[0];
  642. if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
  643. $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
  644. $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
  645. $currentDateTime = new \DateTime();
  646. $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
  647. if ($secondsToExpiry <= $pwdExpireWarningInt) {
  648. //remove last password expiry warning if any
  649. $notification = $this->notificationManager->createNotification();
  650. $notification->setApp('user_ldap')
  651. ->setUser($uid)
  652. ->setObject('pwd_exp_warn', $uid)
  653. ;
  654. $this->notificationManager->markProcessed($notification);
  655. //create new password expiry warning
  656. $notification = $this->notificationManager->createNotification();
  657. $notification->setApp('user_ldap')
  658. ->setUser($uid)
  659. ->setDateTime($currentDateTime)
  660. ->setObject('pwd_exp_warn', $uid)
  661. ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
  662. ;
  663. $this->notificationManager->notify($notification);
  664. }
  665. }
  666. }
  667. }
  668. }
  669. }
  670. }