userController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * Controller to handle user actions.
  4. */
  5. class FreshRSS_user_Controller extends Minz_ActionController {
  6. // Will also have to be computed client side on mobile devices,
  7. // so do not use a too high cost
  8. const BCRYPT_COST = 9;
  9. public static function hashPassword($passwordPlain) {
  10. $passwordHash = password_hash($passwordPlain, PASSWORD_BCRYPT, array('cost' => self::BCRYPT_COST));
  11. $passwordPlain = '';
  12. $passwordHash = preg_replace('/^\$2[xy]\$/', '\$2a\$', $passwordHash); //Compatibility with bcrypt.js
  13. return $passwordHash == '' ? '' : $passwordHash;
  14. }
  15. /**
  16. * The username is also used as folder name, file name, and part of SQL table name.
  17. * '_' is a reserved internal username.
  18. */
  19. const USERNAME_PATTERN = '([0-9a-zA-Z_][0-9a-zA-Z_.@-]{1,38}|[0-9a-zA-Z])';
  20. public static function checkUsername($username) {
  21. return preg_match('/^' . self::USERNAME_PATTERN . '$/', $username) === 1;
  22. }
  23. public static function deleteFeverKey($username) {
  24. $userConfig = get_user_configuration($username);
  25. if ($userConfig !== null && ctype_xdigit($userConfig->feverKey)) {
  26. return @unlink(DATA_PATH . '/fever/.key-' . sha1(FreshRSS_Context::$system_conf->salt) . '-' . $userConfig->feverKey . '.txt');
  27. }
  28. return false;
  29. }
  30. public static function updateUser($user, $passwordPlain, $apiPasswordPlain, $userConfigUpdated = array()) {
  31. $userConfig = get_user_configuration($user);
  32. if ($userConfig === null) {
  33. return false;
  34. }
  35. if ($passwordPlain != '') {
  36. $passwordHash = self::hashPassword($passwordPlain);
  37. $userConfig->passwordHash = $passwordHash;
  38. }
  39. if ($apiPasswordPlain != '') {
  40. $apiPasswordHash = self::hashPassword($apiPasswordPlain);
  41. $userConfig->apiPasswordHash = $apiPasswordHash;
  42. @mkdir(DATA_PATH . '/fever/', 0770, true);
  43. self::deleteFeverKey($user);
  44. $userConfig->feverKey = strtolower(md5($user . ':' . $apiPasswordPlain));
  45. $ok = file_put_contents(DATA_PATH . '/fever/.key-' . sha1(FreshRSS_Context::$system_conf->salt) . '-' . $userConfig->feverKey . '.txt', $user) !== false;
  46. if (!$ok) {
  47. Minz_Log::warning('Could not save API credentials for fever API', ADMIN_LOG);
  48. return $ok;
  49. }
  50. }
  51. if (is_array($userConfigUpdated)) {
  52. foreach ($userConfigUpdated as $configName => $configValue) {
  53. if ($configValue !== null) {
  54. $userConfig->_param($configName, $configValue);
  55. }
  56. }
  57. }
  58. $ok = $userConfig->save();
  59. return $ok;
  60. }
  61. public function updateAction() {
  62. if (!FreshRSS_Auth::hasAccess('admin')) {
  63. Minz_Error::error(403);
  64. }
  65. if (Minz_Request::isPost()) {
  66. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  67. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  68. $_POST['newPasswordPlain'] = '';
  69. $apiPasswordPlain = Minz_Request::param('apiPasswordPlain', '', true);
  70. $username = Minz_Request::param('username');
  71. $ok = self::updateUser($username, $passwordPlain, $apiPasswordPlain, array(
  72. 'token' => Minz_Request::param('token', null),
  73. ));
  74. if ($ok) {
  75. $isSelfUpdate = Minz_Session::param('currentUser', '_') === $username;
  76. if ($passwordPlain == '' || !$isSelfUpdate) {
  77. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  78. } else {
  79. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  80. }
  81. } else {
  82. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  83. array('c' => 'user', 'a' => 'manage'));
  84. }
  85. }
  86. }
  87. /**
  88. * This action displays the user profile page.
  89. */
  90. public function profileAction() {
  91. if (!FreshRSS_Auth::hasAccess()) {
  92. Minz_Error::error(403);
  93. }
  94. Minz_View::prependTitle(_t('conf.profile.title') . ' · ');
  95. Minz_View::appendScript(Minz_Url::display('/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js')));
  96. if (Minz_Request::isPost()) {
  97. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  98. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  99. $_POST['newPasswordPlain'] = '';
  100. $apiPasswordPlain = Minz_Request::param('apiPasswordPlain', '', true);
  101. $ok = self::updateUser(Minz_Session::param('currentUser'), $passwordPlain, $apiPasswordPlain, array(
  102. 'token' => Minz_Request::param('token', null),
  103. ));
  104. Minz_Session::_param('passwordHash', FreshRSS_Context::$user_conf->passwordHash);
  105. if ($ok) {
  106. if ($passwordPlain == '') {
  107. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'profile'));
  108. } else {
  109. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  110. }
  111. } else {
  112. Minz_Request::bad(_t('feedback.profile.error'),
  113. array('c' => 'user', 'a' => 'profile'));
  114. }
  115. }
  116. }
  117. /**
  118. * This action displays the user management page.
  119. */
  120. public function manageAction() {
  121. if (!FreshRSS_Auth::hasAccess('admin')) {
  122. Minz_Error::error(403);
  123. }
  124. Minz_View::prependTitle(_t('admin.user.title') . ' · ');
  125. $this->view->current_user = Minz_Request::param('u');
  126. $this->view->nb_articles = 0;
  127. $this->view->size_user = 0;
  128. if ($this->view->current_user) {
  129. // Get information about the current user.
  130. $entryDAO = FreshRSS_Factory::createEntryDao($this->view->current_user);
  131. $this->view->nb_articles = $entryDAO->count();
  132. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($this->view->current_user);
  133. $this->view->size_user = $databaseDAO->size();
  134. }
  135. }
  136. public static function createUser($new_user_name, $passwordPlain, $apiPasswordPlain, $userConfig = array(), $insertDefaultFeeds = true) {
  137. if (!is_array($userConfig)) {
  138. $userConfig = array();
  139. }
  140. $ok = self::checkUsername($new_user_name);
  141. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  142. if ($ok) {
  143. $languages = Minz_Translate::availableLanguages();
  144. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages)) {
  145. $userConfig['language'] = 'en';
  146. }
  147. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive
  148. $configPath = join_path($homeDir, 'config.php');
  149. $ok &= !file_exists($configPath);
  150. }
  151. if ($ok) {
  152. if (!is_dir($homeDir)) {
  153. mkdir($homeDir);
  154. }
  155. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  156. }
  157. if ($ok) {
  158. $userDAO = new FreshRSS_UserDAO();
  159. $ok &= $userDAO->createUser($new_user_name, $userConfig['language'], $insertDefaultFeeds);
  160. $ok &= self::updateUser($new_user_name, $passwordPlain, $apiPasswordPlain);
  161. }
  162. return $ok;
  163. }
  164. /**
  165. * This action creates a new user.
  166. *
  167. * Request parameters are:
  168. * - new_user_language
  169. * - new_user_name
  170. * - new_user_passwordPlain
  171. * - r (i.e. a redirection url, optional)
  172. *
  173. * @todo clean up this method. Idea: write a method to init a user with basic information.
  174. * @todo handle r redirection in Minz_Request::forward directly?
  175. */
  176. public function createAction() {
  177. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  178. Minz_Error::error(403);
  179. }
  180. if (Minz_Request::isPost()) {
  181. $new_user_name = Minz_Request::param('new_user_name');
  182. $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
  183. $new_user_language = Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language);
  184. $ok = self::createUser($new_user_name, $passwordPlain, '', array('language' => $new_user_language));
  185. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  186. $_POST['new_user_passwordPlain'] = '';
  187. invalidateHttpCache();
  188. // If the user has admin access, it means he's already logged in
  189. // and we don't want to login with the new account. Otherwise, the
  190. // user just created its account himself so he probably wants to
  191. // get started immediately.
  192. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  193. $user_conf = get_user_configuration($new_user_name);
  194. Minz_Session::_param('currentUser', $new_user_name);
  195. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  196. Minz_Session::_param('csrf');
  197. FreshRSS_Auth::giveAccess();
  198. }
  199. $notif = array(
  200. 'type' => $ok ? 'good' : 'bad',
  201. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  202. );
  203. Minz_Session::_param('notification', $notif);
  204. }
  205. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  206. if (!$redirect_url) {
  207. $redirect_url = array('c' => 'user', 'a' => 'manage');
  208. }
  209. Minz_Request::forward($redirect_url, true);
  210. }
  211. public static function deleteUser($username) {
  212. $db = FreshRSS_Context::$system_conf->db;
  213. require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php');
  214. $ok = self::checkUsername($username);
  215. if ($ok) {
  216. $default_user = FreshRSS_Context::$system_conf->default_user;
  217. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  218. }
  219. $user_data = join_path(DATA_PATH, 'users', $username);
  220. $ok &= is_dir($user_data);
  221. if ($ok) {
  222. self::deleteFeverKey($username);
  223. $userDAO = new FreshRSS_UserDAO();
  224. $ok &= $userDAO->deleteUser($username);
  225. $ok &= recursive_unlink($user_data);
  226. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  227. }
  228. return $ok;
  229. }
  230. /**
  231. * This action delete an existing user.
  232. *
  233. * Request parameter is:
  234. * - username
  235. *
  236. * @todo clean up this method. Idea: create a User->clean() method.
  237. */
  238. public function deleteAction() {
  239. $username = Minz_Request::param('username');
  240. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  241. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  242. Minz_Error::error(403);
  243. }
  244. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  245. if (!$redirect_url) {
  246. $redirect_url = array('c' => 'user', 'a' => 'manage');
  247. }
  248. if (Minz_Request::isPost()) {
  249. $ok = true;
  250. if ($ok && $self_deletion) {
  251. // We check the password if it's a self-destruction
  252. $nonce = Minz_Session::param('nonce');
  253. $challenge = Minz_Request::param('challenge', '');
  254. $ok &= FreshRSS_FormAuth::checkCredentials(
  255. $username, FreshRSS_Context::$user_conf->passwordHash,
  256. $nonce, $challenge
  257. );
  258. }
  259. if ($ok) {
  260. $ok &= self::deleteUser($username);
  261. }
  262. if ($ok && $self_deletion) {
  263. FreshRSS_Auth::removeAccess();
  264. $redirect_url = array('c' => 'index', 'a' => 'index');
  265. }
  266. invalidateHttpCache();
  267. $notif = array(
  268. 'type' => $ok ? 'good' : 'bad',
  269. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  270. );
  271. Minz_Session::_param('notification', $notif);
  272. }
  273. Minz_Request::forward($redirect_url, true);
  274. }
  275. }