userController.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Controller to handle user actions.
  5. */
  6. class FreshRSS_user_Controller extends FreshRSS_ActionController {
  7. /**
  8. * The username is also used as folder name, file name, and part of SQL table name.
  9. * '_' is a reserved internal username.
  10. */
  11. public const USERNAME_PATTERN = '([0-9a-zA-Z_][0-9a-zA-Z_.@\-]{1,38}|[0-9a-zA-Z])';
  12. public static function checkUsername(string $username): bool {
  13. return preg_match('/^' . self::USERNAME_PATTERN . '$/', $username) === 1;
  14. }
  15. /**
  16. * Validate an email address, supports internationalized addresses.
  17. *
  18. * @param string $email The address to validate
  19. * @return bool true if email is valid, else false
  20. */
  21. private static function validateEmailAddress(string $email): bool {
  22. $mailer = new PHPMailer\PHPMailer\PHPMailer();
  23. $mailer->CharSet = 'utf-8';
  24. $punyemail = $mailer->punyencodeAddress($email);
  25. return PHPMailer\PHPMailer\PHPMailer::validateAddress($punyemail, 'html5');
  26. }
  27. /**
  28. * @return list<string>
  29. */
  30. public static function listUsers(): array {
  31. $final_list = [];
  32. $base_path = join_path(DATA_PATH, 'users');
  33. $dir_list = array_values(array_diff(
  34. scandir($base_path) ?: [],
  35. ['..', '.', Minz_User::INTERNAL_USER]
  36. ));
  37. foreach ($dir_list as $file) {
  38. if ($file[0] !== '.' && is_dir(join_path($base_path, $file)) && file_exists(join_path($base_path, $file, 'config.php'))) {
  39. $final_list[] = $file;
  40. }
  41. }
  42. return $final_list;
  43. }
  44. public static function userExists(string $username): bool {
  45. $config_path = USERS_PATH . '/' . $username . '/config.php';
  46. if (@file_exists($config_path)) {
  47. return true;
  48. } elseif (@file_exists($config_path . '.bak.php')) {
  49. Minz_Log::warning('Config for user “' . $username . '” not found. Attempting to restore from backup.', ADMIN_LOG);
  50. if (!copy($config_path . '.bak.php', $config_path)) {
  51. @unlink($config_path);
  52. return false;
  53. }
  54. return @file_exists($config_path);
  55. }
  56. return false;
  57. }
  58. /**
  59. * Return if the maximum number of registrations has been reached.
  60. * Note a max_registrations of 0 means there is no limit.
  61. *
  62. * @return bool true if number of users >= max registrations, false otherwise.
  63. */
  64. public static function max_registrations_reached(): bool {
  65. $limit_registrations = FreshRSS_Context::systemConf()->limits['max_registrations'];
  66. $number_accounts = count(self::listUsers());
  67. return $limit_registrations > 0 && $number_accounts >= $limit_registrations;
  68. }
  69. /** @param array<string,mixed> $userConfigUpdated */
  70. public static function updateUser(string $user, ?string $email, #[\SensitiveParameter] string $passwordPlain, array $userConfigUpdated = []): bool {
  71. $userConfig = FreshRSS_UserConfiguration::getForUser($user);
  72. if ($userConfig === null) {
  73. return false;
  74. }
  75. if ($email !== null && $userConfig->mail_login !== $email) {
  76. $userConfig->mail_login = $email;
  77. if (FreshRSS_Context::systemConf()->force_email_validation) {
  78. $userConfig->email_validation_token = hash('sha256', FreshRSS_Context::systemConf()->salt . $email . random_bytes(32));
  79. $mailer = new FreshRSS_User_Mailer();
  80. $mailer->send_email_need_validation($user, $userConfig);
  81. }
  82. }
  83. if ($passwordPlain != '') {
  84. $passwordHash = FreshRSS_password_Util::hash($passwordPlain);
  85. $userConfig->passwordHash = $passwordHash;
  86. if ($user === Minz_User::name()) {
  87. FreshRSS_Context::userConf()->passwordHash = $passwordHash;
  88. }
  89. }
  90. foreach ($userConfigUpdated as $configName => $configValue) {
  91. if ($configName !== '' && $configValue !== null) {
  92. $userConfig->_attribute($configName, $configValue);
  93. }
  94. }
  95. $ok = $userConfig->save();
  96. return $ok;
  97. }
  98. public function updateAction(): void {
  99. if (!FreshRSS_Auth::hasAccess('admin')) {
  100. Minz_Error::error(403);
  101. }
  102. if (Minz_Request::isPost()) {
  103. if (self::reauthRedirect()) {
  104. return;
  105. }
  106. $username = Minz_Request::paramString('username');
  107. $newPasswordPlain = Minz_User::name() !== $username ? Minz_Request::paramString('newPasswordPlain', true) : '';
  108. $ok = self::updateUser($username, null, $newPasswordPlain, [
  109. 'token' => Minz_Request::paramString('token') ?: null,
  110. ]);
  111. if ($ok) {
  112. $isSelfUpdate = Minz_User::name() === $username;
  113. if ($newPasswordPlain == '' || !$isSelfUpdate) {
  114. Minz_Request::good(
  115. _t('feedback.user.updated', $username),
  116. ['c' => 'user', 'a' => 'manage'],
  117. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  118. );
  119. } else {
  120. Minz_Request::good(
  121. _t('feedback.profile.updated'),
  122. ['c' => 'index', 'a' => 'index'],
  123. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  124. );
  125. }
  126. } else {
  127. Minz_Request::bad(_t('feedback.user.updated.error', $username), ['c' => 'user', 'a' => 'manage']);
  128. }
  129. }
  130. }
  131. /**
  132. * This action displays the user profile page.
  133. */
  134. public function profileAction(): void {
  135. if (!FreshRSS_Auth::hasAccess()) {
  136. Minz_Error::error(403);
  137. }
  138. $email_not_verified = FreshRSS_Context::userConf()->email_validation_token != '';
  139. $this->view->disable_aside = false;
  140. if ($email_not_verified) {
  141. $this->view->disable_aside = true;
  142. }
  143. FreshRSS_View::prependTitle(_t('conf.profile.title') . ' · ');
  144. FreshRSS_View::appendScript(Minz_Url::display('/scripts/vendor/bcrypt.js?' . @filemtime(PUBLIC_PATH . '/scripts/vendor/bcrypt.js')));
  145. if (Minz_Request::isPost() && Minz_User::name() != null) {
  146. $old_email = FreshRSS_Context::userConf()->mail_login;
  147. $email = Minz_Request::paramString('email');
  148. $challenge = Minz_Request::paramString('challenge');
  149. $newPasswordPlain = '';
  150. if ($challenge !== '') {
  151. $username = Minz_User::name();
  152. $nonce = Minz_Session::paramString('nonce');
  153. Minz_Session::_param('nonce', false); // One-time: consume the challenge so it cannot be replayed.
  154. $newPasswordPlain = Minz_Request::paramString('newPasswordPlain', plaintext: true);
  155. $confirmPasswordPlain = Minz_Request::paramString('confirmPasswordPlain', plaintext: true);
  156. if (!FreshRSS_FormAuth::checkCredentials(
  157. $username, FreshRSS_Context::userConf()->passwordHash, $nonce, $challenge
  158. ) || strlen($newPasswordPlain) < 7) {
  159. Minz_Session::_param('open', true); // Auto-expand `change password` section
  160. Minz_Request::bad(
  161. _t('feedback.auth.login.invalid'),
  162. ['c' => 'user', 'a' => 'profile']
  163. );
  164. return;
  165. }
  166. if ($newPasswordPlain !== $confirmPasswordPlain) {
  167. Minz_Session::_param('open', true); // Auto-expand `change password` section
  168. Minz_Request::bad(
  169. _t('feedback.profile.passwords_dont_match'),
  170. ['c' => 'user', 'a' => 'profile']
  171. );
  172. return;
  173. }
  174. try {
  175. Minz_Session::regenerateID('FreshRSS');
  176. } catch (RuntimeException $e) {
  177. Minz_Log::error('Session could not be regenerated during password change! ' . $e->getMessage());
  178. Minz_Request::bad(_t('install.session.nok'), ['c' => 'user', 'a' => 'profile']);
  179. return;
  180. }
  181. }
  182. if (FreshRSS_Context::systemConf()->force_email_validation && empty($email)) {
  183. Minz_Request::bad(
  184. _t('user.email.feedback.required'),
  185. ['c' => 'user', 'a' => 'profile']
  186. );
  187. }
  188. if (!empty($email) && !self::validateEmailAddress($email)) {
  189. Minz_Request::bad(
  190. _t('user.email.feedback.invalid'),
  191. ['c' => 'user', 'a' => 'profile']
  192. );
  193. }
  194. $ok = self::updateUser(
  195. Minz_User::name(),
  196. $email,
  197. $newPasswordPlain,
  198. [
  199. 'token' => Minz_Request::paramString('token'),
  200. ]
  201. );
  202. Minz_Session::_param('passwordHash', FreshRSS_Context::userConf()->passwordHash);
  203. if ($ok) {
  204. if (FreshRSS_Context::systemConf()->force_email_validation && $email !== $old_email) {
  205. Minz_Request::good(
  206. _t('feedback.profile.updated'),
  207. ['c' => 'user', 'a' => 'validateEmail'],
  208. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  209. );
  210. } else {
  211. Minz_Request::good(
  212. _t('feedback.profile.updated'),
  213. ['c' => 'user', 'a' => 'profile'],
  214. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  215. );
  216. }
  217. } else {
  218. Minz_Request::bad(_t('feedback.profile.error'), ['c' => 'user', 'a' => 'profile']);
  219. }
  220. }
  221. }
  222. public static function reauthRedirect(): bool {
  223. $url_redirect = [
  224. 'c' => 'user',
  225. 'a' => 'manage',
  226. 'params' => [],
  227. ];
  228. $username = Minz_Request::paramStringNull('username');
  229. if ($username !== null) {
  230. $url_redirect['a'] = 'details';
  231. $url_redirect['params']['username'] = $username;
  232. }
  233. return FreshRSS_Auth::requestReauth($url_redirect);
  234. }
  235. public function purgeAction(): void {
  236. if (!FreshRSS_Auth::hasAccess('admin')) {
  237. Minz_Error::error(403);
  238. }
  239. if (!Minz_Request::isPost()) {
  240. Minz_Error::error(403);
  241. }
  242. if (self::reauthRedirect()) {
  243. return;
  244. }
  245. $username = Minz_Request::paramString('username');
  246. if (!FreshRSS_UserDAO::exists($username)) {
  247. Minz_Error::error(404);
  248. }
  249. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  250. $feedDAO->purge();
  251. }
  252. /**
  253. * This action displays the user management page.
  254. */
  255. public function manageAction(): void {
  256. if (!FreshRSS_Auth::hasAccess('admin')) {
  257. Minz_Error::error(403);
  258. }
  259. if (self::reauthRedirect()) {
  260. return;
  261. }
  262. FreshRSS_View::prependTitle(_t('admin.user.title') . ' · ');
  263. if (Minz_Request::isPost()) {
  264. $action = Minz_Request::paramString('action');
  265. switch ($action) {
  266. case 'delete':
  267. $this->deleteAction();
  268. break;
  269. case 'update':
  270. $this->updateAction();
  271. break;
  272. case 'purge':
  273. $this->purgeAction();
  274. break;
  275. case 'promote':
  276. $this->promoteAction();
  277. break;
  278. case 'demote':
  279. $this->demoteAction();
  280. break;
  281. case 'enable':
  282. $this->enableAction();
  283. break;
  284. case 'disable':
  285. $this->disableAction();
  286. break;
  287. }
  288. }
  289. $this->view->show_email_field = FreshRSS_Context::systemConf()->force_email_validation;
  290. $this->view->current_user = Minz_Request::paramString('u');
  291. $fast = false;
  292. $startTime = time();
  293. foreach (self::listUsers() as $user) {
  294. if (!$fast && (time() - $startTime >= 3)) {
  295. // Disable detailed user statistics if it takes too long, and will retrieve them asynchronously via JavaScript
  296. $fast = true;
  297. }
  298. $this->view->users[$user] = $this->retrieveUserDetails($user, $fast);
  299. }
  300. }
  301. /**
  302. * @param array<string,mixed> $userConfigOverride
  303. * @throws Minz_ConfigurationNamespaceException
  304. * @throws Minz_PDOConnectionException
  305. */
  306. public static function createUser(string $new_user_name, ?string $email, #[\SensitiveParameter] string $passwordPlain,
  307. array $userConfigOverride = [], bool $insertDefaultFeeds = true): bool {
  308. $userConfig = [];
  309. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  310. if (file_exists($customUserConfigPath)) {
  311. $customUserConfig = include $customUserConfigPath;
  312. if (is_array($customUserConfig)) {
  313. $userConfig = $customUserConfig;
  314. }
  315. }
  316. $userConfig = array_merge($userConfig, $userConfigOverride);
  317. $ok = self::checkUsername($new_user_name);
  318. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  319. // create basepath if missing
  320. if (!is_dir(join_path(DATA_PATH, 'users'))) {
  321. $ok &= mkdir(join_path(DATA_PATH, 'users'), 0770, true);
  322. }
  323. $configPath = '';
  324. if ($ok) {
  325. if (!Minz_Translate::exists(is_string($userConfig['language'] ?? null) ? $userConfig['language'] : '')) {
  326. $userConfig['language'] = Minz_Translate::DEFAULT_LANGUAGE;
  327. }
  328. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', self::listUsers()), true); //Not an existing user, case-insensitive
  329. $configPath = join_path($homeDir, 'config.php');
  330. $ok &= !file_exists($configPath);
  331. }
  332. if ($ok) {
  333. // $homeDir must not exist beforehand,
  334. // otherwise it might be multiple remote parties racing to register one username
  335. $ok = mkdir($homeDir, 0770, true);
  336. if ($ok) {
  337. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  338. }
  339. }
  340. if ($ok) {
  341. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  342. $ok &= $newUserDAO->createUser();
  343. if ($ok && $insertDefaultFeeds) {
  344. $opmlPath = DATA_PATH . '/opml.xml';
  345. if (!file_exists($opmlPath)) {
  346. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  347. }
  348. $importController = new FreshRSS_importExport_Controller();
  349. try {
  350. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  351. } catch (Exception $e) {
  352. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  353. }
  354. }
  355. $ok &= self::updateUser($new_user_name, $email, $passwordPlain);
  356. }
  357. return (bool)$ok;
  358. }
  359. /**
  360. * This action creates a new user.
  361. *
  362. * Request parameters are:
  363. * - new_user_language
  364. * - new_user_name
  365. * - new_user_email
  366. * - new_user_passwordPlain
  367. * - r (i.e. a redirection url, optional)
  368. *
  369. * @todo clean up this method. Idea: write a method to init a user with basic information.
  370. */
  371. public function createAction(): void {
  372. if (!FreshRSS_Auth::hasAccess('admin') && self::max_registrations_reached()) {
  373. Minz_Error::error(403);
  374. }
  375. if (FreshRSS_Auth::hasAccess('admin') && self::reauthRedirect()) {
  376. return;
  377. }
  378. if (Minz_Request::isPost()) {
  379. $new_user_name = Minz_Request::paramString('new_user_name');
  380. $email = Minz_Request::paramString('new_user_email');
  381. $passwordPlain = Minz_Request::paramString('new_user_passwordPlain', true);
  382. $badRedirectUrl = [
  383. 'c' => Minz_Request::paramString('originController') ?: 'auth',
  384. 'a' => Minz_Request::paramString('originAction') ?: 'register',
  385. ];
  386. if (!self::checkUsername($new_user_name)) {
  387. Minz_Request::bad(
  388. _t('user.username.invalid'),
  389. $badRedirectUrl
  390. );
  391. }
  392. if (FreshRSS_UserDAO::exists($new_user_name)) {
  393. Minz_Request::bad(
  394. _t('user.username.taken', $new_user_name),
  395. $badRedirectUrl
  396. );
  397. }
  398. if (!FreshRSS_password_Util::check($passwordPlain)) {
  399. Minz_Request::bad(
  400. _t('user.password.invalid'),
  401. $badRedirectUrl
  402. );
  403. }
  404. if (!FreshRSS_Auth::hasAccess('admin')) {
  405. // TODO: We may want to ask the user to accept TOS before first login
  406. $tos_enabled = file_exists(TOS_FILENAME);
  407. $accept_tos = Minz_Request::paramBoolean('accept_tos');
  408. if ($tos_enabled && !$accept_tos) {
  409. Minz_Request::bad(_t('user.tos.feedback.invalid'), $badRedirectUrl);
  410. }
  411. }
  412. if (FreshRSS_Context::systemConf()->force_email_validation && empty($email)) {
  413. Minz_Request::bad(
  414. _t('user.email.feedback.required'),
  415. $badRedirectUrl
  416. );
  417. }
  418. if (!empty($email) && !self::validateEmailAddress($email)) {
  419. Minz_Request::bad(
  420. _t('user.email.feedback.invalid'),
  421. $badRedirectUrl
  422. );
  423. }
  424. $is_admin = false;
  425. if (FreshRSS_Auth::hasAccess('admin')) {
  426. $is_admin = Minz_Request::paramBoolean('new_user_is_admin');
  427. }
  428. $ok = self::createUser($new_user_name, $email, $passwordPlain, [
  429. 'language' => Minz_Request::paramString('new_user_language') ?: FreshRSS_Context::userConf()->language,
  430. 'timezone' => Minz_Request::paramString('new_user_timezone'),
  431. 'is_admin' => $is_admin,
  432. 'enabled' => true,
  433. ]);
  434. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  435. $_POST['new_user_passwordPlain'] = '';
  436. invalidateHttpCache();
  437. // If the user has admin access, it means he’s already logged in
  438. // and we don’t want to login with the new account. Otherwise, the
  439. // user just created its account himself so he probably wants to
  440. // get started immediately.
  441. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  442. $user_conf = FreshRSS_UserConfiguration::getForUser($new_user_name);
  443. if ($user_conf !== null) {
  444. Minz_Session::_params([
  445. Minz_User::CURRENT_USER => $new_user_name,
  446. 'passwordHash' => $user_conf->passwordHash,
  447. 'csrf' => false,
  448. ]);
  449. FreshRSS_Auth::giveAccess();
  450. } else {
  451. $ok = false;
  452. }
  453. }
  454. if ($ok) {
  455. Minz_Request::setGoodNotification(_t('feedback.user.created', $new_user_name));
  456. } else {
  457. Minz_Request::setBadNotification(_t('feedback.user.created.error', $new_user_name));
  458. }
  459. }
  460. if (FreshRSS_Auth::hasAccess('admin')) {
  461. $redirect_url = ['c' => 'user', 'a' => 'manage'];
  462. } else {
  463. $redirect_url = ['c' => 'index', 'a' => 'index'];
  464. }
  465. Minz_Request::forward($redirect_url, true);
  466. }
  467. public static function deleteUser(string $username): bool {
  468. $ok = self::checkUsername($username);
  469. if ($ok) {
  470. $default_user = FreshRSS_Context::systemConf()->default_user;
  471. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  472. }
  473. $user_data = join_path(DATA_PATH, 'users', $username);
  474. $ok &= is_dir($user_data);
  475. if ($ok) {
  476. FreshRSS_fever_Util::deleteKey($username);
  477. Minz_ModelPdo::$usesSharedPdo = false;
  478. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  479. $ok &= $oldUserDAO->deleteUser();
  480. Minz_ModelPdo::$usesSharedPdo = true;
  481. $ok &= recursive_unlink($user_data);
  482. $filenames = glob(PSHB_PATH . '/feeds/*/' . $username . '.txt');
  483. if (!empty($filenames)) {
  484. array_map('unlink', $filenames);
  485. }
  486. }
  487. return (bool)$ok;
  488. }
  489. /**
  490. * This action validates an email address, based on the token sent by email.
  491. * It also serves the main page when user is blocked.
  492. *
  493. * Request parameters are:
  494. * - username
  495. * - token
  496. *
  497. * This route works with GET requests since the URL is provided by email.
  498. * The security risks (e.g. forged URL by an attacker) are not very high so
  499. * it’s ok.
  500. *
  501. * It returns 404 error if `force_email_validation` is disabled or if the
  502. * user doesn’t exist.
  503. *
  504. * It returns 403 if user isn’t logged in and `username` param isn’t passed.
  505. */
  506. public function validateEmailAction(): void {
  507. if (!FreshRSS_Context::systemConf()->force_email_validation) {
  508. Minz_Error::error(404);
  509. }
  510. FreshRSS_View::prependTitle(_t('user.email.validation.title') . ' · ');
  511. $username = Minz_Request::paramString('username');
  512. if (FreshRSS_Auth::hasAccess()) {
  513. $username = Minz_User::name() ?? '';
  514. }
  515. $token = Minz_Request::paramString('token');
  516. if ($username !== '') {
  517. $user_config = FreshRSS_UserConfiguration::getForUser($username);
  518. } elseif (FreshRSS_Auth::hasAccess()) {
  519. $user_config = FreshRSS_Context::userConf();
  520. } else {
  521. Minz_Error::error(403);
  522. return;
  523. }
  524. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  525. Minz_Error::error(404);
  526. return;
  527. }
  528. if ($user_config->email_validation_token === '') {
  529. Minz_Request::good(
  530. _t('user.email.validation.feedback.unnecessary'),
  531. ['c' => 'index', 'a' => 'index'],
  532. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  533. );
  534. }
  535. if ($token != '') {
  536. if (!hash_equals($user_config->email_validation_token, $token)) {
  537. Minz_Request::bad(
  538. _t('user.email.validation.feedback.wrong_token'),
  539. ['c' => 'user', 'a' => 'validateEmail']
  540. );
  541. }
  542. $user_config->email_validation_token = '';
  543. if ($user_config->save()) {
  544. Minz_Request::good(
  545. _t('user.email.validation.feedback.ok'),
  546. ['c' => 'index', 'a' => 'index'],
  547. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  548. );
  549. } else {
  550. Minz_Request::bad(
  551. _t('user.email.validation.feedback.error'),
  552. ['c' => 'user', 'a' => 'validateEmail']
  553. );
  554. }
  555. }
  556. }
  557. /**
  558. * This action resends a validation email to the current user.
  559. *
  560. * It only acts on POST requests but doesn’t require any param (except the
  561. * CSRF token).
  562. *
  563. * It returns 403 error if the user is not logged in or 404 if request is
  564. * not POST. Else it redirects silently to the index if user has already
  565. * validated its email, or to the user#validateEmail route.
  566. */
  567. public function sendValidationEmailAction(): void {
  568. if (!FreshRSS_Auth::hasAccess()) {
  569. Minz_Error::error(403);
  570. }
  571. if (!Minz_Request::isPost()) {
  572. Minz_Error::error(404);
  573. }
  574. $username = Minz_User::name();
  575. if (FreshRSS_Context::userConf()->email_validation_token === '') {
  576. Minz_Request::forward([
  577. 'c' => 'index',
  578. 'a' => 'index',
  579. ], true);
  580. }
  581. $mailer = new FreshRSS_User_Mailer();
  582. $ok = $username != null && $mailer->send_email_need_validation($username, FreshRSS_Context::userConf());
  583. $redirect_url = ['c' => 'user', 'a' => 'validateEmail'];
  584. if ($ok) {
  585. Minz_Request::good(
  586. _t('user.email.validation.feedback.email_sent'),
  587. $redirect_url,
  588. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  589. );
  590. } else {
  591. Minz_Request::bad(
  592. _t('user.email.validation.feedback.email_failed'),
  593. $redirect_url
  594. );
  595. }
  596. }
  597. /**
  598. * This action delete an existing user.
  599. *
  600. * Request parameter is:
  601. * - username
  602. *
  603. * @todo clean up this method. Idea: create a User->clean() method.
  604. */
  605. public function deleteAction(): void {
  606. $username = Minz_Request::paramString('username');
  607. $self_deletion = Minz_User::name() === $username;
  608. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  609. Minz_Error::error(403);
  610. }
  611. $redirect_url = ['c' => 'user', 'a' => 'manage'];
  612. if (Minz_Request::isPost()) {
  613. $ok = true;
  614. if ($self_deletion) {
  615. // We check the password if it’s a self-destruction
  616. $nonce = Minz_Session::paramString('nonce');
  617. Minz_Session::_param('nonce', false); // One-time: consume the challenge so it cannot be replayed.
  618. $challenge = Minz_Request::paramString('challenge');
  619. $ok &= FreshRSS_FormAuth::checkCredentials(
  620. $username, FreshRSS_Context::userConf()->passwordHash,
  621. $nonce, $challenge
  622. );
  623. if (!$ok) {
  624. Minz_Request::bad(_t('feedback.auth.login.invalid'), ['c' => 'user', 'a' => 'profile']);
  625. return;
  626. }
  627. } elseif (self::reauthRedirect()) {
  628. return;
  629. }
  630. $ok &= self::deleteUser($username);
  631. if ($ok && $self_deletion) {
  632. FreshRSS_Auth::removeAccess();
  633. Minz_Session::_param('csrf', false);
  634. $redirect_url = ['c' => 'index', 'a' => 'index'];
  635. }
  636. invalidateHttpCache();
  637. if ($ok) {
  638. Minz_Request::setGoodNotification(_t('feedback.user.deleted', $username));
  639. } else {
  640. Minz_Request::setBadNotification(_t('feedback.user.deleted.error', $username));
  641. }
  642. }
  643. Minz_Request::forward($redirect_url, true);
  644. }
  645. public function promoteAction(): void {
  646. $this->toggleAction('is_admin', true);
  647. }
  648. public function demoteAction(): void {
  649. $this->toggleAction('is_admin', false);
  650. }
  651. public function enableAction(): void {
  652. $this->toggleAction('enabled', true);
  653. }
  654. public function disableAction(): void {
  655. $this->toggleAction('enabled', false);
  656. }
  657. private function toggleAction(string $field, bool $value): void {
  658. if (!FreshRSS_Auth::hasAccess('admin')) {
  659. Minz_Error::error(403);
  660. }
  661. if (!Minz_Request::isPost()) {
  662. Minz_Error::error(403);
  663. }
  664. if (self::reauthRedirect()) {
  665. return;
  666. }
  667. $username = Minz_Request::paramString('username');
  668. if (!FreshRSS_UserDAO::exists($username)) {
  669. Minz_Error::error(404);
  670. }
  671. if (null === $userConfig = FreshRSS_UserConfiguration::getForUser($username)) {
  672. Minz_Error::error(500);
  673. return;
  674. }
  675. if ($field === '') {
  676. Minz_Error::error(400, 'Invalid field name');
  677. return;
  678. }
  679. $userConfig->_attribute($field, $value);
  680. $ok = $userConfig->save();
  681. FreshRSS_UserDAO::touch($username);
  682. if ($ok) {
  683. Minz_Request::good(
  684. _t('feedback.user.updated', $username),
  685. ['c' => 'user', 'a' => 'manage'],
  686. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  687. );
  688. } else {
  689. Minz_Request::bad(
  690. _t('feedback.user.updated.error', $username),
  691. ['c' => 'user', 'a' => 'manage']
  692. );
  693. }
  694. }
  695. public function detailsAction(): void {
  696. if (!FreshRSS_Auth::hasAccess('admin')) {
  697. Minz_Error::error(403);
  698. }
  699. if (self::reauthRedirect()) {
  700. return;
  701. }
  702. $username = Minz_Request::paramString('username');
  703. if (!FreshRSS_UserDAO::exists($username)) {
  704. Minz_Error::error(404);
  705. }
  706. if (Minz_Request::paramBoolean('ajax')) {
  707. $this->view->_layout(null);
  708. }
  709. $this->view->username = $username;
  710. $this->view->details = $this->retrieveUserDetails($username);
  711. FreshRSS_View::prependTitle($username . ' · ' . _t('gen.menu.user_management') . ' · ');
  712. }
  713. /** @return array{feed_count:?int,article_count:?int,database_size:?int,language:string,mail_login:string,enabled:bool,is_admin:bool,last_user_activity:string,is_default:bool} */
  714. private function retrieveUserDetails(string $username, bool $fast = false): array {
  715. $feedDAO = $fast ? null : FreshRSS_Factory::createFeedDao($username);
  716. $entryDAO = $fast ? null : FreshRSS_Factory::createEntryDao($username);
  717. $databaseDAO = $fast ? null : FreshRSS_Factory::createDatabaseDAO($username);
  718. $userConfiguration = FreshRSS_UserConfiguration::getForUser($username);
  719. if ($userConfiguration === null) {
  720. throw new Exception('Error loading user configuration!');
  721. }
  722. return [
  723. 'feed_count' => isset($feedDAO) ? $feedDAO->count() : null,
  724. 'article_count' => isset($entryDAO) ? $entryDAO->count() : null,
  725. 'database_size' => isset($databaseDAO) ? $databaseDAO->size() : null,
  726. 'language' => $userConfiguration->language,
  727. 'mail_login' => $userConfiguration->mail_login,
  728. 'enabled' => $userConfiguration->enabled,
  729. 'is_admin' => $userConfiguration->is_admin,
  730. 'last_user_activity' => date('c', FreshRSS_UserDAO::mtime($username)) ?: '',
  731. 'is_default' => FreshRSS_Context::systemConf()->default_user === $username,
  732. ];
  733. }
  734. }