userController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. /**
  163. * This action displays the user management page.
  164. */
  165. public function manageAction() {
  166. if (!FreshRSS_Auth::hasAccess('admin')) {
  167. Minz_Error::error(403);
  168. }
  169. Minz_View::prependTitle(_t('admin.user.title') . ' · ');
  170. $this->view->show_email_field = FreshRSS_Context::$system_conf->force_email_validation;
  171. $this->view->current_user = Minz_Request::param('u');
  172. $this->view->nb_articles = 0;
  173. $this->view->size_user = 0;
  174. if ($this->view->current_user) {
  175. // Get information about the current user.
  176. $entryDAO = FreshRSS_Factory::createEntryDao($this->view->current_user);
  177. $this->view->nb_articles = $entryDAO->count();
  178. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($this->view->current_user);
  179. $this->view->size_user = $databaseDAO->size();
  180. }
  181. }
  182. public static function createUser($new_user_name, $email, $passwordPlain, $apiPasswordPlain = '', $userConfigOverride = [], $insertDefaultFeeds = true) {
  183. $userConfig = [];
  184. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  185. if (file_exists($customUserConfigPath)) {
  186. $customUserConfig = include($customUserConfigPath);
  187. if (is_array($customUserConfig)) {
  188. $userConfig = $customUserConfig;
  189. }
  190. }
  191. if (is_array($userConfigOverride)) {
  192. $userConfig = array_merge($userConfig, $userConfigOverride);
  193. }
  194. $ok = self::checkUsername($new_user_name);
  195. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  196. if ($ok) {
  197. $languages = Minz_Translate::availableLanguages();
  198. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages)) {
  199. $userConfig['language'] = 'en';
  200. }
  201. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive
  202. $configPath = join_path($homeDir, 'config.php');
  203. $ok &= !file_exists($configPath);
  204. }
  205. if ($ok) {
  206. if (!is_dir($homeDir)) {
  207. mkdir($homeDir);
  208. }
  209. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  210. }
  211. if ($ok) {
  212. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  213. $ok &= $newUserDAO->createUser();
  214. if ($ok && $insertDefaultFeeds) {
  215. $opmlPath = DATA_PATH . '/opml.xml';
  216. if (!file_exists($opmlPath)) {
  217. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  218. }
  219. $importController = new FreshRSS_importExport_Controller();
  220. try {
  221. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  222. } catch (Exception $e) {
  223. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  224. }
  225. }
  226. $ok &= self::updateUser($new_user_name, $email, $passwordPlain, $apiPasswordPlain);
  227. }
  228. return $ok;
  229. }
  230. /**
  231. * This action creates a new user.
  232. *
  233. * Request parameters are:
  234. * - new_user_language
  235. * - new_user_name
  236. * - new_user_email
  237. * - new_user_passwordPlain
  238. * - r (i.e. a redirection url, optional)
  239. *
  240. * @todo clean up this method. Idea: write a method to init a user with basic information.
  241. * @todo handle r redirection in Minz_Request::forward directly?
  242. */
  243. public function createAction() {
  244. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  245. Minz_Error::error(403);
  246. }
  247. if (Minz_Request::isPost()) {
  248. $system_conf = FreshRSS_Context::$system_conf;
  249. $new_user_name = Minz_Request::param('new_user_name');
  250. $email = Minz_Request::param('new_user_email', '');
  251. $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
  252. $new_user_language = Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language);
  253. $tos_enabled = file_exists(join_path(DATA_PATH, 'tos.html'));
  254. $accept_tos = Minz_Request::param('accept_tos', false);
  255. if ($system_conf->force_email_validation && empty($email)) {
  256. Minz_Request::bad(
  257. _t('user.email.feedback.required'),
  258. array('c' => 'auth', 'a' => 'register')
  259. );
  260. }
  261. if (!empty($email) && !validateEmailAddress($email)) {
  262. Minz_Request::bad(
  263. _t('user.email.feedback.invalid'),
  264. array('c' => 'auth', 'a' => 'register')
  265. );
  266. }
  267. if ($tos_enabled && !$accept_tos) {
  268. Minz_Request::bad(
  269. _t('user.tos.feedback.invalid'),
  270. array('c' => 'auth', 'a' => 'register')
  271. );
  272. }
  273. $ok = self::createUser($new_user_name, $email, $passwordPlain, '', array('language' => $new_user_language));
  274. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  275. $_POST['new_user_passwordPlain'] = '';
  276. invalidateHttpCache();
  277. // If the user has admin access, it means he's already logged in
  278. // and we don't want to login with the new account. Otherwise, the
  279. // user just created its account himself so he probably wants to
  280. // get started immediately.
  281. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  282. $user_conf = get_user_configuration($new_user_name);
  283. Minz_Session::_param('currentUser', $new_user_name);
  284. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  285. Minz_Session::_param('csrf');
  286. FreshRSS_Auth::giveAccess();
  287. }
  288. $notif = array(
  289. 'type' => $ok ? 'good' : 'bad',
  290. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  291. );
  292. Minz_Session::_param('notification', $notif);
  293. }
  294. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  295. if (!$redirect_url) {
  296. $redirect_url = array('c' => 'user', 'a' => 'manage');
  297. }
  298. Minz_Request::forward($redirect_url, true);
  299. }
  300. public static function deleteUser($username) {
  301. $ok = self::checkUsername($username);
  302. if ($ok) {
  303. $default_user = FreshRSS_Context::$system_conf->default_user;
  304. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  305. }
  306. $user_data = join_path(DATA_PATH, 'users', $username);
  307. $ok &= is_dir($user_data);
  308. if ($ok) {
  309. self::deleteFeverKey($username);
  310. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  311. $ok &= $oldUserDAO->deleteUser();
  312. $ok &= recursive_unlink($user_data);
  313. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  314. }
  315. return $ok;
  316. }
  317. /**
  318. * This action validates an email address, based on the token sent by email.
  319. * It also serves the main page when user is blocked.
  320. *
  321. * Request parameters are:
  322. * - username
  323. * - token
  324. *
  325. * This route works with GET requests since the URL is provided by email.
  326. * The security risks (e.g. forged URL by an attacker) are not very high so
  327. * it's ok.
  328. *
  329. * It returns 404 error if `force_email_validation` is disabled or if the
  330. * user doesn't exist.
  331. *
  332. * It returns 403 if user isn't logged in and `username` param isn't passed.
  333. */
  334. public function validateEmailAction() {
  335. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  336. Minz_Error::error(404);
  337. }
  338. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  339. $this->view->_layout('simple');
  340. $username = Minz_Request::param('username');
  341. $token = Minz_Request::param('token');
  342. if ($username) {
  343. $user_config = get_user_configuration($username);
  344. } elseif (FreshRSS_Auth::hasAccess()) {
  345. $user_config = FreshRSS_Context::$user_conf;
  346. } else {
  347. Minz_Error::error(403);
  348. }
  349. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  350. Minz_Error::error(404);
  351. }
  352. if ($user_config->email_validation_token === '') {
  353. Minz_Request::good(
  354. _t('user.email.validation.feedback.unnecessary'),
  355. array('c' => 'index', 'a' => 'index')
  356. );
  357. }
  358. if ($token) {
  359. if ($user_config->email_validation_token !== $token) {
  360. Minz_Request::bad(
  361. _t('user.email.validation.feedback.wrong_token'),
  362. array('c' => 'user', 'a' => 'validateEmail')
  363. );
  364. }
  365. $user_config->email_validation_token = '';
  366. if ($user_config->save()) {
  367. Minz_Request::good(
  368. _t('user.email.validation.feedback.ok'),
  369. array('c' => 'index', 'a' => 'index')
  370. );
  371. } else {
  372. Minz_Request::bad(
  373. _t('user.email.validation.feedback.error'),
  374. array('c' => 'user', 'a' => 'validateEmail')
  375. );
  376. }
  377. }
  378. }
  379. /**
  380. * This action resends a validation email to the current user.
  381. *
  382. * It only acts on POST requests but doesn't require any param (except the
  383. * CSRF token).
  384. *
  385. * It returns 403 error if the user is not logged in or 404 if request is
  386. * not POST. Else it redirects silently to the index if user has already
  387. * validated its email, or to the user#validateEmail route.
  388. */
  389. public function sendValidationEmailAction() {
  390. if (!FreshRSS_Auth::hasAccess()) {
  391. Minz_Error::error(403);
  392. }
  393. if (!Minz_Request::isPost()) {
  394. Minz_Error::error(404);
  395. }
  396. $username = Minz_Session::param('currentUser', '_');
  397. $user_config = FreshRSS_Context::$user_conf;
  398. if ($user_config->email_validation_token === '') {
  399. Minz_Request::forward(array(
  400. 'c' => 'index',
  401. 'a' => 'index',
  402. ), true);
  403. }
  404. $mailer = new FreshRSS_User_Mailer();
  405. $ok = $mailer->send_email_need_validation($username, $user_config);
  406. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  407. if ($ok) {
  408. Minz_Request::good(
  409. _t('user.email.validation.feedback.email_sent'),
  410. $redirect_url
  411. );
  412. } else {
  413. Minz_Request::bad(
  414. _t('user.email.validation.feedback.email_failed'),
  415. $redirect_url
  416. );
  417. }
  418. }
  419. /**
  420. * This action delete an existing user.
  421. *
  422. * Request parameter is:
  423. * - username
  424. *
  425. * @todo clean up this method. Idea: create a User->clean() method.
  426. */
  427. public function deleteAction() {
  428. $username = Minz_Request::param('username');
  429. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  430. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  431. Minz_Error::error(403);
  432. }
  433. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  434. if (!$redirect_url) {
  435. $redirect_url = array('c' => 'user', 'a' => 'manage');
  436. }
  437. if (Minz_Request::isPost()) {
  438. $ok = true;
  439. if ($ok && $self_deletion) {
  440. // We check the password if it's a self-destruction
  441. $nonce = Minz_Session::param('nonce');
  442. $challenge = Minz_Request::param('challenge', '');
  443. $ok &= FreshRSS_FormAuth::checkCredentials(
  444. $username, FreshRSS_Context::$user_conf->passwordHash,
  445. $nonce, $challenge
  446. );
  447. }
  448. if ($ok) {
  449. $ok &= self::deleteUser($username);
  450. }
  451. if ($ok && $self_deletion) {
  452. FreshRSS_Auth::removeAccess();
  453. $redirect_url = array('c' => 'index', 'a' => 'index');
  454. }
  455. invalidateHttpCache();
  456. $notif = array(
  457. 'type' => $ok ? 'good' : 'bad',
  458. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  459. );
  460. Minz_Session::_param('notification', $notif);
  461. }
  462. Minz_Request::forward($redirect_url, true);
  463. }
  464. }