Auth.php 8.1 KB

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