userController.php 17 KB

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