4
0

userController.php 26 KB

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