User.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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 false|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($this->access->username2dn($this->getUsername()), $attr);
  263. if ($homedir && isset($homedir[0])) {
  264. $path = $homedir[0];
  265. }
  266. }
  267. if ($path !== '') {
  268. //if attribute's value is an absolute path take this, otherwise append it to data dir
  269. //check for / at the beginning or pattern c:\ resp. c:/
  270. if ('/' !== $path[0]
  271. && !(3 < strlen($path) && ctype_alpha($path[0])
  272. && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
  273. ) {
  274. $path = $this->config->getSystemValue('datadirectory',
  275. \OC::$SERVERROOT.'/data') . '/' . $path;
  276. }
  277. //we need it to store it in the DB as well in case a user gets
  278. //deleted so we can clean up afterwards
  279. $this->config->setUserValue(
  280. $this->getUsername(), 'user_ldap', 'homePath', $path
  281. );
  282. return $path;
  283. }
  284. if (!is_null($attr)
  285. && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
  286. ) {
  287. // a naming rule attribute is defined, but it doesn't exist for that LDAP user
  288. throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
  289. }
  290. //false will apply default behaviour as defined and done by OC_User
  291. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
  292. return false;
  293. }
  294. public function getMemberOfGroups() {
  295. $cacheKey = 'getMemberOf'.$this->getUsername();
  296. $memberOfGroups = $this->connection->getFromCache($cacheKey);
  297. if (!is_null($memberOfGroups)) {
  298. return $memberOfGroups;
  299. }
  300. $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
  301. $this->connection->writeToCache($cacheKey, $groupDNs);
  302. return $groupDNs;
  303. }
  304. /**
  305. * @brief reads the image from LDAP that shall be used as Avatar
  306. * @return string data (provided by LDAP) | false
  307. */
  308. public function getAvatarImage() {
  309. if (!is_null($this->avatarImage)) {
  310. return $this->avatarImage;
  311. }
  312. $this->avatarImage = false;
  313. /** @var Connection $connection */
  314. $connection = $this->access->getConnection();
  315. $attributes = $connection->resolveRule('avatar');
  316. foreach ($attributes as $attribute) {
  317. $result = $this->access->readAttribute($this->dn, $attribute);
  318. if ($result !== false && is_array($result) && isset($result[0])) {
  319. $this->avatarImage = $result[0];
  320. break;
  321. }
  322. }
  323. return $this->avatarImage;
  324. }
  325. /**
  326. * @brief marks the user as having logged in at least once
  327. * @return null
  328. */
  329. public function markLogin() {
  330. $this->config->setUserValue(
  331. $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
  332. }
  333. /**
  334. * Stores a key-value pair in relation to this user
  335. *
  336. * @param string $key
  337. * @param string $value
  338. */
  339. private function store($key, $value) {
  340. $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
  341. }
  342. /**
  343. * Composes the display name and stores it in the database. The final
  344. * display name is returned.
  345. *
  346. * @param string $displayName
  347. * @param string $displayName2
  348. * @return string the effective display name
  349. */
  350. public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
  351. $displayName2 = (string)$displayName2;
  352. if ($displayName2 !== '') {
  353. $displayName .= ' (' . $displayName2 . ')';
  354. }
  355. $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
  356. if ($oldName !== $displayName) {
  357. $this->store('displayName', $displayName);
  358. $user = $this->userManager->get($this->getUsername());
  359. if (!empty($oldName) && $user instanceof \OC\User\User) {
  360. // if it was empty, it would be a new record, not a change emitting the trigger could
  361. // potentially cause a UniqueConstraintViolationException, depending on some factors.
  362. $user->triggerChange('displayName', $displayName, $oldName);
  363. }
  364. }
  365. return $displayName;
  366. }
  367. /**
  368. * Stores the LDAP Username in the Database
  369. * @param string $userName
  370. */
  371. public function storeLDAPUserName($userName) {
  372. $this->store('uid', $userName);
  373. }
  374. /**
  375. * @brief checks whether an update method specified by feature was run
  376. * already. If not, it will marked like this, because it is expected that
  377. * the method will be run, when false is returned.
  378. * @param string $feature email | quota | avatar (can be extended)
  379. * @return bool
  380. */
  381. private function wasRefreshed($feature) {
  382. if (isset($this->refreshedFeatures[$feature])) {
  383. return true;
  384. }
  385. $this->refreshedFeatures[$feature] = 1;
  386. return false;
  387. }
  388. /**
  389. * fetches the email from LDAP and stores it as Nextcloud user value
  390. * @param string $valueFromLDAP if known, to save an LDAP read request
  391. * @return null
  392. */
  393. public function updateEmail($valueFromLDAP = null) {
  394. if ($this->wasRefreshed('email')) {
  395. return;
  396. }
  397. $email = (string)$valueFromLDAP;
  398. if (is_null($valueFromLDAP)) {
  399. $emailAttribute = $this->connection->ldapEmailAttribute;
  400. if ($emailAttribute !== '') {
  401. $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
  402. if (is_array($aEmail) && (count($aEmail) > 0)) {
  403. $email = (string)$aEmail[0];
  404. }
  405. }
  406. }
  407. if ($email !== '') {
  408. $user = $this->userManager->get($this->uid);
  409. if (!is_null($user)) {
  410. $currentEmail = (string)$user->getSystemEMailAddress();
  411. if ($currentEmail !== $email) {
  412. $user->setEMailAddress($email);
  413. }
  414. }
  415. }
  416. }
  417. /**
  418. * Overall process goes as follow:
  419. * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
  420. * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
  421. * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
  422. * 4. check if the target user exists and set the quota for the user.
  423. *
  424. * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
  425. * parameter can be passed with the value of the attribute. This value will be considered as the
  426. * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
  427. * fetch all the user's attributes in one call and use the fetched values in this function.
  428. * The expected value for that parameter is a string describing the quota for the user. Valid
  429. * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
  430. * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
  431. *
  432. * fetches the quota from LDAP and stores it as Nextcloud user value
  433. * @param ?string $valueFromLDAP the quota attribute's value can be passed,
  434. * to save the readAttribute request
  435. * @return void
  436. */
  437. public function updateQuota($valueFromLDAP = null) {
  438. if ($this->wasRefreshed('quota')) {
  439. return;
  440. }
  441. $quotaAttribute = $this->connection->ldapQuotaAttribute;
  442. $defaultQuota = $this->connection->ldapQuotaDefault;
  443. if ($quotaAttribute === '' && $defaultQuota === '') {
  444. return;
  445. }
  446. $quota = false;
  447. if (is_null($valueFromLDAP) && $quotaAttribute !== '') {
  448. $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
  449. if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
  450. $quota = $aQuota[0];
  451. } elseif (is_array($aQuota) && isset($aQuota[0])) {
  452. $this->logger->debug('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ['app' => 'user_ldap']);
  453. }
  454. } elseif (!is_null($valueFromLDAP) && $this->verifyQuotaValue($valueFromLDAP)) {
  455. $quota = $valueFromLDAP;
  456. } else {
  457. $this->logger->debug('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ['app' => 'user_ldap']);
  458. }
  459. if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
  460. // quota not found using the LDAP attribute (or not parseable). Try the default quota
  461. $quota = $defaultQuota;
  462. } elseif ($quota === false) {
  463. $this->logger->debug('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ['app' => 'user_ldap']);
  464. return;
  465. }
  466. $targetUser = $this->userManager->get($this->uid);
  467. if ($targetUser instanceof IUser) {
  468. $targetUser->setQuota($quota);
  469. } else {
  470. $this->logger->info('trying to set a quota for user ' . $this->uid . ' but the user is missing', ['app' => 'user_ldap']);
  471. }
  472. }
  473. private function verifyQuotaValue(string $quotaValue) {
  474. return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
  475. }
  476. /**
  477. * called by a post_login hook to save the avatar picture
  478. *
  479. * @param array $params
  480. */
  481. public function updateAvatarPostLogin($params) {
  482. if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
  483. $this->updateAvatar();
  484. }
  485. }
  486. /**
  487. * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
  488. * @return bool
  489. */
  490. public function updateAvatar($force = false) {
  491. if (!$force && $this->wasRefreshed('avatar')) {
  492. return false;
  493. }
  494. $avatarImage = $this->getAvatarImage();
  495. if ($avatarImage === false) {
  496. //not set, nothing left to do;
  497. return false;
  498. }
  499. if (!$this->image->loadFromBase64(base64_encode($avatarImage))) {
  500. return false;
  501. }
  502. // use the checksum before modifications
  503. $checksum = md5($this->image->data());
  504. if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
  505. return true;
  506. }
  507. $isSet = $this->setOwnCloudAvatar();
  508. if ($isSet) {
  509. // save checksum only after successful setting
  510. $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
  511. }
  512. return $isSet;
  513. }
  514. /**
  515. * @brief sets an image as Nextcloud avatar
  516. * @return bool
  517. */
  518. private function setOwnCloudAvatar() {
  519. if (!$this->image->valid()) {
  520. $this->logger->error('avatar image data from LDAP invalid for '.$this->dn, ['app' => 'user_ldap']);
  521. return false;
  522. }
  523. //make sure it is a square and not bigger than 128x128
  524. $size = min([$this->image->width(), $this->image->height(), 128]);
  525. if (!$this->image->centerCrop($size)) {
  526. $this->logger->error('croping image for avatar failed for '.$this->dn, ['app' => 'user_ldap']);
  527. return false;
  528. }
  529. if (!$this->fs->isLoaded()) {
  530. $this->fs->setup($this->uid);
  531. }
  532. try {
  533. $avatar = $this->avatarManager->getAvatar($this->uid);
  534. $avatar->set($this->image);
  535. return true;
  536. } catch (\Exception $e) {
  537. \OC::$server->getLogger()->logException($e, [
  538. 'message' => 'Could not set avatar for ' . $this->dn,
  539. 'level' => ILogger::INFO,
  540. 'app' => 'user_ldap',
  541. ]);
  542. }
  543. return false;
  544. }
  545. /**
  546. * @throws AttributeNotSet
  547. * @throws \OC\ServerNotAvailableException
  548. * @throws \OCP\PreConditionNotMetException
  549. */
  550. public function getExtStorageHome():string {
  551. $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
  552. if ($value !== '') {
  553. return $value;
  554. }
  555. $value = $this->updateExtStorageHome();
  556. if ($value !== '') {
  557. return $value;
  558. }
  559. throw new AttributeNotSet(sprintf(
  560. 'external home storage attribute yield no value for %s', $this->getUsername()
  561. ));
  562. }
  563. /**
  564. * @throws \OCP\PreConditionNotMetException
  565. * @throws \OC\ServerNotAvailableException
  566. */
  567. public function updateExtStorageHome(string $valueFromLDAP = null):string {
  568. if ($valueFromLDAP === null) {
  569. $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
  570. } else {
  571. $extHomeValues = [$valueFromLDAP];
  572. }
  573. if ($extHomeValues && isset($extHomeValues[0])) {
  574. $extHome = $extHomeValues[0];
  575. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
  576. return $extHome;
  577. } else {
  578. $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
  579. return '';
  580. }
  581. }
  582. /**
  583. * called by a post_login hook to handle password expiry
  584. *
  585. * @param array $params
  586. */
  587. public function handlePasswordExpiry($params) {
  588. $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
  589. if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
  590. return;//password expiry handling disabled
  591. }
  592. $uid = $params['uid'];
  593. if (isset($uid) && $uid === $this->getUsername()) {
  594. //retrieve relevant user attributes
  595. $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
  596. if (array_key_exists('pwdpolicysubentry', $result[0])) {
  597. $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
  598. if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
  599. $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
  600. }
  601. }
  602. $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
  603. $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
  604. $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
  605. //retrieve relevant password policy attributes
  606. $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
  607. $result = $this->connection->getFromCache($cacheKey);
  608. if (is_null($result)) {
  609. $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
  610. $this->connection->writeToCache($cacheKey, $result);
  611. }
  612. $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
  613. $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
  614. $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
  615. //handle grace login
  616. if (!empty($pwdGraceUseTime)) { //was this a grace login?
  617. if (!empty($pwdGraceAuthNLimit)
  618. && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
  619. $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
  620. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  621. 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
  622. } else { //no more grace login available
  623. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  624. 'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
  625. }
  626. exit();
  627. }
  628. //handle pwdReset attribute
  629. if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
  630. $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
  631. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  632. 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
  633. exit();
  634. }
  635. //handle password expiry warning
  636. if (!empty($pwdChangedTime)) {
  637. if (!empty($pwdMaxAge)
  638. && !empty($pwdExpireWarning)) {
  639. $pwdMaxAgeInt = (int)$pwdMaxAge[0];
  640. $pwdExpireWarningInt = (int)$pwdExpireWarning[0];
  641. if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
  642. $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
  643. $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
  644. $currentDateTime = new \DateTime();
  645. $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
  646. if ($secondsToExpiry <= $pwdExpireWarningInt) {
  647. //remove last password expiry warning if any
  648. $notification = $this->notificationManager->createNotification();
  649. $notification->setApp('user_ldap')
  650. ->setUser($uid)
  651. ->setObject('pwd_exp_warn', $uid)
  652. ;
  653. $this->notificationManager->markProcessed($notification);
  654. //create new password expiry warning
  655. $notification = $this->notificationManager->createNotification();
  656. $notification->setApp('user_ldap')
  657. ->setUser($uid)
  658. ->setDateTime($currentDateTime)
  659. ->setObject('pwd_exp_warn', $uid)
  660. ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
  661. ;
  662. $this->notificationManager->notify($notification);
  663. }
  664. }
  665. }
  666. }
  667. }
  668. }
  669. }