userController.php 16 KB

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