userController.php 24 KB

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