userController.php 11 KB

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