userController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. @mkdir(DATA_PATH . '/fever/', 0770, true);
  52. self::deleteFeverKey($user);
  53. $userConfig->feverKey = strtolower(md5($user . ':' . $apiPasswordPlain));
  54. $ok = file_put_contents(DATA_PATH . '/fever/.key-' . sha1(FreshRSS_Context::$system_conf->salt) . '-' . $userConfig->feverKey . '.txt', $user) !== false;
  55. if (!$ok) {
  56. Minz_Log::warning('Could not save API credentials for fever API', ADMIN_LOG);
  57. return $ok;
  58. }
  59. }
  60. if (is_array($userConfigUpdated)) {
  61. foreach ($userConfigUpdated as $configName => $configValue) {
  62. if ($configValue !== null) {
  63. $userConfig->_param($configName, $configValue);
  64. }
  65. }
  66. }
  67. $ok = $userConfig->save();
  68. return $ok;
  69. }
  70. public function updateAction() {
  71. if (!FreshRSS_Auth::hasAccess('admin')) {
  72. Minz_Error::error(403);
  73. }
  74. if (Minz_Request::isPost()) {
  75. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  76. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  77. $_POST['newPasswordPlain'] = '';
  78. $apiPasswordPlain = Minz_Request::param('apiPasswordPlain', '', true);
  79. $username = Minz_Request::param('username');
  80. $ok = self::updateUser($username, null, $passwordPlain, $apiPasswordPlain, array(
  81. 'token' => Minz_Request::param('token', null),
  82. ));
  83. if ($ok) {
  84. $isSelfUpdate = Minz_Session::param('currentUser', '_') === $username;
  85. if ($passwordPlain == '' || !$isSelfUpdate) {
  86. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  87. } else {
  88. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  89. }
  90. } else {
  91. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  92. array('c' => 'user', 'a' => 'manage'));
  93. }
  94. }
  95. }
  96. /**
  97. * This action displays the user profile page.
  98. */
  99. public function profileAction() {
  100. if (!FreshRSS_Auth::hasAccess()) {
  101. Minz_Error::error(403);
  102. }
  103. $email_not_verified = FreshRSS_Context::$user_conf->email_validation_token !== '';
  104. $this->view->disable_aside = false;
  105. if ($email_not_verified) {
  106. $this->view->_layout('simple');
  107. $this->view->disable_aside = true;
  108. }
  109. Minz_View::prependTitle(_t('conf.profile.title') . ' · ');
  110. Minz_View::appendScript(Minz_Url::display('/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js')));
  111. if (Minz_Request::isPost()) {
  112. $system_conf = FreshRSS_Context::$system_conf;
  113. $user_config = FreshRSS_Context::$user_conf;
  114. $old_email = $user_config->mail_login;
  115. $email = trim(Minz_Request::param('email', ''));
  116. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  117. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  118. $_POST['newPasswordPlain'] = '';
  119. $apiPasswordPlain = Minz_Request::param('apiPasswordPlain', '', true);
  120. if ($system_conf->force_email_validation && empty($email)) {
  121. Minz_Request::bad(
  122. _t('user.email.feedback.required'),
  123. array('c' => 'user', 'a' => 'profile')
  124. );
  125. }
  126. if (!empty($email) && !validateEmailAddress($email)) {
  127. Minz_Request::bad(
  128. _t('user.email.feedback.invalid'),
  129. array('c' => 'user', 'a' => 'profile')
  130. );
  131. }
  132. $ok = self::updateUser(
  133. Minz_Session::param('currentUser'),
  134. $email,
  135. $passwordPlain,
  136. $apiPasswordPlain,
  137. array(
  138. 'token' => Minz_Request::param('token', null),
  139. )
  140. );
  141. Minz_Session::_param('passwordHash', FreshRSS_Context::$user_conf->passwordHash);
  142. if ($ok) {
  143. if ($system_conf->force_email_validation && $email !== $old_email) {
  144. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'validateEmail'));
  145. } elseif ($passwordPlain == '') {
  146. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'profile'));
  147. } else {
  148. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  149. }
  150. } else {
  151. Minz_Request::bad(_t('feedback.profile.error'),
  152. array('c' => 'user', 'a' => 'profile'));
  153. }
  154. }
  155. }
  156. /**
  157. * This action displays the user management page.
  158. */
  159. public function manageAction() {
  160. if (!FreshRSS_Auth::hasAccess('admin')) {
  161. Minz_Error::error(403);
  162. }
  163. Minz_View::prependTitle(_t('admin.user.title') . ' · ');
  164. $this->view->show_email_field = FreshRSS_Context::$system_conf->force_email_validation;
  165. $this->view->current_user = Minz_Request::param('u');
  166. $this->view->nb_articles = 0;
  167. $this->view->size_user = 0;
  168. if ($this->view->current_user) {
  169. // Get information about the current user.
  170. $entryDAO = FreshRSS_Factory::createEntryDao($this->view->current_user);
  171. $this->view->nb_articles = $entryDAO->count();
  172. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($this->view->current_user);
  173. $this->view->size_user = $databaseDAO->size();
  174. }
  175. }
  176. public static function createUser($new_user_name, $email, $passwordPlain, $apiPasswordPlain, $userConfigOverride = array(), $insertDefaultFeeds = true) {
  177. $userConfig = array();
  178. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  179. if (file_exists($customUserConfigPath)) {
  180. $customUserConfig = include($customUserConfigPath);
  181. }
  182. if (is_array($customUserConfig)) {
  183. $userConfig = $customUserConfig;
  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($userConfig['language'], $insertDefaultFeeds);
  208. $ok &= self::updateUser($new_user_name, $email, $passwordPlain, $apiPasswordPlain);
  209. }
  210. return $ok;
  211. }
  212. /**
  213. * This action creates a new user.
  214. *
  215. * Request parameters are:
  216. * - new_user_language
  217. * - new_user_name
  218. * - new_user_email
  219. * - new_user_passwordPlain
  220. * - r (i.e. a redirection url, optional)
  221. *
  222. * @todo clean up this method. Idea: write a method to init a user with basic information.
  223. * @todo handle r redirection in Minz_Request::forward directly?
  224. */
  225. public function createAction() {
  226. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  227. Minz_Error::error(403);
  228. }
  229. if (Minz_Request::isPost()) {
  230. $system_conf = FreshRSS_Context::$system_conf;
  231. $new_user_name = Minz_Request::param('new_user_name');
  232. $email = Minz_Request::param('new_user_email', '');
  233. $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
  234. $new_user_language = Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language);
  235. $tos_enabled = file_exists(join_path(DATA_PATH, 'tos.html'));
  236. $accept_tos = Minz_Request::param('accept_tos', false);
  237. if ($system_conf->force_email_validation && empty($email)) {
  238. Minz_Request::bad(
  239. _t('user.email.feedback.required'),
  240. array('c' => 'auth', 'a' => 'register')
  241. );
  242. }
  243. if (!empty($email) && !validateEmailAddress($email)) {
  244. Minz_Request::bad(
  245. _t('user.email.feedback.invalid'),
  246. array('c' => 'auth', 'a' => 'register')
  247. );
  248. }
  249. if ($tos_enabled && !$accept_tos) {
  250. Minz_Request::bad(
  251. _t('user.tos.feedback.invalid'),
  252. array('c' => 'auth', 'a' => 'register')
  253. );
  254. }
  255. $ok = self::createUser($new_user_name, $email, $passwordPlain, '', array('language' => $new_user_language));
  256. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  257. $_POST['new_user_passwordPlain'] = '';
  258. invalidateHttpCache();
  259. // If the user has admin access, it means he's already logged in
  260. // and we don't want to login with the new account. Otherwise, the
  261. // user just created its account himself so he probably wants to
  262. // get started immediately.
  263. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  264. $user_conf = get_user_configuration($new_user_name);
  265. Minz_Session::_param('currentUser', $new_user_name);
  266. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  267. Minz_Session::_param('csrf');
  268. FreshRSS_Auth::giveAccess();
  269. }
  270. $notif = array(
  271. 'type' => $ok ? 'good' : 'bad',
  272. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  273. );
  274. Minz_Session::_param('notification', $notif);
  275. }
  276. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  277. if (!$redirect_url) {
  278. $redirect_url = array('c' => 'user', 'a' => 'manage');
  279. }
  280. Minz_Request::forward($redirect_url, true);
  281. }
  282. public static function deleteUser($username) {
  283. $ok = self::checkUsername($username);
  284. if ($ok) {
  285. $default_user = FreshRSS_Context::$system_conf->default_user;
  286. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  287. }
  288. $user_data = join_path(DATA_PATH, 'users', $username);
  289. $ok &= is_dir($user_data);
  290. if ($ok) {
  291. self::deleteFeverKey($username);
  292. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  293. $ok &= $oldUserDAO->deleteUser();
  294. $ok &= recursive_unlink($user_data);
  295. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  296. }
  297. return $ok;
  298. }
  299. /**
  300. * This action validates an email address, based on the token sent by email.
  301. * It also serves the main page when user is blocked.
  302. *
  303. * Request parameters are:
  304. * - username
  305. * - token
  306. *
  307. * This route works with GET requests since the URL is provided by email.
  308. * The security risks (e.g. forged URL by an attacker) are not very high so
  309. * it's ok.
  310. *
  311. * It returns 404 error if `force_email_validation` is disabled or if the
  312. * user doesn't exist.
  313. *
  314. * It returns 403 if user isn't logged in and `username` param isn't passed.
  315. */
  316. public function validateEmailAction() {
  317. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  318. Minz_Error::error(404);
  319. }
  320. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  321. $this->view->_layout('simple');
  322. $username = Minz_Request::param('username');
  323. $token = Minz_Request::param('token');
  324. if ($username) {
  325. $user_config = get_user_configuration($username);
  326. } elseif (FreshRSS_Auth::hasAccess()) {
  327. $user_config = FreshRSS_Context::$user_conf;
  328. } else {
  329. Minz_Error::error(403);
  330. }
  331. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  332. Minz_Error::error(404);
  333. }
  334. if ($user_config->email_validation_token === '') {
  335. Minz_Request::good(
  336. _t('user.email.validation.feedback.unnecessary'),
  337. array('c' => 'index', 'a' => 'index')
  338. );
  339. }
  340. if ($token) {
  341. if ($user_config->email_validation_token !== $token) {
  342. Minz_Request::bad(
  343. _t('user.email.validation.feedback.wrong_token'),
  344. array('c' => 'user', 'a' => 'validateEmail')
  345. );
  346. }
  347. $user_config->email_validation_token = '';
  348. if ($user_config->save()) {
  349. Minz_Request::good(
  350. _t('user.email.validation.feedback.ok'),
  351. array('c' => 'index', 'a' => 'index')
  352. );
  353. } else {
  354. Minz_Request::bad(
  355. _t('user.email.validation.feedback.error'),
  356. array('c' => 'user', 'a' => 'validateEmail')
  357. );
  358. }
  359. }
  360. }
  361. /**
  362. * This action resends a validation email to the current user.
  363. *
  364. * It only acts on POST requests but doesn't require any param (except the
  365. * CSRF token).
  366. *
  367. * It returns 403 error if the user is not logged in or 404 if request is
  368. * not POST. Else it redirects silently to the index if user has already
  369. * validated its email, or to the user#validateEmail route.
  370. */
  371. public function sendValidationEmailAction() {
  372. if (!FreshRSS_Auth::hasAccess()) {
  373. Minz_Error::error(403);
  374. }
  375. if (!Minz_Request::isPost()) {
  376. Minz_Error::error(404);
  377. }
  378. $username = Minz_Session::param('currentUser', '_');
  379. $user_config = FreshRSS_Context::$user_conf;
  380. if ($user_config->email_validation_token === '') {
  381. Minz_Request::forward(array(
  382. 'c' => 'index',
  383. 'a' => 'index',
  384. ), true);
  385. }
  386. $mailer = new FreshRSS_User_Mailer();
  387. $ok = $mailer->send_email_need_validation($username, $user_config);
  388. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  389. if ($ok) {
  390. Minz_Request::good(
  391. _t('user.email.validation.feedback.email_sent'),
  392. $redirect_url
  393. );
  394. } else {
  395. Minz_Request::bad(
  396. _t('user.email.validation.feedback.email_failed'),
  397. $redirect_url
  398. );
  399. }
  400. }
  401. /**
  402. * This action delete an existing user.
  403. *
  404. * Request parameter is:
  405. * - username
  406. *
  407. * @todo clean up this method. Idea: create a User->clean() method.
  408. */
  409. public function deleteAction() {
  410. $username = Minz_Request::param('username');
  411. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  412. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  413. Minz_Error::error(403);
  414. }
  415. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  416. if (!$redirect_url) {
  417. $redirect_url = array('c' => 'user', 'a' => 'manage');
  418. }
  419. if (Minz_Request::isPost()) {
  420. $ok = true;
  421. if ($ok && $self_deletion) {
  422. // We check the password if it's a self-destruction
  423. $nonce = Minz_Session::param('nonce');
  424. $challenge = Minz_Request::param('challenge', '');
  425. $ok &= FreshRSS_FormAuth::checkCredentials(
  426. $username, FreshRSS_Context::$user_conf->passwordHash,
  427. $nonce, $challenge
  428. );
  429. }
  430. if ($ok) {
  431. $ok &= self::deleteUser($username);
  432. }
  433. if ($ok && $self_deletion) {
  434. FreshRSS_Auth::removeAccess();
  435. $redirect_url = array('c' => 'index', 'a' => 'index');
  436. }
  437. invalidateHttpCache();
  438. $notif = array(
  439. 'type' => $ok ? 'good' : 'bad',
  440. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  441. );
  442. Minz_Session::_param('notification', $notif);
  443. }
  444. Minz_Request::forward($redirect_url, true);
  445. }
  446. }