userController.php 11 KB

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