User.php 31 KB

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