userController.php 25 KB

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