user_ldap.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. /**
  3. * @author Andreas Fischer <bantu@owncloud.com>
  4. * @author Arthur Schiwon <blizzz@owncloud.com>
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Dominik Schmidt <dev@dominik-schmidt.de>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <icewind@owncloud.com>
  11. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Tom Needham <tom@owncloud.com>
  14. *
  15. * @copyright Copyright (c) 2015, ownCloud, Inc.
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OCA\user_ldap;
  32. use OCA\user_ldap\lib\BackendUtility;
  33. use OCA\user_ldap\lib\Access;
  34. use OCA\user_ldap\lib\user\OfflineUser;
  35. use OCA\User_LDAP\lib\User\User;
  36. use OCP\IConfig;
  37. class USER_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface {
  38. /** @var string[] $homesToKill */
  39. protected $homesToKill = array();
  40. /** @var \OCP\IConfig */
  41. protected $ocConfig;
  42. /**
  43. * @param \OCA\user_ldap\lib\Access $access
  44. * @param \OCP\IConfig $ocConfig
  45. */
  46. public function __construct(Access $access, IConfig $ocConfig) {
  47. parent::__construct($access);
  48. $this->ocConfig = $ocConfig;
  49. }
  50. /**
  51. * checks whether the user is allowed to change his avatar in ownCloud
  52. * @param string $uid the ownCloud user name
  53. * @return boolean either the user can or cannot
  54. */
  55. public function canChangeAvatar($uid) {
  56. $user = $this->access->userManager->get($uid);
  57. if(!$user instanceof User) {
  58. return false;
  59. }
  60. if($user->getAvatarImage() === false) {
  61. return true;
  62. }
  63. return false;
  64. }
  65. /**
  66. * Check if the password is correct
  67. * @param string $uid The username
  68. * @param string $password The password
  69. * @return false|string
  70. *
  71. * Check if the password is correct without logging in the user
  72. */
  73. public function checkPassword($uid, $password) {
  74. $uid = $this->access->escapeFilterPart($uid);
  75. //find out dn of the user name
  76. $attrs = array($this->access->connection->ldapUserDisplayName, 'dn',
  77. 'uid', 'samaccountname');
  78. $filter = \OCP\Util::mb_str_replace(
  79. '%uid', $uid, $this->access->connection->ldapLoginFilter, 'UTF-8');
  80. $users = $this->access->fetchListOfUsers($filter, $attrs);
  81. if(count($users) < 1) {
  82. return false;
  83. }
  84. $dn = $users[0]['dn'];
  85. $user = $this->access->userManager->get($dn);
  86. if(!$user instanceof User) {
  87. \OCP\Util::writeLog('user_ldap',
  88. 'LDAP Login: Could not get user object for DN ' . $dn .
  89. '. Maybe the LDAP entry has no set display name attribute?',
  90. \OCP\Util::WARN);
  91. return false;
  92. }
  93. if($user->getUsername() !== false) {
  94. //are the credentials OK?
  95. if(!$this->access->areCredentialsValid($dn, $password)) {
  96. return false;
  97. }
  98. $user->markLogin();
  99. if(isset($users[0][$this->access->connection->ldapUserDisplayName])) {
  100. $dpn = $users[0][$this->access->connection->ldapUserDisplayName];
  101. $user->storeDisplayName($dpn);
  102. }
  103. if(isset($users[0]['uid'])) {
  104. $user->storeLDAPUserName($users[0]['uid']);
  105. } else if(isset($users[0]['samaccountname'])) {
  106. $user->storeLDAPUserName($users[0]['samaccountname']);
  107. }
  108. return $user->getUsername();
  109. }
  110. return false;
  111. }
  112. /**
  113. * Get a list of all users
  114. * @return string[] with all uids
  115. *
  116. * Get a list of all users.
  117. */
  118. public function getUsers($search = '', $limit = 10, $offset = 0) {
  119. $search = $this->access->escapeFilterPart($search, true);
  120. $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
  121. //check if users are cached, if so return
  122. $ldap_users = $this->access->connection->getFromCache($cachekey);
  123. if(!is_null($ldap_users)) {
  124. return $ldap_users;
  125. }
  126. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  127. // error. With a limit of 0, we get 0 results. So we pass null.
  128. if($limit <= 0) {
  129. $limit = null;
  130. }
  131. $filter = $this->access->combineFilterWithAnd(array(
  132. $this->access->connection->ldapUserFilter,
  133. $this->access->getFilterPartForUserSearch($search)
  134. ));
  135. \OCP\Util::writeLog('user_ldap',
  136. 'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
  137. \OCP\Util::DEBUG);
  138. //do the search and translate results to owncloud names
  139. $ldap_users = $this->access->fetchListOfUsers(
  140. $filter,
  141. array($this->access->connection->ldapUserDisplayName, 'dn'),
  142. $limit, $offset);
  143. $ldap_users = $this->access->ownCloudUserNames($ldap_users);
  144. \OCP\Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', \OCP\Util::DEBUG);
  145. $this->access->connection->writeToCache($cachekey, $ldap_users);
  146. return $ldap_users;
  147. }
  148. /**
  149. * checks whether a user is still available on LDAP
  150. * @param string|\OCA\User_LDAP\lib\user\User $user either the ownCloud user
  151. * name or an instance of that user
  152. * @return bool
  153. */
  154. public function userExistsOnLDAP($user) {
  155. if(is_string($user)) {
  156. $user = $this->access->userManager->get($user);
  157. }
  158. if(!$user instanceof User) {
  159. return false;
  160. }
  161. $dn = $user->getDN();
  162. //check if user really still exists by reading its entry
  163. if(!is_array($this->access->readAttribute($dn, ''))) {
  164. $lcr = $this->access->connection->getConnectionResource();
  165. if(is_null($lcr)) {
  166. throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
  167. }
  168. return false;
  169. }
  170. return true;
  171. }
  172. /**
  173. * check if a user exists
  174. * @param string $uid the username
  175. * @return boolean
  176. */
  177. public function userExists($uid) {
  178. if($this->access->connection->isCached('userExists'.$uid)) {
  179. return $this->access->connection->getFromCache('userExists'.$uid);
  180. }
  181. //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
  182. $user = $this->access->userManager->get($uid);
  183. if(is_null($user)) {
  184. \OCP\Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
  185. $this->access->connection->ldapHost, \OCP\Util::DEBUG);
  186. $this->access->connection->writeToCache('userExists'.$uid, false);
  187. return false;
  188. } else if($user instanceof OfflineUser) {
  189. //express check for users marked as deleted. Returning true is
  190. //necessary for cleanup
  191. return true;
  192. }
  193. try {
  194. $result = $this->userExistsOnLDAP($user);
  195. $this->access->connection->writeToCache('userExists'.$uid, $result);
  196. if($result === true) {
  197. $user->update();
  198. }
  199. return $result;
  200. } catch (\Exception $e) {
  201. \OCP\Util::writeLog('user_ldap', $e->getMessage(), \OCP\Util::WARN);
  202. return false;
  203. }
  204. }
  205. /**
  206. * returns whether a user was deleted in LDAP
  207. *
  208. * @param string $uid The username of the user to delete
  209. * @return bool
  210. */
  211. public function deleteUser($uid) {
  212. $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
  213. if(intval($marked) === 0) {
  214. \OC::$server->getLogger()->notice(
  215. 'User '.$uid . ' is not marked as deleted, not cleaning up.',
  216. array('app' => 'user_ldap'));
  217. return false;
  218. }
  219. \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
  220. array('app' => 'user_ldap'));
  221. //Get Home Directory out of user preferences so we can return it later,
  222. //necessary for removing directories as done by OC_User.
  223. $home = $this->ocConfig->getUserValue($uid, 'user_ldap', 'homePath', '');
  224. $this->homesToKill[$uid] = $home;
  225. $this->access->getUserMapper()->unmap($uid);
  226. return true;
  227. }
  228. /**
  229. * get the user's home directory
  230. * @param string $uid the username
  231. * @return string|bool
  232. */
  233. public function getHome($uid) {
  234. // user Exists check required as it is not done in user proxy!
  235. if(!$this->userExists($uid)) {
  236. return false;
  237. }
  238. if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
  239. //a deleted user who needs some clean up
  240. return $this->homesToKill[$uid];
  241. }
  242. $cacheKey = 'getHome'.$uid;
  243. if($this->access->connection->isCached($cacheKey)) {
  244. return $this->access->connection->getFromCache($cacheKey);
  245. }
  246. if(strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0) {
  247. $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
  248. $homedir = $this->access->readAttribute(
  249. $this->access->username2dn($uid), $attr);
  250. if($homedir && isset($homedir[0])) {
  251. $path = $homedir[0];
  252. //if attribute's value is an absolute path take this, otherwise append it to data dir
  253. //check for / at the beginning or pattern c:\ resp. c:/
  254. if(
  255. '/' === $path[0]
  256. || (3 < strlen($path) && ctype_alpha($path[0])
  257. && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
  258. ) {
  259. $homedir = $path;
  260. } else {
  261. $homedir = $this->ocConfig->getSystemValue('datadirectory',
  262. \OC::$SERVERROOT.'/data' ) . '/' . $homedir[0];
  263. }
  264. $this->access->connection->writeToCache($cacheKey, $homedir);
  265. //we need it to store it in the DB as well in case a user gets
  266. //deleted so we can clean up afterwards
  267. $this->ocConfig->setUserValue(
  268. $uid, 'user_ldap', 'homePath', $homedir
  269. );
  270. //TODO: if home directory changes, the old one needs to be removed.
  271. return $homedir;
  272. }
  273. }
  274. //false will apply default behaviour as defined and done by OC_User
  275. $this->access->connection->writeToCache($cacheKey, false);
  276. $this->ocConfig->setUserValue($uid, 'user_ldap', 'homePath', '');
  277. return false;
  278. }
  279. /**
  280. * get display name of the user
  281. * @param string $uid user ID of the user
  282. * @return string|false display name
  283. */
  284. public function getDisplayName($uid) {
  285. if(!$this->userExists($uid)) {
  286. return false;
  287. }
  288. $cacheKey = 'getDisplayName'.$uid;
  289. if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  290. return $displayName;
  291. }
  292. $displayName = $this->access->readAttribute(
  293. $this->access->username2dn($uid),
  294. $this->access->connection->ldapUserDisplayName);
  295. if($displayName && (count($displayName) > 0)) {
  296. $this->access->connection->writeToCache($cacheKey, $displayName[0]);
  297. return $displayName[0];
  298. }
  299. return null;
  300. }
  301. /**
  302. * Get a list of all display names
  303. * @return array with all displayNames (value) and the correspondig uids (key)
  304. *
  305. * Get a list of all display names and user ids.
  306. */
  307. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  308. $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
  309. if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
  310. return $displayNames;
  311. }
  312. $displayNames = array();
  313. $users = $this->getUsers($search, $limit, $offset);
  314. foreach ($users as $user) {
  315. $displayNames[$user] = $this->getDisplayName($user);
  316. }
  317. $this->access->connection->writeToCache($cacheKey, $displayNames);
  318. return $displayNames;
  319. }
  320. /**
  321. * Check if backend implements actions
  322. * @param int $actions bitwise-or'ed actions
  323. * @return boolean
  324. *
  325. * Returns the supported actions as int to be
  326. * compared with OC_USER_BACKEND_CREATE_USER etc.
  327. */
  328. public function implementsActions($actions) {
  329. return (bool)((OC_USER_BACKEND_CHECK_PASSWORD
  330. | OC_USER_BACKEND_GET_HOME
  331. | OC_USER_BACKEND_GET_DISPLAYNAME
  332. | OC_USER_BACKEND_PROVIDE_AVATAR
  333. | OC_USER_BACKEND_COUNT_USERS)
  334. & $actions);
  335. }
  336. /**
  337. * @return bool
  338. */
  339. public function hasUserListings() {
  340. return true;
  341. }
  342. /**
  343. * counts the users in LDAP
  344. *
  345. * @return int|bool
  346. */
  347. public function countUsers() {
  348. $filter = $this->access->getFilterForUserCount();
  349. $cacheKey = 'countUsers-'.$filter;
  350. if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
  351. return $entries;
  352. }
  353. $entries = $this->access->countUsers($filter);
  354. $this->access->connection->writeToCache($cacheKey, $entries);
  355. return $entries;
  356. }
  357. /**
  358. * Backend name to be shown in user management
  359. * @return string the name of the backend to be shown
  360. */
  361. public function getBackendName(){
  362. return 'LDAP';
  363. }
  364. }