userController.php 23 KB

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