userController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. /**
  3. * Controller to handle user actions.
  4. */
  5. class FreshRSS_user_Controller extends Minz_ActionController {
  6. // Will also have to be computed client side on mobile devices,
  7. // so do not use a too high cost
  8. const BCRYPT_COST = 9;
  9. public static function hashPassword($passwordPlain) {
  10. $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST));
  11. $passwordPlain = '';
  12. $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js
  13. return $passwordHash == '' ? '' : $passwordHash;
  14. }
  15. /**
  16. * The username is also used as folder name, file name, and part of SQL table name.
  17. * '_' is a reserved internal username.
  18. */
  19. const USERNAME_PATTERN = '([0-9a-zA-Z_][0-9a-zA-Z_.@-]{1,38}|[0-9a-zA-Z])';
  20. public static function checkUsername($username) {
  21. return preg_match('/^' . self::USERNAME_PATTERN . '$/', $username) === 1;
  22. }
  23. public static function deleteFeverKey($username) {
  24. $userConfig = get_user_configuration($username);
  25. if ($userConfig !== null && ctype_xdigit($userConfig->feverKey)) {
  26. return @unlink(DATA_PATH . '/fever/.key-' . sha1(FreshRSS_Context::$system_conf->salt) . '-' . $userConfig->feverKey . '.txt');
  27. }
  28. return false;
  29. }
  30. public static function updateUser($user, $email, $passwordPlain, $apiPasswordPlain, $userConfigUpdated = array()) {
  31. $userConfig = get_user_configuration($user);
  32. if ($userConfig === null) {
  33. return false;
  34. }
  35. if ($email !== null && $userConfig->mail_login !== $email) {
  36. $userConfig->mail_login = $email;
  37. if (FreshRSS_Context::$system_conf->force_email_validation) {
  38. $salt = FreshRSS_Context::$system_conf->salt;
  39. $userConfig->email_validation_token = sha1($salt . uniqid(mt_rand(), true));
  40. $mailer = new FreshRSS_User_Mailer();
  41. $mailer->send_email_need_validation($user, $userConfig);
  42. }
  43. }
  44. if ($passwordPlain != '') {
  45. $passwordHash = self::hashPassword($passwordPlain);
  46. $userConfig->passwordHash = $passwordHash;
  47. }
  48. if ($apiPasswordPlain != '') {
  49. $apiPasswordHash = self::hashPassword($apiPasswordPlain);
  50. $userConfig->apiPasswordHash = $apiPasswordHash;
  51. $feverPath = DATA_PATH . '/fever/';
  52. if (!file_exists($feverPath)) {
  53. @mkdir($feverPath, 0770, true);
  54. }
  55. if (!is_writable($feverPath)) {
  56. Minz_Log::error("Could not save Fever API credentials. The directory does not have write access.");
  57. } else {
  58. self::deleteFeverKey($user);
  59. $userConfig->feverKey = strtolower(md5("{$user}:{$apiPasswordPlain}"));
  60. $ok = file_put_contents($feverPath . '.key-' . sha1(FreshRSS_Context::$system_conf->salt) . '-' . $userConfig->feverKey . '.txt', $user) !== false;
  61. if (!$ok) {
  62. Minz_Log::warning('Could not save Fever API credentials. Unknown error.', ADMIN_LOG);
  63. }
  64. }
  65. }
  66. if (is_array($userConfigUpdated)) {
  67. foreach ($userConfigUpdated as $configName => $configValue) {
  68. if ($configValue !== null) {
  69. $userConfig->_param($configName, $configValue);
  70. }
  71. }
  72. }
  73. $ok = $userConfig->save();
  74. return $ok;
  75. }
  76. public function updateAction() {
  77. if (!FreshRSS_Auth::hasAccess('admin')) {
  78. Minz_Error::error(403);
  79. }
  80. if (Minz_Request::isPost()) {
  81. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  82. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  83. $_POST['newPasswordPlain'] = '';
  84. $apiPasswordPlain = Minz_Request::param('apiPasswordPlain', '', true);
  85. $username = Minz_Request::param('username');
  86. $ok = self::updateUser($username, null, $passwordPlain, $apiPasswordPlain, array(
  87. 'token' => Minz_Request::param('token', null),
  88. ));
  89. if ($ok) {
  90. $isSelfUpdate = Minz_Session::param('currentUser', '_') === $username;
  91. if ($passwordPlain == '' || !$isSelfUpdate) {
  92. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  93. } else {
  94. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  95. }
  96. } else {
  97. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  98. array('c' => 'user', 'a' => 'manage'));
  99. }
  100. }
  101. }
  102. /**
  103. * This action displays the user profile page.
  104. */
  105. public function profileAction() {
  106. if (!FreshRSS_Auth::hasAccess()) {
  107. Minz_Error::error(403);
  108. }
  109. $email_not_verified = FreshRSS_Context::$user_conf->email_validation_token != '';
  110. $this->view->disable_aside = false;
  111. if ($email_not_verified) {
  112. $this->view->_layout('simple');
  113. $this->view->disable_aside = true;
  114. }
  115. Minz_View::prependTitle(_t('conf.profile.title') . ' · ');
  116. Minz_View::appendScript(Minz_Url::display('/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js')));
  117. if (Minz_Request::isPost()) {
  118. $system_conf = FreshRSS_Context::$system_conf;
  119. $user_config = FreshRSS_Context::$user_conf;
  120. $old_email = $user_config->mail_login;
  121. $email = trim(Minz_Request::param('email', ''));
  122. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  123. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  124. $_POST['newPasswordPlain'] = '';
  125. $apiPasswordPlain = Minz_Request::param('apiPasswordPlain', '', true);
  126. if ($system_conf->force_email_validation && empty($email)) {
  127. Minz_Request::bad(
  128. _t('user.email.feedback.required'),
  129. array('c' => 'user', 'a' => 'profile')
  130. );
  131. }
  132. if (!empty($email) && !validateEmailAddress($email)) {
  133. Minz_Request::bad(
  134. _t('user.email.feedback.invalid'),
  135. array('c' => 'user', 'a' => 'profile')
  136. );
  137. }
  138. $ok = self::updateUser(
  139. Minz_Session::param('currentUser'),
  140. $email,
  141. $passwordPlain,
  142. $apiPasswordPlain,
  143. array(
  144. 'token' => Minz_Request::param('token', null),
  145. )
  146. );
  147. Minz_Session::_param('passwordHash', FreshRSS_Context::$user_conf->passwordHash);
  148. if ($ok) {
  149. if ($system_conf->force_email_validation && $email !== $old_email) {
  150. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'validateEmail'));
  151. } elseif ($passwordPlain == '') {
  152. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'profile'));
  153. } else {
  154. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  155. }
  156. } else {
  157. Minz_Request::bad(_t('feedback.profile.error'),
  158. array('c' => 'user', 'a' => 'profile'));
  159. }
  160. }
  161. }
  162. public function purgeAction() {
  163. if (!FreshRSS_Auth::hasAccess('admin')) {
  164. Minz_Error::error(403);
  165. }
  166. if (Minz_Request::isPost()) {
  167. $username = Minz_Request::param('username');
  168. if (!FreshRSS_UserDAO::exists($username)) {
  169. Minz_Error::error(404);
  170. }
  171. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  172. $feedDAO->purge();
  173. }
  174. }
  175. /**
  176. * This action displays the user management page.
  177. */
  178. public function manageAction() {
  179. if (!FreshRSS_Auth::hasAccess('admin')) {
  180. Minz_Error::error(403);
  181. }
  182. Minz_View::prependTitle(_t('admin.user.title') . ' · ');
  183. if (Minz_Request::isPost()) {
  184. $action = Minz_Request::param('action');
  185. if ('delete' === $action) {
  186. $this->deleteAction();
  187. } elseif ('update' === $action) {
  188. $this->updateAction();
  189. } elseif ('purge' === $action) {
  190. $this->purgeAction();
  191. }
  192. }
  193. $this->view->show_email_field = FreshRSS_Context::$system_conf->force_email_validation;
  194. $this->view->current_user = Minz_Request::param('u');
  195. foreach (listUsers() as $user) {
  196. $this->view->users[$user] = $this->retrieveUserDetails($user);
  197. }
  198. }
  199. public static function createUser($new_user_name, $email, $passwordPlain, $apiPasswordPlain = '', $userConfigOverride = [], $insertDefaultFeeds = true) {
  200. $userConfig = [];
  201. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  202. if (file_exists($customUserConfigPath)) {
  203. $customUserConfig = include($customUserConfigPath);
  204. if (is_array($customUserConfig)) {
  205. $userConfig = $customUserConfig;
  206. }
  207. }
  208. if (is_array($userConfigOverride)) {
  209. $userConfig = array_merge($userConfig, $userConfigOverride);
  210. }
  211. $ok = self::checkUsername($new_user_name);
  212. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  213. if ($ok) {
  214. $languages = Minz_Translate::availableLanguages();
  215. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages)) {
  216. $userConfig['language'] = 'en';
  217. }
  218. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive
  219. $configPath = join_path($homeDir, 'config.php');
  220. $ok &= !file_exists($configPath);
  221. }
  222. if ($ok) {
  223. if (!is_dir($homeDir)) {
  224. mkdir($homeDir);
  225. }
  226. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  227. }
  228. if ($ok) {
  229. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  230. $ok &= $newUserDAO->createUser();
  231. if ($ok && $insertDefaultFeeds) {
  232. $opmlPath = DATA_PATH . '/opml.xml';
  233. if (!file_exists($opmlPath)) {
  234. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  235. }
  236. $importController = new FreshRSS_importExport_Controller();
  237. try {
  238. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  239. } catch (Exception $e) {
  240. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  241. }
  242. }
  243. $ok &= self::updateUser($new_user_name, $email, $passwordPlain, $apiPasswordPlain);
  244. }
  245. return $ok;
  246. }
  247. /**
  248. * This action creates a new user.
  249. *
  250. * Request parameters are:
  251. * - new_user_language
  252. * - new_user_name
  253. * - new_user_email
  254. * - new_user_passwordPlain
  255. * - r (i.e. a redirection url, optional)
  256. *
  257. * @todo clean up this method. Idea: write a method to init a user with basic information.
  258. * @todo handle r redirection in Minz_Request::forward directly?
  259. */
  260. public function createAction() {
  261. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  262. Minz_Error::error(403);
  263. }
  264. if (Minz_Request::isPost()) {
  265. $system_conf = FreshRSS_Context::$system_conf;
  266. $new_user_name = Minz_Request::param('new_user_name');
  267. $email = Minz_Request::param('new_user_email', '');
  268. $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
  269. $new_user_language = Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language);
  270. $tos_enabled = file_exists(join_path(DATA_PATH, 'tos.html'));
  271. $accept_tos = Minz_Request::param('accept_tos', false);
  272. if ($system_conf->force_email_validation && empty($email)) {
  273. Minz_Request::bad(
  274. _t('user.email.feedback.required'),
  275. array('c' => 'auth', 'a' => 'register')
  276. );
  277. }
  278. if (!empty($email) && !validateEmailAddress($email)) {
  279. Minz_Request::bad(
  280. _t('user.email.feedback.invalid'),
  281. array('c' => 'auth', 'a' => 'register')
  282. );
  283. }
  284. if ($tos_enabled && !$accept_tos) {
  285. Minz_Request::bad(
  286. _t('user.tos.feedback.invalid'),
  287. array('c' => 'auth', 'a' => 'register')
  288. );
  289. }
  290. $ok = self::createUser($new_user_name, $email, $passwordPlain, '', array('language' => $new_user_language));
  291. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  292. $_POST['new_user_passwordPlain'] = '';
  293. invalidateHttpCache();
  294. // If the user has admin access, it means he's already logged in
  295. // and we don't want to login with the new account. Otherwise, the
  296. // user just created its account himself so he probably wants to
  297. // get started immediately.
  298. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  299. $user_conf = get_user_configuration($new_user_name);
  300. Minz_Session::_param('currentUser', $new_user_name);
  301. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  302. Minz_Session::_param('csrf');
  303. FreshRSS_Auth::giveAccess();
  304. }
  305. $notif = array(
  306. 'type' => $ok ? 'good' : 'bad',
  307. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  308. );
  309. Minz_Session::_param('notification', $notif);
  310. }
  311. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  312. if (!$redirect_url) {
  313. $redirect_url = array('c' => 'user', 'a' => 'manage');
  314. }
  315. Minz_Request::forward($redirect_url, true);
  316. }
  317. public static function deleteUser($username) {
  318. $ok = self::checkUsername($username);
  319. if ($ok) {
  320. $default_user = FreshRSS_Context::$system_conf->default_user;
  321. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  322. }
  323. $user_data = join_path(DATA_PATH, 'users', $username);
  324. $ok &= is_dir($user_data);
  325. if ($ok) {
  326. self::deleteFeverKey($username);
  327. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  328. $ok &= $oldUserDAO->deleteUser();
  329. $ok &= recursive_unlink($user_data);
  330. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  331. }
  332. return $ok;
  333. }
  334. /**
  335. * This action validates an email address, based on the token sent by email.
  336. * It also serves the main page when user is blocked.
  337. *
  338. * Request parameters are:
  339. * - username
  340. * - token
  341. *
  342. * This route works with GET requests since the URL is provided by email.
  343. * The security risks (e.g. forged URL by an attacker) are not very high so
  344. * it's ok.
  345. *
  346. * It returns 404 error if `force_email_validation` is disabled or if the
  347. * user doesn't exist.
  348. *
  349. * It returns 403 if user isn't logged in and `username` param isn't passed.
  350. */
  351. public function validateEmailAction() {
  352. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  353. Minz_Error::error(404);
  354. }
  355. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  356. $this->view->_layout('simple');
  357. $username = Minz_Request::param('username');
  358. $token = Minz_Request::param('token');
  359. if ($username) {
  360. $user_config = get_user_configuration($username);
  361. } elseif (FreshRSS_Auth::hasAccess()) {
  362. $user_config = FreshRSS_Context::$user_conf;
  363. } else {
  364. Minz_Error::error(403);
  365. }
  366. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  367. Minz_Error::error(404);
  368. }
  369. if ($user_config->email_validation_token === '') {
  370. Minz_Request::good(
  371. _t('user.email.validation.feedback.unnecessary'),
  372. array('c' => 'index', 'a' => 'index')
  373. );
  374. }
  375. if ($token) {
  376. if ($user_config->email_validation_token !== $token) {
  377. Minz_Request::bad(
  378. _t('user.email.validation.feedback.wrong_token'),
  379. array('c' => 'user', 'a' => 'validateEmail')
  380. );
  381. }
  382. $user_config->email_validation_token = '';
  383. if ($user_config->save()) {
  384. Minz_Request::good(
  385. _t('user.email.validation.feedback.ok'),
  386. array('c' => 'index', 'a' => 'index')
  387. );
  388. } else {
  389. Minz_Request::bad(
  390. _t('user.email.validation.feedback.error'),
  391. array('c' => 'user', 'a' => 'validateEmail')
  392. );
  393. }
  394. }
  395. }
  396. /**
  397. * This action resends a validation email to the current user.
  398. *
  399. * It only acts on POST requests but doesn't require any param (except the
  400. * CSRF token).
  401. *
  402. * It returns 403 error if the user is not logged in or 404 if request is
  403. * not POST. Else it redirects silently to the index if user has already
  404. * validated its email, or to the user#validateEmail route.
  405. */
  406. public function sendValidationEmailAction() {
  407. if (!FreshRSS_Auth::hasAccess()) {
  408. Minz_Error::error(403);
  409. }
  410. if (!Minz_Request::isPost()) {
  411. Minz_Error::error(404);
  412. }
  413. $username = Minz_Session::param('currentUser', '_');
  414. $user_config = FreshRSS_Context::$user_conf;
  415. if ($user_config->email_validation_token === '') {
  416. Minz_Request::forward(array(
  417. 'c' => 'index',
  418. 'a' => 'index',
  419. ), true);
  420. }
  421. $mailer = new FreshRSS_User_Mailer();
  422. $ok = $mailer->send_email_need_validation($username, $user_config);
  423. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  424. if ($ok) {
  425. Minz_Request::good(
  426. _t('user.email.validation.feedback.email_sent'),
  427. $redirect_url
  428. );
  429. } else {
  430. Minz_Request::bad(
  431. _t('user.email.validation.feedback.email_failed'),
  432. $redirect_url
  433. );
  434. }
  435. }
  436. /**
  437. * This action delete an existing user.
  438. *
  439. * Request parameter is:
  440. * - username
  441. *
  442. * @todo clean up this method. Idea: create a User->clean() method.
  443. */
  444. public function deleteAction() {
  445. $username = Minz_Request::param('username');
  446. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  447. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  448. Minz_Error::error(403);
  449. }
  450. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  451. if (!$redirect_url) {
  452. $redirect_url = array('c' => 'user', 'a' => 'manage');
  453. }
  454. if (Minz_Request::isPost()) {
  455. $ok = true;
  456. if ($ok && $self_deletion) {
  457. // We check the password if it's a self-destruction
  458. $nonce = Minz_Session::param('nonce');
  459. $challenge = Minz_Request::param('challenge', '');
  460. $ok &= FreshRSS_FormAuth::checkCredentials(
  461. $username, FreshRSS_Context::$user_conf->passwordHash,
  462. $nonce, $challenge
  463. );
  464. }
  465. if ($ok) {
  466. $ok &= self::deleteUser($username);
  467. }
  468. if ($ok && $self_deletion) {
  469. FreshRSS_Auth::removeAccess();
  470. $redirect_url = array('c' => 'index', 'a' => 'index');
  471. }
  472. invalidateHttpCache();
  473. $notif = array(
  474. 'type' => $ok ? 'good' : 'bad',
  475. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  476. );
  477. Minz_Session::_param('notification', $notif);
  478. }
  479. Minz_Request::forward($redirect_url, true);
  480. }
  481. public function detailsAction() {
  482. if (!FreshRSS_Auth::hasAccess('admin')) {
  483. Minz_Error::error(403);
  484. }
  485. $username = Minz_Request::param('username');
  486. if (!FreshRSS_UserDAO::exists($username)) {
  487. Minz_Error::error(404);
  488. }
  489. $this->view->username = $username;
  490. $this->view->details = $this->retrieveUserDetails($username);
  491. }
  492. private function retrieveUserDetails($username) {
  493. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  494. $entryDAO = FreshRSS_Factory::createEntryDao($username);
  495. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  496. return array(
  497. 'feed_count' => $feedDAO->count(),
  498. 'article_count' => $entryDAO->count(),
  499. 'database_size' => $databaseDAO->size(),
  500. );
  501. }
  502. }