Auth.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This class handles all authentication process.
  5. */
  6. class FreshRSS_Auth {
  7. /**
  8. * Determines if user is connected.
  9. */
  10. public const DEFAULT_COOKIE_DURATION = 7_776_000;
  11. private static bool $login_ok = false;
  12. /**
  13. * This method initializes authentication system.
  14. */
  15. public static function init(): bool {
  16. if (isset($_SESSION['REMOTE_USER']) && $_SESSION['REMOTE_USER'] !== FreshRSS_http_Util::httpAuthUser()) {
  17. //HTTP REMOTE_USER has changed
  18. self::removeAccess();
  19. Minz_Session::_param('csrf', false);
  20. }
  21. self::$login_ok = Minz_Session::paramBoolean('loginOk');
  22. $current_user = Minz_User::name();
  23. if ($current_user === null) {
  24. $current_user = FreshRSS_Context::systemConf()->default_user;
  25. Minz_Session::_params([
  26. Minz_User::CURRENT_USER => $current_user,
  27. ]);
  28. }
  29. if (self::$login_ok && self::giveAccess()) {
  30. return self::$login_ok;
  31. }
  32. if (self::accessControl()) {
  33. // Rotate the PHP session ID on the unauthenticated->authenticated transition.
  34. // Keep the old session (not authenticated) to not break concurrent in-flight requests.
  35. if (FreshRSS_Context::systemConf()->auth_type !== 'none') {
  36. try {
  37. Minz_Session::regenerateID('FreshRSS', delete_old_session: false);
  38. } catch (RuntimeException $e) {
  39. Minz_Log::error('Session could not be regenerated during access restoration: ' . $e->getMessage());
  40. }
  41. }
  42. if (self::giveAccess()) {
  43. FreshRSS_UserDAO::touch();
  44. return self::$login_ok;
  45. }
  46. }
  47. // Be sure all accesses are removed!
  48. self::removeAccess();
  49. return false;
  50. }
  51. /**
  52. * This method checks if user is allowed to connect.
  53. *
  54. * Required session parameters are also set in this method (such as
  55. * currentUser).
  56. *
  57. * @return bool true if user can be connected, false otherwise.
  58. */
  59. private static function accessControl(): bool {
  60. $auth_type = FreshRSS_Context::systemConf()->auth_type;
  61. switch ($auth_type) {
  62. case 'form':
  63. $credentials = FreshRSS_FormAuth::getCredentialsFromCookie();
  64. $current_user = '';
  65. if (isset($credentials[1])) {
  66. $current_user = trim($credentials[0]);
  67. Minz_Session::_params([
  68. Minz_User::CURRENT_USER => $current_user,
  69. 'passwordHash' => trim($credentials[1]),
  70. 'csrf' => false,
  71. ]);
  72. }
  73. return $current_user != '';
  74. case 'http_auth':
  75. $current_user = FreshRSS_http_Util::httpAuthUser();
  76. if ($current_user == '') {
  77. return false;
  78. }
  79. $login_ok = FreshRSS_UserDAO::exists($current_user);
  80. if (!$login_ok && FreshRSS_Context::systemConf()->http_auth_auto_register) {
  81. $email = null;
  82. if (FreshRSS_Context::systemConf()->http_auth_auto_register_email_field !== '' &&
  83. is_string($_SERVER[FreshRSS_Context::systemConf()->http_auth_auto_register_email_field] ?? null)) {
  84. $email = $_SERVER[FreshRSS_Context::systemConf()->http_auth_auto_register_email_field];
  85. }
  86. $language = Minz_Translate::getLanguage(null, Minz_Request::getPreferredLanguages(), FreshRSS_Context::systemConf()->language);
  87. Minz_Translate::init($language);
  88. $login_ok = FreshRSS_user_Controller::createUser($current_user, $email, '', [
  89. 'language' => $language,
  90. ]);
  91. }
  92. if ($login_ok) {
  93. Minz_Session::_params([
  94. Minz_User::CURRENT_USER => $current_user,
  95. 'csrf' => false,
  96. ]);
  97. }
  98. return $login_ok;
  99. case 'none':
  100. return true;
  101. default:
  102. // TODO load extension
  103. return false;
  104. }
  105. }
  106. /**
  107. * Gives access to the current user.
  108. */
  109. public static function giveAccess(): bool {
  110. FreshRSS_Context::initUser();
  111. if (!FreshRSS_Context::hasUserConf() || !FreshRSS_Context::userConf()->enabled) {
  112. self::$login_ok = false;
  113. Minz_Session::_param('loginOk', false);
  114. return false;
  115. }
  116. switch (FreshRSS_Context::systemConf()->auth_type) {
  117. case 'form':
  118. self::$login_ok = Minz_Session::paramString('passwordHash') === FreshRSS_Context::userConf()->passwordHash;
  119. break;
  120. case 'http_auth':
  121. $current_user = Minz_User::name() ?? '';
  122. self::$login_ok = strcasecmp($current_user, FreshRSS_http_Util::httpAuthUser()) === 0;
  123. break;
  124. case 'none':
  125. self::$login_ok = true;
  126. break;
  127. default:
  128. // TODO: extensions
  129. self::$login_ok = false;
  130. }
  131. Minz_Session::_params([
  132. 'loginOk' => self::$login_ok,
  133. 'REMOTE_USER' => FreshRSS_http_Util::httpAuthUser(),
  134. ]);
  135. return self::$login_ok;
  136. }
  137. /**
  138. * Returns if current user has access to the given scope.
  139. *
  140. * @param string $scope general (default) or admin
  141. * @return bool true if user has corresponding access, false else.
  142. */
  143. public static function hasAccess(string $scope = 'general'): bool {
  144. if (!FreshRSS_Context::hasUserConf()) {
  145. return false;
  146. }
  147. $currentUser = Minz_User::name();
  148. $isAdmin = FreshRSS_Context::userConf()->is_admin;
  149. $default_user = FreshRSS_Context::systemConf()->default_user;
  150. $ok = self::$login_ok;
  151. switch ($scope) {
  152. case 'general':
  153. break;
  154. case 'admin':
  155. $ok &= $default_user === $currentUser || $isAdmin;
  156. break;
  157. default:
  158. $ok = false;
  159. }
  160. return (bool)$ok;
  161. }
  162. /**
  163. * Removes all accesses for the current user.
  164. */
  165. public static function removeAccess(): void {
  166. self::$login_ok = false;
  167. Minz_Session::_params([
  168. 'loginOk' => false,
  169. 'lastReauth' => false,
  170. // 'csrf' => false, // Must be refreshed separately
  171. 'REMOTE_USER' => false,
  172. ]);
  173. $username = Minz_Request::paramString('user');
  174. if (!Minz_Request::tokenIsOk()) {
  175. $username = FreshRSS_Context::systemConf()->default_user;
  176. }
  177. Minz_User::change($username);
  178. switch (FreshRSS_Context::systemConf()->auth_type) {
  179. case 'form':
  180. Minz_Session::_param('passwordHash');
  181. FreshRSS_FormAuth::deleteCookie();
  182. break;
  183. case 'http_auth':
  184. case 'none':
  185. // Nothing to do…
  186. break;
  187. default:
  188. // TODO: extensions
  189. }
  190. }
  191. /**
  192. * Return if authentication is enabled on this instance of FRSS.
  193. */
  194. public static function accessNeedsLogin(): bool {
  195. return FreshRSS_Context::systemConf()->auth_type !== 'none';
  196. }
  197. /**
  198. * Return if authentication requires a PHP action.
  199. */
  200. public static function accessNeedsAction(): bool {
  201. return FreshRSS_Context::systemConf()->auth_type === 'form';
  202. }
  203. public static function csrfToken(): string {
  204. $csrf = Minz_Session::paramString('csrf');
  205. if ($csrf == '') {
  206. $csrf = hash('sha256', FreshRSS_Context::systemConf()->salt . random_bytes(32));
  207. Minz_Session::_param('csrf', $csrf);
  208. }
  209. return $csrf;
  210. }
  211. public static function isCsrfOk(?string $token = null): bool {
  212. $csrf = Minz_Session::paramString('csrf');
  213. if ($token === null) {
  214. $token = is_string($_POST['_csrf'] ?? null) ? $_POST['_csrf'] : '';
  215. }
  216. return $token != '' && hash_equals($csrf, $token);
  217. }
  218. public static function needsReauth(): bool {
  219. $auth_type = FreshRSS_Context::systemConf()->auth_type;
  220. $reauth_required = FreshRSS_Context::systemConf()->reauth_required;
  221. $reauth_time = FreshRSS_Context::systemConf()->reauth_time;
  222. if (!$reauth_required) {
  223. return false;
  224. }
  225. $last_reauth = Minz_Session::paramInt('lastReauth');
  226. if ($auth_type !== 'none' && time() - $last_reauth > $reauth_time) {
  227. if ($auth_type === 'http_auth') {
  228. // TODO: not implemented - just let the user through
  229. return false;
  230. }
  231. return true;
  232. }
  233. return false;
  234. }
  235. /**
  236. * Return if user needs reauth and got redirected to login page.
  237. *
  238. * @param array{c?: string, a?: string, params?: array<string, mixed>}|null $redirect
  239. */
  240. public static function requestReauth(?array $redirect = null): bool {
  241. if (self::needsReauth()) {
  242. if (Minz_Request::paramBoolean('ajax')) {
  243. // Send 403 and exit instead of redirect with Minz_Error::error()
  244. header('HTTP/1.1 403 Forbidden');
  245. exit();
  246. }
  247. $redirect = Minz_Url::serialize($redirect ?? Minz_Request::currentRequest());
  248. Minz_Request::forward([
  249. 'c' => 'auth',
  250. 'a' => 'reauth',
  251. 'params' => [
  252. 'r' => $redirect,
  253. ],
  254. ], true);
  255. return true;
  256. }
  257. return false;
  258. }
  259. public static function allowAnonymous(): bool {
  260. $defaultUser = FreshRSS_Context::systemConf()->default_user;
  261. $requestedUser = Minz_Request::paramString('user');
  262. return FreshRSS_Context::systemConf()->allow_anonymous &&
  263. Minz_User::name() === $defaultUser &&
  264. ($requestedUser === '' || $requestedUser === $defaultUser);
  265. }
  266. public static function allowAnonymousRefresh(): bool {
  267. return FreshRSS_Context::systemConf()->allow_anonymous_refresh;
  268. }
  269. }