userController.php 25 KB

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