userController.php 23 KB

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