User.php 30 KB

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