userController.php 18 KB

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