userController.php 25 KB

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