User.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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 Marc Hefter <marchefter@march42.net>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Philipp Staiger <philipp@staiger.it>
  13. * @author Roger Szabo <roger.szabo@web.de>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  16. * @author Vincent Petry <vincent@nextcloud.com>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\User_LDAP\User;
  34. use Exception;
  35. use OC\Accounts\AccountManager;
  36. use OCA\User_LDAP\Access;
  37. use OCA\User_LDAP\Connection;
  38. use OCA\User_LDAP\Exceptions\AttributeNotSet;
  39. use OCA\User_LDAP\FilesystemHelper;
  40. use OCP\IAvatarManager;
  41. use OCP\IConfig;
  42. use OCP\ILogger;
  43. use OCP\Image;
  44. use OCP\IUser;
  45. use OCP\IUserManager;
  46. use OCP\Accounts\IAccountManager;
  47. use OCP\Accounts\PropertyDoesNotExistException;
  48. use OCP\Notification\IManager as INotificationManager;
  49. use OCP\Server;
  50. use Psr\Log\LoggerInterface;
  51. /**
  52. * User
  53. *
  54. * represents an LDAP user, gets and holds user-specific information from LDAP
  55. */
  56. class User {
  57. /**
  58. * @var Access
  59. */
  60. protected $access;
  61. /**
  62. * @var Connection
  63. */
  64. protected $connection;
  65. /**
  66. * @var IConfig
  67. */
  68. protected $config;
  69. /**
  70. * @var FilesystemHelper
  71. */
  72. protected $fs;
  73. /**
  74. * @var Image
  75. */
  76. protected $image;
  77. /**
  78. * @var LoggerInterface
  79. */
  80. protected $logger;
  81. /**
  82. * @var IAvatarManager
  83. */
  84. protected $avatarManager;
  85. /**
  86. * @var IUserManager
  87. */
  88. protected $userManager;
  89. /**
  90. * @var INotificationManager
  91. */
  92. protected $notificationManager;
  93. /**
  94. * @var string
  95. */
  96. protected $dn;
  97. /**
  98. * @var string
  99. */
  100. protected $uid;
  101. /**
  102. * @var string[]
  103. */
  104. protected $refreshedFeatures = [];
  105. /**
  106. * @var string
  107. */
  108. protected $avatarImage;
  109. /**
  110. * DB config keys for user preferences
  111. */
  112. public const USER_PREFKEY_FIRSTLOGIN = 'firstLoginAccomplished';
  113. /**
  114. * @brief constructor, make sure the subclasses call this one!
  115. * @param string $username the internal username
  116. * @param string $dn the LDAP DN
  117. */
  118. public function __construct($username, $dn, Access $access,
  119. IConfig $config, FilesystemHelper $fs, Image $image,
  120. LoggerInterface $logger, IAvatarManager $avatarManager, IUserManager $userManager,
  121. INotificationManager $notificationManager) {
  122. if ($username === null) {
  123. $logger->error("uid for '$dn' must not be null!", ['app' => 'user_ldap']);
  124. throw new \InvalidArgumentException('uid must not be null!');
  125. } elseif ($username === '') {
  126. $logger->error("uid for '$dn' must not be an empty string", ['app' => 'user_ldap']);
  127. throw new \InvalidArgumentException('uid must not be an empty string!');
  128. }
  129. $this->access = $access;
  130. $this->connection = $access->getConnection();
  131. $this->config = $config;
  132. $this->fs = $fs;
  133. $this->dn = $dn;
  134. $this->uid = $username;
  135. $this->image = $image;
  136. $this->logger = $logger;
  137. $this->avatarManager = $avatarManager;
  138. $this->userManager = $userManager;
  139. $this->notificationManager = $notificationManager;
  140. \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
  141. }
  142. /**
  143. * marks a user as deleted
  144. *
  145. * @throws \OCP\PreConditionNotMetException
  146. */
  147. public function markUser() {
  148. $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
  149. if ($curValue === '1') {
  150. // the user is already marked, do not write to DB again
  151. return;
  152. }
  153. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
  154. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
  155. }
  156. /**
  157. * processes results from LDAP for attributes as returned by getAttributesToRead()
  158. * @param array $ldapEntry the user entry as retrieved from LDAP
  159. */
  160. public function processAttributes($ldapEntry) {
  161. //Quota
  162. $attr = strtolower($this->connection->ldapQuotaAttribute);
  163. if (isset($ldapEntry[$attr])) {
  164. $this->updateQuota($ldapEntry[$attr][0]);
  165. } else {
  166. if ($this->connection->ldapQuotaDefault !== '') {
  167. $this->updateQuota();
  168. }
  169. }
  170. unset($attr);
  171. //displayName
  172. $displayName = $displayName2 = '';
  173. $attr = strtolower($this->connection->ldapUserDisplayName);
  174. if (isset($ldapEntry[$attr])) {
  175. $displayName = (string)$ldapEntry[$attr][0];
  176. }
  177. $attr = strtolower($this->connection->ldapUserDisplayName2);
  178. if (isset($ldapEntry[$attr])) {
  179. $displayName2 = (string)$ldapEntry[$attr][0];
  180. }
  181. if ($displayName !== '') {
  182. $this->composeAndStoreDisplayName($displayName, $displayName2);
  183. $this->access->cacheUserDisplayName(
  184. $this->getUsername(),
  185. $displayName,
  186. $displayName2
  187. );
  188. }
  189. unset($attr);
  190. //Email
  191. //email must be stored after displayname, because it would cause a user
  192. //change event that will trigger fetching the display name again
  193. $attr = strtolower($this->connection->ldapEmailAttribute);
  194. if (isset($ldapEntry[$attr])) {
  195. $this->updateEmail($ldapEntry[$attr][0]);
  196. }
  197. unset($attr);
  198. // LDAP Username, needed for s2s sharing
  199. if (isset($ldapEntry['uid'])) {
  200. $this->storeLDAPUserName($ldapEntry['uid'][0]);
  201. } elseif (isset($ldapEntry['samaccountname'])) {
  202. $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
  203. }
  204. //homePath
  205. if (str_starts_with($this->connection->homeFolderNamingRule, 'attr:')) {
  206. $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
  207. if (isset($ldapEntry[$attr])) {
  208. $this->access->cacheUserHome(
  209. $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
  210. }
  211. }
  212. //memberOf groups
  213. $cacheKey = 'getMemberOf'.$this->getUsername();
  214. $groups = false;
  215. if (isset($ldapEntry['memberof'])) {
  216. $groups = $ldapEntry['memberof'];
  217. }
  218. $this->connection->writeToCache($cacheKey, $groups);
  219. //external storage var
  220. $attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
  221. if (isset($ldapEntry[$attr])) {
  222. $this->updateExtStorageHome($ldapEntry[$attr][0]);
  223. }
  224. unset($attr);
  225. // check for cached profile data
  226. $username = $this->getUsername(); // buffer variable, to save resource
  227. $cacheKey = 'getUserProfile-'.$username;
  228. $profileCached = $this->connection->getFromCache($cacheKey);
  229. // honoring profile disabled in config.php and check if user profile was refreshed
  230. if ($this->config->getSystemValueBool('profile.enabled', true) &&
  231. ($profileCached === null) && // no cache or TTL not expired
  232. !$this->wasRefreshed('profile')) {
  233. // check current data
  234. $profileValues = array();
  235. //User Profile Field - Phone number
  236. $attr = strtolower($this->connection->ldapAttributePhone);
  237. if (!empty($attr)) { // attribute configured
  238. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_PHONE]
  239. = $ldapEntry[$attr][0] ?? "";
  240. }
  241. //User Profile Field - website
  242. $attr = strtolower($this->connection->ldapAttributeWebsite);
  243. if (isset($ldapEntry[$attr])) {
  244. $cutPosition = strpos($ldapEntry[$attr][0]," ");
  245. if ($cutPosition) {
  246. // drop appended label
  247. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_WEBSITE]
  248. = substr($ldapEntry[$attr][0],0,$cutPosition);
  249. } else {
  250. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_WEBSITE]
  251. = $ldapEntry[$attr][0];
  252. }
  253. } elseif (!empty($attr)) { // configured, but not defined
  254. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_WEBSITE] = "";
  255. }
  256. //User Profile Field - Address
  257. $attr = strtolower($this->connection->ldapAttributeAddress);
  258. if (isset($ldapEntry[$attr])) {
  259. if (str_contains($ldapEntry[$attr][0],'$')) {
  260. // basic format conversion from postalAddress syntax to commata delimited
  261. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_ADDRESS]
  262. = str_replace('$', ", ", $ldapEntry[$attr][0]);
  263. } else {
  264. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_ADDRESS]
  265. = $ldapEntry[$attr][0];
  266. }
  267. } elseif (!empty($attr)) { // configured, but not defined
  268. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_ADDRESS] = "";
  269. }
  270. //User Profile Field - Twitter
  271. $attr = strtolower($this->connection->ldapAttributeTwitter);
  272. if (!empty($attr)) {
  273. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_TWITTER]
  274. = $ldapEntry[$attr][0] ?? "";
  275. }
  276. //User Profile Field - fediverse
  277. $attr = strtolower($this->connection->ldapAttributeFediverse);
  278. if (!empty($attr)) {
  279. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_FEDIVERSE]
  280. = $ldapEntry[$attr][0] ?? "";
  281. }
  282. //User Profile Field - organisation
  283. $attr = strtolower($this->connection->ldapAttributeOrganisation);
  284. if (!empty($attr)) {
  285. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_ORGANISATION]
  286. = $ldapEntry[$attr][0] ?? "";
  287. }
  288. //User Profile Field - role
  289. $attr = strtolower($this->connection->ldapAttributeRole);
  290. if (!empty($attr)) {
  291. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_ROLE]
  292. = $ldapEntry[$attr][0] ?? "";
  293. }
  294. //User Profile Field - headline
  295. $attr = strtolower($this->connection->ldapAttributeHeadline);
  296. if (!empty($attr)) {
  297. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_HEADLINE]
  298. = $ldapEntry[$attr][0] ?? "";
  299. }
  300. //User Profile Field - biography
  301. $attr = strtolower($this->connection->ldapAttributeBiography);
  302. if (isset($ldapEntry[$attr])) {
  303. if (str_contains($ldapEntry[$attr][0],'\r')) {
  304. // convert line endings
  305. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_BIOGRAPHY]
  306. = str_replace(array("\r\n","\r"), "\n", $ldapEntry[$attr][0]);
  307. } else {
  308. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_BIOGRAPHY]
  309. = $ldapEntry[$attr][0];
  310. }
  311. } elseif (!empty($attr)) { // configured, but not defined
  312. $profileValues[\OCP\Accounts\IAccountManager::PROPERTY_BIOGRAPHY] = "";
  313. }
  314. // check for changed data and cache just for TTL checking
  315. $checksum = hash('sha256', json_encode($profileValues));
  316. $this->connection->writeToCache($cacheKey
  317. , $checksum // write array to cache. is waste of cache space
  318. , null); // use ldapCacheTTL from configuration
  319. // Update user profile
  320. if ($this->config->getUserValue($username, 'user_ldap', 'lastProfileChecksum', null) !== $checksum) {
  321. $this->config->setUserValue($username, 'user_ldap', 'lastProfileChecksum', $checksum);
  322. $this->updateProfile($profileValues);
  323. $this->logger->info("updated profile uid=$username"
  324. , ['app' => 'user_ldap']);
  325. } else {
  326. $this->logger->debug("profile data from LDAP unchanged"
  327. , ['app' => 'user_ldap', 'uid' => $username]);
  328. }
  329. unset($attr);
  330. } elseif ($profileCached !== null) { // message delayed, to declutter log
  331. $this->logger->debug("skipping profile check, while cached data exist"
  332. , ['app' => 'user_ldap', 'uid' => $username]);
  333. }
  334. //Avatar
  335. /** @var Connection $connection */
  336. $connection = $this->access->getConnection();
  337. $attributes = $connection->resolveRule('avatar');
  338. foreach ($attributes as $attribute) {
  339. if (isset($ldapEntry[$attribute])) {
  340. $this->avatarImage = $ldapEntry[$attribute][0];
  341. // the call to the method that saves the avatar in the file
  342. // system must be postponed after the login. It is to ensure
  343. // external mounts are mounted properly (e.g. with login
  344. // credentials from the session).
  345. \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
  346. break;
  347. }
  348. }
  349. }
  350. /**
  351. * @brief returns the LDAP DN of the user
  352. * @return string
  353. */
  354. public function getDN() {
  355. return $this->dn;
  356. }
  357. /**
  358. * @brief returns the Nextcloud internal username of the user
  359. * @return string
  360. */
  361. public function getUsername() {
  362. return $this->uid;
  363. }
  364. /**
  365. * returns the home directory of the user if specified by LDAP settings
  366. * @param ?string $valueFromLDAP
  367. * @return false|string
  368. * @throws \Exception
  369. */
  370. public function getHomePath($valueFromLDAP = null) {
  371. $path = (string)$valueFromLDAP;
  372. $attr = null;
  373. if (is_null($valueFromLDAP)
  374. && str_starts_with($this->access->connection->homeFolderNamingRule, 'attr:')
  375. && $this->access->connection->homeFolderNamingRule !== 'attr:') {
  376. $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
  377. $homedir = $this->access->readAttribute($this->access->username2dn($this->getUsername()), $attr);
  378. if ($homedir && isset($homedir[0])) {
  379. $path = $homedir[0];
  380. }
  381. }
  382. if ($path !== '') {
  383. //if attribute's value is an absolute path take this, otherwise append it to data dir
  384. //check for / at the beginning or pattern c:\ resp. c:/
  385. if ('/' !== $path[0]
  386. && !(3 < strlen($path) && ctype_alpha($path[0])
  387. && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
  388. ) {
  389. $path = $this->config->getSystemValue('datadirectory',
  390. \OC::$SERVERROOT.'/data') . '/' . $path;
  391. }
  392. //we need it to store it in the DB as well in case a user gets
  393. //deleted so we can clean up afterwards
  394. $this->config->setUserValue(
  395. $this->getUsername(), 'user_ldap', 'homePath', $path
  396. );
  397. return $path;
  398. }
  399. if (!is_null($attr)
  400. && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', 'true')
  401. ) {
  402. // a naming rule attribute is defined, but it doesn't exist for that LDAP user
  403. throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
  404. }
  405. //false will apply default behaviour as defined and done by OC_User
  406. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
  407. return false;
  408. }
  409. public function getMemberOfGroups() {
  410. $cacheKey = 'getMemberOf'.$this->getUsername();
  411. $memberOfGroups = $this->connection->getFromCache($cacheKey);
  412. if (!is_null($memberOfGroups)) {
  413. return $memberOfGroups;
  414. }
  415. $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
  416. $this->connection->writeToCache($cacheKey, $groupDNs);
  417. return $groupDNs;
  418. }
  419. /**
  420. * @brief reads the image from LDAP that shall be used as Avatar
  421. * @return string data (provided by LDAP) | false
  422. */
  423. public function getAvatarImage() {
  424. if (!is_null($this->avatarImage)) {
  425. return $this->avatarImage;
  426. }
  427. $this->avatarImage = false;
  428. /** @var Connection $connection */
  429. $connection = $this->access->getConnection();
  430. $attributes = $connection->resolveRule('avatar');
  431. foreach ($attributes as $attribute) {
  432. $result = $this->access->readAttribute($this->dn, $attribute);
  433. if ($result !== false && is_array($result) && isset($result[0])) {
  434. $this->avatarImage = $result[0];
  435. break;
  436. }
  437. }
  438. return $this->avatarImage;
  439. }
  440. /**
  441. * @brief marks the user as having logged in at least once
  442. * @return null
  443. */
  444. public function markLogin() {
  445. $this->config->setUserValue(
  446. $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, '1');
  447. }
  448. /**
  449. * Stores a key-value pair in relation to this user
  450. *
  451. * @param string $key
  452. * @param string $value
  453. */
  454. private function store($key, $value) {
  455. $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
  456. }
  457. /**
  458. * Composes the display name and stores it in the database. The final
  459. * display name is returned.
  460. *
  461. * @param string $displayName
  462. * @param string $displayName2
  463. * @return string the effective display name
  464. */
  465. public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
  466. $displayName2 = (string)$displayName2;
  467. if ($displayName2 !== '') {
  468. $displayName .= ' (' . $displayName2 . ')';
  469. }
  470. $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
  471. if ($oldName !== $displayName) {
  472. $this->store('displayName', $displayName);
  473. $user = $this->userManager->get($this->getUsername());
  474. if (!empty($oldName) && $user instanceof \OC\User\User) {
  475. // if it was empty, it would be a new record, not a change emitting the trigger could
  476. // potentially cause a UniqueConstraintViolationException, depending on some factors.
  477. $user->triggerChange('displayName', $displayName, $oldName);
  478. }
  479. }
  480. return $displayName;
  481. }
  482. /**
  483. * Stores the LDAP Username in the Database
  484. * @param string $userName
  485. */
  486. public function storeLDAPUserName($userName) {
  487. $this->store('uid', $userName);
  488. }
  489. /**
  490. * @brief checks whether an update method specified by feature was run
  491. * already. If not, it will marked like this, because it is expected that
  492. * the method will be run, when false is returned.
  493. * @param string $feature email | quota | avatar | profile (can be extended)
  494. * @return bool
  495. */
  496. private function wasRefreshed($feature) {
  497. if (isset($this->refreshedFeatures[$feature])) {
  498. return true;
  499. }
  500. $this->refreshedFeatures[$feature] = 1;
  501. return false;
  502. }
  503. /**
  504. * fetches the email from LDAP and stores it as Nextcloud user value
  505. * @param string $valueFromLDAP if known, to save an LDAP read request
  506. * @return null
  507. */
  508. public function updateEmail($valueFromLDAP = null) {
  509. if ($this->wasRefreshed('email')) {
  510. return;
  511. }
  512. $email = (string)$valueFromLDAP;
  513. if (is_null($valueFromLDAP)) {
  514. $emailAttribute = $this->connection->ldapEmailAttribute;
  515. if ($emailAttribute !== '') {
  516. $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
  517. if (is_array($aEmail) && (count($aEmail) > 0)) {
  518. $email = (string)$aEmail[0];
  519. }
  520. }
  521. }
  522. if ($email !== '') {
  523. $user = $this->userManager->get($this->uid);
  524. if (!is_null($user)) {
  525. $currentEmail = (string)$user->getSystemEMailAddress();
  526. if ($currentEmail !== $email) {
  527. $user->setEMailAddress($email);
  528. }
  529. }
  530. }
  531. }
  532. /**
  533. * Overall process goes as follow:
  534. * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
  535. * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
  536. * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
  537. * 4. check if the target user exists and set the quota for the user.
  538. *
  539. * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
  540. * parameter can be passed with the value of the attribute. This value will be considered as the
  541. * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
  542. * fetch all the user's attributes in one call and use the fetched values in this function.
  543. * The expected value for that parameter is a string describing the quota for the user. Valid
  544. * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
  545. * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
  546. *
  547. * fetches the quota from LDAP and stores it as Nextcloud user value
  548. * @param ?string $valueFromLDAP the quota attribute's value can be passed,
  549. * to save the readAttribute request
  550. * @return void
  551. */
  552. public function updateQuota($valueFromLDAP = null) {
  553. if ($this->wasRefreshed('quota')) {
  554. return;
  555. }
  556. $quotaAttribute = $this->connection->ldapQuotaAttribute;
  557. $defaultQuota = $this->connection->ldapQuotaDefault;
  558. if ($quotaAttribute === '' && $defaultQuota === '') {
  559. return;
  560. }
  561. $quota = false;
  562. if (is_null($valueFromLDAP) && $quotaAttribute !== '') {
  563. $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
  564. if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
  565. $quota = $aQuota[0];
  566. } elseif (is_array($aQuota) && isset($aQuota[0])) {
  567. $this->logger->debug('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ['app' => 'user_ldap']);
  568. }
  569. } elseif (!is_null($valueFromLDAP) && $this->verifyQuotaValue($valueFromLDAP)) {
  570. $quota = $valueFromLDAP;
  571. } else {
  572. $this->logger->debug('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ['app' => 'user_ldap']);
  573. }
  574. if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
  575. // quota not found using the LDAP attribute (or not parseable). Try the default quota
  576. $quota = $defaultQuota;
  577. } elseif ($quota === false) {
  578. $this->logger->debug('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ['app' => 'user_ldap']);
  579. return;
  580. }
  581. $targetUser = $this->userManager->get($this->uid);
  582. if ($targetUser instanceof IUser) {
  583. $targetUser->setQuota($quota);
  584. } else {
  585. $this->logger->info('trying to set a quota for user ' . $this->uid . ' but the user is missing', ['app' => 'user_ldap']);
  586. }
  587. }
  588. private function verifyQuotaValue(string $quotaValue) {
  589. return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
  590. }
  591. /**
  592. * takes values from LDAP and stores it as Nextcloud user profile value
  593. *
  594. * @param array $profileValues associative array of property keys and values from LDAP
  595. */
  596. private function updateProfile(array $profileValues): void {
  597. // check if given array is empty
  598. if (empty($profileValues)) {
  599. return; // okay, nothing to do
  600. }
  601. // fetch/prepare user
  602. $user = $this->userManager->get($this->uid);
  603. if (is_null($user)) {
  604. $this->logger->error('could not get user for uid='.$this->uid.'', ['app' => 'user_ldap']);
  605. return;
  606. }
  607. // prepare AccountManager and Account
  608. $accountManager = Server::get(IAccountManager::class);
  609. $account = $accountManager->getAccount($user); // get Account
  610. $defaultScopes = array_merge(AccountManager::DEFAULT_SCOPES,
  611. $this->config->getSystemValue('account_manager.default_property_scope', []));
  612. // loop through the properties and handle them
  613. foreach($profileValues as $property => $valueFromLDAP) {
  614. // check and update profile properties
  615. $value = (is_array($valueFromLDAP) ? $valueFromLDAP[0] : $valueFromLDAP); // take ONLY the first value, if multiple values specified
  616. try {
  617. $accountProperty = $account->getProperty($property);
  618. $currentValue = $accountProperty->getValue();
  619. $scope = ($accountProperty->getScope() ? $accountProperty->getScope()
  620. : $defaultScopes[$property]);
  621. }
  622. catch (PropertyDoesNotExistException $e) { // thrown at getProperty
  623. $this->logger->error('property does not exist: '.$property
  624. .' for uid='.$this->uid.''
  625. , ['app' => 'user_ldap', 'exception' => $e]);
  626. $currentValue = '';
  627. $scope = $defaultScopes[$property];
  628. }
  629. $verified = IAccountManager::VERIFIED; // trust the LDAP admin knew what he put there
  630. if ($currentValue !== $value) {
  631. $account->setProperty($property,$value,$scope,$verified);
  632. $this->logger->debug('update user profile: '.$property.'='.$value
  633. .' for uid='.$this->uid.'', ['app' => 'user_ldap']);
  634. }
  635. }
  636. try {
  637. $accountManager->updateAccount($account); // may throw InvalidArgumentException
  638. } catch (\InvalidArgumentException $e) {
  639. $this->logger->error('invalid data from LDAP: for uid='.$this->uid.''
  640. , ['app' => 'user_ldap', 'func' => 'updateProfile'
  641. , 'exception' => $e]);
  642. }
  643. }
  644. /**
  645. * called by a post_login hook to save the avatar picture
  646. *
  647. * @param array $params
  648. */
  649. public function updateAvatarPostLogin($params) {
  650. if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
  651. $this->updateAvatar();
  652. }
  653. }
  654. /**
  655. * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
  656. * @return bool
  657. */
  658. public function updateAvatar($force = false) {
  659. if (!$force && $this->wasRefreshed('avatar')) {
  660. return false;
  661. }
  662. $avatarImage = $this->getAvatarImage();
  663. if ($avatarImage === false) {
  664. //not set, nothing left to do;
  665. return false;
  666. }
  667. if (!$this->image->loadFromBase64(base64_encode($avatarImage))) {
  668. return false;
  669. }
  670. // use the checksum before modifications
  671. $checksum = md5($this->image->data());
  672. if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
  673. return true;
  674. }
  675. $isSet = $this->setOwnCloudAvatar();
  676. if ($isSet) {
  677. // save checksum only after successful setting
  678. $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
  679. }
  680. return $isSet;
  681. }
  682. /**
  683. * @brief sets an image as Nextcloud avatar
  684. * @return bool
  685. */
  686. private function setOwnCloudAvatar() {
  687. if (!$this->image->valid()) {
  688. $this->logger->error('avatar image data from LDAP invalid for '.$this->dn, ['app' => 'user_ldap']);
  689. return false;
  690. }
  691. //make sure it is a square and not bigger than 128x128
  692. $size = min([$this->image->width(), $this->image->height(), 128]);
  693. if (!$this->image->centerCrop($size)) {
  694. $this->logger->error('croping image for avatar failed for '.$this->dn, ['app' => 'user_ldap']);
  695. return false;
  696. }
  697. if (!$this->fs->isLoaded()) {
  698. $this->fs->setup($this->uid);
  699. }
  700. try {
  701. $avatar = $this->avatarManager->getAvatar($this->uid);
  702. $avatar->set($this->image);
  703. return true;
  704. } catch (\Exception $e) {
  705. \OC::$server->getLogger()->logException($e, [
  706. 'message' => 'Could not set avatar for ' . $this->dn,
  707. 'level' => ILogger::INFO,
  708. 'app' => 'user_ldap',
  709. ]);
  710. }
  711. return false;
  712. }
  713. /**
  714. * @throws AttributeNotSet
  715. * @throws \OC\ServerNotAvailableException
  716. * @throws \OCP\PreConditionNotMetException
  717. */
  718. public function getExtStorageHome():string {
  719. $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
  720. if ($value !== '') {
  721. return $value;
  722. }
  723. $value = $this->updateExtStorageHome();
  724. if ($value !== '') {
  725. return $value;
  726. }
  727. throw new AttributeNotSet(sprintf(
  728. 'external home storage attribute yield no value for %s', $this->getUsername()
  729. ));
  730. }
  731. /**
  732. * @throws \OCP\PreConditionNotMetException
  733. * @throws \OC\ServerNotAvailableException
  734. */
  735. public function updateExtStorageHome(string $valueFromLDAP = null):string {
  736. if ($valueFromLDAP === null) {
  737. $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
  738. } else {
  739. $extHomeValues = [$valueFromLDAP];
  740. }
  741. if ($extHomeValues && isset($extHomeValues[0])) {
  742. $extHome = $extHomeValues[0];
  743. $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
  744. return $extHome;
  745. } else {
  746. $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
  747. return '';
  748. }
  749. }
  750. /**
  751. * called by a post_login hook to handle password expiry
  752. *
  753. * @param array $params
  754. */
  755. public function handlePasswordExpiry($params) {
  756. $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
  757. if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
  758. return;//password expiry handling disabled
  759. }
  760. $uid = $params['uid'];
  761. if (isset($uid) && $uid === $this->getUsername()) {
  762. //retrieve relevant user attributes
  763. $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
  764. if (array_key_exists('pwdpolicysubentry', $result[0])) {
  765. $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
  766. if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
  767. $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
  768. }
  769. }
  770. $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
  771. $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
  772. $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
  773. //retrieve relevant password policy attributes
  774. $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
  775. $result = $this->connection->getFromCache($cacheKey);
  776. if (is_null($result)) {
  777. $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
  778. $this->connection->writeToCache($cacheKey, $result);
  779. }
  780. $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
  781. $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
  782. $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
  783. //handle grace login
  784. if (!empty($pwdGraceUseTime)) { //was this a grace login?
  785. if (!empty($pwdGraceAuthNLimit)
  786. && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
  787. $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
  788. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  789. 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
  790. } else { //no more grace login available
  791. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  792. 'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
  793. }
  794. exit();
  795. }
  796. //handle pwdReset attribute
  797. if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
  798. $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
  799. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
  800. 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
  801. exit();
  802. }
  803. //handle password expiry warning
  804. if (!empty($pwdChangedTime)) {
  805. if (!empty($pwdMaxAge)
  806. && !empty($pwdExpireWarning)) {
  807. $pwdMaxAgeInt = (int)$pwdMaxAge[0];
  808. $pwdExpireWarningInt = (int)$pwdExpireWarning[0];
  809. if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
  810. $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
  811. $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
  812. $currentDateTime = new \DateTime();
  813. $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
  814. if ($secondsToExpiry <= $pwdExpireWarningInt) {
  815. //remove last password expiry warning if any
  816. $notification = $this->notificationManager->createNotification();
  817. $notification->setApp('user_ldap')
  818. ->setUser($uid)
  819. ->setObject('pwd_exp_warn', $uid)
  820. ;
  821. $this->notificationManager->markProcessed($notification);
  822. //create new password expiry warning
  823. $notification = $this->notificationManager->createNotification();
  824. $notification->setApp('user_ldap')
  825. ->setUser($uid)
  826. ->setDateTime($currentDateTime)
  827. ->setObject('pwd_exp_warn', $uid)
  828. ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
  829. ;
  830. $this->notificationManager->notify($notification);
  831. }
  832. }
  833. }
  834. }
  835. }
  836. }
  837. }