userController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. public static function userExists(string $username): bool {
  16. $config_path = USERS_PATH . '/' . $username . '/config.php';
  17. if (@file_exists($config_path)) {
  18. return true;
  19. } elseif (@file_exists($config_path . '.bak.php')) {
  20. Minz_Log::warning('Config for user “' . $username . '” not found. Attempting to restore from backup.', ADMIN_LOG);
  21. if (!copy($config_path . '.bak.php', $config_path)) {
  22. @unlink($config_path);
  23. return false;
  24. }
  25. return @file_exists($config_path);
  26. }
  27. return false;
  28. }
  29. /** @param array<string,mixed> $userConfigUpdated */
  30. public static function updateUser(string $user, ?string $email, string $passwordPlain, array $userConfigUpdated = []): bool {
  31. $userConfig = get_user_configuration($user);
  32. if ($userConfig === null) {
  33. return false;
  34. }
  35. if ($email !== null && $userConfig->mail_login !== $email) {
  36. $userConfig->mail_login = $email;
  37. if (FreshRSS_Context::systemConf()->force_email_validation) {
  38. $salt = FreshRSS_Context::systemConf()->salt;
  39. $userConfig->email_validation_token = sha1($salt . uniqid('' . mt_rand(), true));
  40. $mailer = new FreshRSS_User_Mailer();
  41. $mailer->send_email_need_validation($user, $userConfig);
  42. }
  43. }
  44. if ($passwordPlain != '') {
  45. $passwordHash = FreshRSS_password_Util::hash($passwordPlain);
  46. $userConfig->passwordHash = $passwordHash;
  47. if ($user === Minz_User::name()) {
  48. FreshRSS_Context::userConf()->passwordHash = $passwordHash;
  49. }
  50. }
  51. foreach ($userConfigUpdated as $configName => $configValue) {
  52. if ($configName !== '' && $configValue !== null) {
  53. $userConfig->_attribute($configName, $configValue);
  54. }
  55. }
  56. $ok = $userConfig->save();
  57. return $ok;
  58. }
  59. public function updateAction(): void {
  60. if (!FreshRSS_Auth::hasAccess('admin')) {
  61. Minz_Error::error(403);
  62. }
  63. if (Minz_Request::isPost()) {
  64. if (self::reauthRedirect()) {
  65. return;
  66. }
  67. $username = Minz_Request::paramString('username');
  68. $newPasswordPlain = Minz_User::name() !== $username ? Minz_Request::paramString('newPasswordPlain', true) : '';
  69. $ok = self::updateUser($username, null, $newPasswordPlain, [
  70. 'token' => Minz_Request::paramString('token') ?: null,
  71. ]);
  72. if ($ok) {
  73. $isSelfUpdate = Minz_User::name() === $username;
  74. if ($newPasswordPlain == '' || !$isSelfUpdate) {
  75. Minz_Request::good(_t('feedback.user.updated', $username), ['c' => 'user', 'a' => 'manage']);
  76. } else {
  77. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'index', 'a' => 'index']);
  78. }
  79. } else {
  80. Minz_Request::bad(_t('feedback.user.updated.error', $username), ['c' => 'user', 'a' => 'manage']);
  81. }
  82. }
  83. }
  84. /**
  85. * This action displays the user profile page.
  86. */
  87. public function profileAction(): void {
  88. if (!FreshRSS_Auth::hasAccess()) {
  89. Minz_Error::error(403);
  90. }
  91. $email_not_verified = FreshRSS_Context::userConf()->email_validation_token != '';
  92. $this->view->disable_aside = false;
  93. if ($email_not_verified) {
  94. $this->view->_layout('simple');
  95. $this->view->disable_aside = true;
  96. }
  97. FreshRSS_View::prependTitle(_t('conf.profile.title') . ' · ');
  98. FreshRSS_View::appendScript(Minz_Url::display('/scripts/vendor/bcrypt.js?' . @filemtime(PUBLIC_PATH . '/scripts/vendor/bcrypt.js')));
  99. if (Minz_Request::isPost() && Minz_User::name() != null) {
  100. $old_email = FreshRSS_Context::userConf()->mail_login;
  101. $email = Minz_Request::paramString('email');
  102. $challenge = Minz_Request::paramString('challenge');
  103. $newPasswordPlain = '';
  104. if ($challenge !== '') {
  105. $username = Minz_User::name();
  106. $nonce = Minz_Session::paramString('nonce');
  107. $newPasswordPlain = Minz_Request::paramString('newPasswordPlain', plaintext: true);
  108. $confirmPasswordPlain = Minz_Request::paramString('confirmPasswordPlain', plaintext: true);
  109. if (!FreshRSS_FormAuth::checkCredentials(
  110. $username, FreshRSS_Context::userConf()->passwordHash, $nonce, $challenge
  111. ) || strlen($newPasswordPlain) < 7) {
  112. Minz_Session::_param('open', true); // Auto-expand `change password` section
  113. Minz_Request::bad(
  114. _t('feedback.auth.login.invalid'),
  115. ['c' => 'user', 'a' => 'profile']
  116. );
  117. return;
  118. }
  119. if ($newPasswordPlain !== $confirmPasswordPlain) {
  120. Minz_Session::_param('open', true); // Auto-expand `change password` section
  121. Minz_Request::bad(
  122. _t('feedback.profile.passwords_dont_match'),
  123. ['c' => 'user', 'a' => 'profile']
  124. );
  125. return;
  126. }
  127. ini_set('session.use_cookies', '1');
  128. Minz_Session::lock();
  129. Minz_Session::regenerateID();
  130. Minz_Session::unlock();
  131. }
  132. if (FreshRSS_Context::systemConf()->force_email_validation && empty($email)) {
  133. Minz_Request::bad(
  134. _t('user.email.feedback.required'),
  135. ['c' => 'user', 'a' => 'profile']
  136. );
  137. }
  138. if (!empty($email) && !validateEmailAddress($email)) {
  139. Minz_Request::bad(
  140. _t('user.email.feedback.invalid'),
  141. ['c' => 'user', 'a' => 'profile']
  142. );
  143. }
  144. $ok = self::updateUser(
  145. Minz_User::name(),
  146. $email,
  147. $newPasswordPlain,
  148. [
  149. 'token' => Minz_Request::paramString('token'),
  150. ]
  151. );
  152. Minz_Session::_param('passwordHash', FreshRSS_Context::userConf()->passwordHash);
  153. if ($ok) {
  154. if (FreshRSS_Context::systemConf()->force_email_validation && $email !== $old_email) {
  155. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'user', 'a' => 'validateEmail']);
  156. } elseif ($newPasswordPlain == '') {
  157. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'user', 'a' => 'profile']);
  158. } else {
  159. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'index', 'a' => 'index']);
  160. }
  161. } else {
  162. Minz_Request::bad(_t('feedback.profile.error'), ['c' => 'user', 'a' => 'profile']);
  163. }
  164. }
  165. }
  166. public static function reauthRedirect(): bool {
  167. $url_redirect = [
  168. 'c' => 'user',
  169. 'a' => 'manage',
  170. 'params' => [],
  171. ];
  172. $username = Minz_Request::paramStringNull('username');
  173. if ($username !== null) {
  174. $url_redirect['a'] = 'details';
  175. $url_redirect['params']['username'] = $username;
  176. }
  177. return FreshRSS_Auth::requestReauth($url_redirect);
  178. }
  179. public function purgeAction(): void {
  180. if (!FreshRSS_Auth::hasAccess('admin')) {
  181. Minz_Error::error(403);
  182. }
  183. if (!Minz_Request::isPost()) {
  184. Minz_Error::error(403);
  185. }
  186. if (self::reauthRedirect()) {
  187. return;
  188. }
  189. $username = Minz_Request::paramString('username');
  190. if (!FreshRSS_UserDAO::exists($username)) {
  191. Minz_Error::error(404);
  192. }
  193. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  194. $feedDAO->purge();
  195. }
  196. /**
  197. * This action displays the user management page.
  198. */
  199. public function manageAction(): void {
  200. if (!FreshRSS_Auth::hasAccess('admin')) {
  201. Minz_Error::error(403);
  202. }
  203. if (self::reauthRedirect()) {
  204. return;
  205. }
  206. FreshRSS_View::prependTitle(_t('admin.user.title') . ' · ');
  207. if (Minz_Request::isPost()) {
  208. $action = Minz_Request::paramString('action');
  209. switch ($action) {
  210. case 'delete':
  211. $this->deleteAction();
  212. break;
  213. case 'update':
  214. $this->updateAction();
  215. break;
  216. case 'purge':
  217. $this->purgeAction();
  218. break;
  219. case 'promote':
  220. $this->promoteAction();
  221. break;
  222. case 'demote':
  223. $this->demoteAction();
  224. break;
  225. case 'enable':
  226. $this->enableAction();
  227. break;
  228. case 'disable':
  229. $this->disableAction();
  230. break;
  231. }
  232. }
  233. $this->view->show_email_field = FreshRSS_Context::systemConf()->force_email_validation;
  234. $this->view->current_user = Minz_Request::paramString('u');
  235. foreach (listUsers() as $user) {
  236. $this->view->users[$user] = $this->retrieveUserDetails($user);
  237. }
  238. }
  239. /**
  240. * @param array<string,mixed> $userConfigOverride
  241. * @throws Minz_ConfigurationNamespaceException
  242. * @throws Minz_PDOConnectionException
  243. */
  244. public static function createUser(string $new_user_name, ?string $email, string $passwordPlain,
  245. array $userConfigOverride = [], bool $insertDefaultFeeds = true): bool {
  246. $userConfig = [];
  247. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  248. if (file_exists($customUserConfigPath)) {
  249. $customUserConfig = include($customUserConfigPath);
  250. if (is_array($customUserConfig)) {
  251. $userConfig = $customUserConfig;
  252. }
  253. }
  254. $userConfig = array_merge($userConfig, $userConfigOverride);
  255. $ok = self::checkUsername($new_user_name);
  256. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  257. // create basepath if missing
  258. if (!is_dir(join_path(DATA_PATH, 'users'))) {
  259. $ok &= mkdir(join_path(DATA_PATH, 'users'), 0770, true);
  260. }
  261. $configPath = '';
  262. if ($ok) {
  263. $languages = Minz_Translate::availableLanguages();
  264. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages, true)) {
  265. $userConfig['language'] = 'en';
  266. }
  267. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers()), true); //Not an existing user, case-insensitive
  268. $configPath = join_path($homeDir, 'config.php');
  269. $ok &= !file_exists($configPath);
  270. }
  271. if ($ok) {
  272. // $homeDir must not exist beforehand,
  273. // otherwise it might be multiple remote parties racing to register one username
  274. $ok = mkdir($homeDir, 0770, true);
  275. if ($ok) {
  276. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  277. }
  278. }
  279. if ($ok) {
  280. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  281. $ok &= $newUserDAO->createUser();
  282. if ($ok && $insertDefaultFeeds) {
  283. $opmlPath = DATA_PATH . '/opml.xml';
  284. if (!file_exists($opmlPath)) {
  285. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  286. }
  287. $importController = new FreshRSS_importExport_Controller();
  288. try {
  289. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  290. } catch (Exception $e) {
  291. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  292. }
  293. }
  294. $ok &= self::updateUser($new_user_name, $email, $passwordPlain);
  295. }
  296. return (bool)$ok;
  297. }
  298. /**
  299. * This action creates a new user.
  300. *
  301. * Request parameters are:
  302. * - new_user_language
  303. * - new_user_name
  304. * - new_user_email
  305. * - new_user_passwordPlain
  306. * - r (i.e. a redirection url, optional)
  307. *
  308. * @todo clean up this method. Idea: write a method to init a user with basic information.
  309. */
  310. public function createAction(): void {
  311. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  312. Minz_Error::error(403);
  313. }
  314. if (FreshRSS_Auth::hasAccess('admin') && self::reauthRedirect()) {
  315. return;
  316. }
  317. if (Minz_Request::isPost()) {
  318. $new_user_name = Minz_Request::paramString('new_user_name');
  319. $email = Minz_Request::paramString('new_user_email');
  320. $passwordPlain = Minz_Request::paramString('new_user_passwordPlain', true);
  321. $badRedirectUrl = [
  322. 'c' => Minz_Request::paramString('originController') ?: 'auth',
  323. 'a' => Minz_Request::paramString('originAction') ?: 'register',
  324. ];
  325. if (!self::checkUsername($new_user_name)) {
  326. Minz_Request::bad(
  327. _t('user.username.invalid'),
  328. $badRedirectUrl
  329. );
  330. }
  331. if (FreshRSS_UserDAO::exists($new_user_name)) {
  332. Minz_Request::bad(
  333. _t('user.username.taken', $new_user_name),
  334. $badRedirectUrl
  335. );
  336. }
  337. if (!FreshRSS_password_Util::check($passwordPlain)) {
  338. Minz_Request::bad(
  339. _t('user.password.invalid'),
  340. $badRedirectUrl
  341. );
  342. }
  343. if (!FreshRSS_Auth::hasAccess('admin')) {
  344. // TODO: We may want to ask the user to accept TOS before first login
  345. $tos_enabled = file_exists(TOS_FILENAME);
  346. $accept_tos = Minz_Request::paramBoolean('accept_tos');
  347. if ($tos_enabled && !$accept_tos) {
  348. Minz_Request::bad(_t('user.tos.feedback.invalid'), $badRedirectUrl);
  349. }
  350. }
  351. if (FreshRSS_Context::systemConf()->force_email_validation && empty($email)) {
  352. Minz_Request::bad(
  353. _t('user.email.feedback.required'),
  354. $badRedirectUrl
  355. );
  356. }
  357. if (!empty($email) && !validateEmailAddress($email)) {
  358. Minz_Request::bad(
  359. _t('user.email.feedback.invalid'),
  360. $badRedirectUrl
  361. );
  362. }
  363. $is_admin = false;
  364. if (FreshRSS_Auth::hasAccess('admin')) {
  365. $is_admin = Minz_Request::paramBoolean('new_user_is_admin');
  366. }
  367. $ok = self::createUser($new_user_name, $email, $passwordPlain, [
  368. 'language' => Minz_Request::paramString('new_user_language') ?: FreshRSS_Context::userConf()->language,
  369. 'timezone' => Minz_Request::paramString('new_user_timezone'),
  370. 'is_admin' => $is_admin,
  371. 'enabled' => true,
  372. ]);
  373. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  374. $_POST['new_user_passwordPlain'] = '';
  375. invalidateHttpCache();
  376. // If the user has admin access, it means he’s already logged in
  377. // and we don’t want to login with the new account. Otherwise, the
  378. // user just created its account himself so he probably wants to
  379. // get started immediately.
  380. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  381. $user_conf = get_user_configuration($new_user_name);
  382. if ($user_conf !== null) {
  383. Minz_Session::_params([
  384. Minz_User::CURRENT_USER => $new_user_name,
  385. 'passwordHash' => $user_conf->passwordHash,
  386. 'csrf' => false,
  387. ]);
  388. FreshRSS_Auth::giveAccess();
  389. } else {
  390. $ok = false;
  391. }
  392. }
  393. if ($ok) {
  394. Minz_Request::setGoodNotification(_t('feedback.user.created', $new_user_name));
  395. } else {
  396. Minz_Request::setBadNotification(_t('feedback.user.created.error', $new_user_name));
  397. }
  398. }
  399. if (FreshRSS_Auth::hasAccess('admin')) {
  400. $redirect_url = ['c' => 'user', 'a' => 'manage'];
  401. } else {
  402. $redirect_url = ['c' => 'index', 'a' => 'index'];
  403. }
  404. Minz_Request::forward($redirect_url, true);
  405. }
  406. public static function deleteUser(string $username): bool {
  407. $ok = self::checkUsername($username);
  408. if ($ok) {
  409. $default_user = FreshRSS_Context::systemConf()->default_user;
  410. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  411. }
  412. $user_data = join_path(DATA_PATH, 'users', $username);
  413. $ok &= is_dir($user_data);
  414. if ($ok) {
  415. FreshRSS_fever_Util::deleteKey($username);
  416. Minz_ModelPdo::$usesSharedPdo = false;
  417. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  418. $ok &= $oldUserDAO->deleteUser();
  419. Minz_ModelPdo::$usesSharedPdo = true;
  420. $ok &= recursive_unlink($user_data);
  421. $filenames = glob(PSHB_PATH . '/feeds/*/' . $username . '.txt');
  422. if (!empty($filenames)) {
  423. array_map('unlink', $filenames);
  424. }
  425. }
  426. return (bool)$ok;
  427. }
  428. /**
  429. * This action validates an email address, based on the token sent by email.
  430. * It also serves the main page when user is blocked.
  431. *
  432. * Request parameters are:
  433. * - username
  434. * - token
  435. *
  436. * This route works with GET requests since the URL is provided by email.
  437. * The security risks (e.g. forged URL by an attacker) are not very high so
  438. * it’s ok.
  439. *
  440. * It returns 404 error if `force_email_validation` is disabled or if the
  441. * user doesn’t exist.
  442. *
  443. * It returns 403 if user isn’t logged in and `username` param isn’t passed.
  444. */
  445. public function validateEmailAction(): void {
  446. if (!FreshRSS_Context::systemConf()->force_email_validation) {
  447. Minz_Error::error(404);
  448. }
  449. FreshRSS_View::prependTitle(_t('user.email.validation.title') . ' · ');
  450. $this->view->_layout('simple');
  451. $username = Minz_Request::paramString('username');
  452. $token = Minz_Request::paramString('token');
  453. if ($username !== '') {
  454. $user_config = get_user_configuration($username);
  455. } elseif (FreshRSS_Auth::hasAccess()) {
  456. $user_config = FreshRSS_Context::userConf();
  457. } else {
  458. Minz_Error::error(403);
  459. return;
  460. }
  461. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  462. Minz_Error::error(404);
  463. return;
  464. }
  465. if ($user_config->email_validation_token === '') {
  466. Minz_Request::good(
  467. _t('user.email.validation.feedback.unnecessary'),
  468. ['c' => 'index', 'a' => 'index']
  469. );
  470. }
  471. if ($token != '') {
  472. if ($user_config->email_validation_token !== $token) {
  473. Minz_Request::bad(
  474. _t('user.email.validation.feedback.wrong_token'),
  475. ['c' => 'user', 'a' => 'validateEmail']
  476. );
  477. }
  478. $user_config->email_validation_token = '';
  479. if ($user_config->save()) {
  480. Minz_Request::good(
  481. _t('user.email.validation.feedback.ok'),
  482. ['c' => 'index', 'a' => 'index']
  483. );
  484. } else {
  485. Minz_Request::bad(
  486. _t('user.email.validation.feedback.error'),
  487. ['c' => 'user', 'a' => 'validateEmail']
  488. );
  489. }
  490. }
  491. }
  492. /**
  493. * This action resends a validation email to the current user.
  494. *
  495. * It only acts on POST requests but doesn’t require any param (except the
  496. * CSRF token).
  497. *
  498. * It returns 403 error if the user is not logged in or 404 if request is
  499. * not POST. Else it redirects silently to the index if user has already
  500. * validated its email, or to the user#validateEmail route.
  501. */
  502. public function sendValidationEmailAction(): void {
  503. if (!FreshRSS_Auth::hasAccess()) {
  504. Minz_Error::error(403);
  505. }
  506. if (!Minz_Request::isPost()) {
  507. Minz_Error::error(404);
  508. }
  509. $username = Minz_User::name();
  510. if (FreshRSS_Context::userConf()->email_validation_token === '') {
  511. Minz_Request::forward([
  512. 'c' => 'index',
  513. 'a' => 'index',
  514. ], true);
  515. }
  516. $mailer = new FreshRSS_User_Mailer();
  517. $ok = $username != null && $mailer->send_email_need_validation($username, FreshRSS_Context::userConf());
  518. $redirect_url = ['c' => 'user', 'a' => 'validateEmail'];
  519. if ($ok) {
  520. Minz_Request::good(
  521. _t('user.email.validation.feedback.email_sent'),
  522. $redirect_url
  523. );
  524. } else {
  525. Minz_Request::bad(
  526. _t('user.email.validation.feedback.email_failed'),
  527. $redirect_url
  528. );
  529. }
  530. }
  531. /**
  532. * This action delete an existing user.
  533. *
  534. * Request parameter is:
  535. * - username
  536. *
  537. * @todo clean up this method. Idea: create a User->clean() method.
  538. */
  539. public function deleteAction(): void {
  540. $username = Minz_Request::paramString('username');
  541. $self_deletion = Minz_User::name() === $username;
  542. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  543. Minz_Error::error(403);
  544. }
  545. $redirect_url = ['c' => 'user', 'a' => 'manage'];
  546. if (Minz_Request::isPost()) {
  547. $ok = true;
  548. if ($self_deletion) {
  549. // We check the password if it’s a self-destruction
  550. $nonce = Minz_Session::paramString('nonce');
  551. $challenge = Minz_Request::paramString('challenge');
  552. $ok &= FreshRSS_FormAuth::checkCredentials(
  553. $username, FreshRSS_Context::userConf()->passwordHash,
  554. $nonce, $challenge
  555. );
  556. } elseif (self::reauthRedirect()) {
  557. return;
  558. }
  559. if ($ok) {
  560. $ok &= self::deleteUser($username);
  561. }
  562. if ($ok && $self_deletion) {
  563. FreshRSS_Auth::removeAccess();
  564. $redirect_url = ['c' => 'index', 'a' => 'index'];
  565. }
  566. invalidateHttpCache();
  567. if ($ok) {
  568. Minz_Request::setGoodNotification(_t('feedback.user.deleted', $username));
  569. } else {
  570. Minz_Request::setBadNotification(_t('feedback.user.deleted.error', $username));
  571. }
  572. }
  573. Minz_Request::forward($redirect_url, true);
  574. }
  575. public function promoteAction(): void {
  576. $this->toggleAction('is_admin', true);
  577. }
  578. public function demoteAction(): void {
  579. $this->toggleAction('is_admin', false);
  580. }
  581. public function enableAction(): void {
  582. $this->toggleAction('enabled', true);
  583. }
  584. public function disableAction(): void {
  585. $this->toggleAction('enabled', false);
  586. }
  587. private function toggleAction(string $field, bool $value): void {
  588. if (!FreshRSS_Auth::hasAccess('admin')) {
  589. Minz_Error::error(403);
  590. }
  591. if (!Minz_Request::isPost()) {
  592. Minz_Error::error(403);
  593. }
  594. if (self::reauthRedirect()) {
  595. return;
  596. }
  597. $username = Minz_Request::paramString('username');
  598. if (!FreshRSS_UserDAO::exists($username)) {
  599. Minz_Error::error(404);
  600. }
  601. if (null === $userConfig = get_user_configuration($username)) {
  602. Minz_Error::error(500);
  603. return;
  604. }
  605. if ($field === '') {
  606. Minz_Error::error(400, 'Invalid field name');
  607. return;
  608. }
  609. $userConfig->_attribute($field, $value);
  610. $ok = $userConfig->save();
  611. FreshRSS_UserDAO::touch($username);
  612. if ($ok) {
  613. Minz_Request::good(_t('feedback.user.updated', $username), ['c' => 'user', 'a' => 'manage']);
  614. } else {
  615. Minz_Request::bad(
  616. _t('feedback.user.updated.error', $username),
  617. ['c' => 'user', 'a' => 'manage']
  618. );
  619. }
  620. }
  621. public function detailsAction(): void {
  622. if (!FreshRSS_Auth::hasAccess('admin')) {
  623. Minz_Error::error(403);
  624. }
  625. if (self::reauthRedirect()) {
  626. return;
  627. }
  628. $username = Minz_Request::paramString('username');
  629. if (!FreshRSS_UserDAO::exists($username)) {
  630. Minz_Error::error(404);
  631. }
  632. if (Minz_Request::paramBoolean('ajax')) {
  633. $this->view->_layout(null);
  634. }
  635. $this->view->username = $username;
  636. $this->view->details = $this->retrieveUserDetails($username);
  637. FreshRSS_View::prependTitle($username . ' · ' . _t('gen.menu.user_management') . ' · ');
  638. }
  639. /** @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} */
  640. private function retrieveUserDetails(string $username): array {
  641. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  642. $entryDAO = FreshRSS_Factory::createEntryDao($username);
  643. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  644. $userConfiguration = get_user_configuration($username);
  645. if ($userConfiguration === null) {
  646. throw new Exception('Error loading user configuration!');
  647. }
  648. return [
  649. 'feed_count' => $feedDAO->count(),
  650. 'article_count' => $entryDAO->count(),
  651. 'database_size' => $databaseDAO->size(),
  652. 'language' => $userConfiguration->language,
  653. 'mail_login' => $userConfiguration->mail_login,
  654. 'enabled' => $userConfiguration->enabled,
  655. 'is_admin' => $userConfiguration->is_admin,
  656. 'last_user_activity' => date('c', FreshRSS_UserDAO::mtime($username)) ?: '',
  657. 'is_default' => FreshRSS_Context::systemConf()->default_user === $username,
  658. ];
  659. }
  660. }