4
0

userController.php 26 KB

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