userController.php 16 KB

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