userController.php 16 KB

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