-/**
- * Log in user via Simple HTTP Auth.
- * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
- *
- * @param App $a App
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- * @hook 'authenticate'
- * array $addon_auth
- * 'username' => username from login form
- * 'password' => password from login form
- * 'authenticated' => return status,
- * 'user_record' => return authenticated user record
- */
-function api_login(App $a)
-{
- $_SESSION["allow_api"] = false;
-
- // workaround for HTTP-auth in CGI mode
- if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
- $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
- if (strlen($userpass)) {
- list($name, $password) = explode(':', $userpass);
- $_SERVER['PHP_AUTH_USER'] = $name;
- $_SERVER['PHP_AUTH_PW'] = $password;
- }
- }
-
- if (empty($_SERVER['PHP_AUTH_USER'])) {
- Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
- header('WWW-Authenticate: Basic realm="Friendica"');
- throw new UnauthorizedException("This API requires login");
- }
-
- $user = $_SERVER['PHP_AUTH_USER'] ?? '';
- $password = $_SERVER['PHP_AUTH_PW'] ?? '';
-
- // allow "user@server" login (but ignore 'server' part)
- $at = strstr($user, "@", true);
- if ($at) {
- $user = $at;
- }
-
- // next code from mod/auth.php. needs better solution
- $record = null;
-
- $addon_auth = [
- 'username' => trim($user),
- 'password' => trim($password),
- 'authenticated' => 0,
- 'user_record' => null,
- ];
-
- /*
- * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
- * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
- * and later addons should not interfere with an earlier one that succeeded.
- */
- Hook::callAll('authenticate', $addon_auth);
-
- if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
- $record = $addon_auth['user_record'];
- } else {
- $user_id = User::authenticate(trim($user), trim($password), true);
- if ($user_id !== false) {
- $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
- }
- }
-
- if (!DBA::isResult($record)) {
- Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
- header('WWW-Authenticate: Basic realm="Friendica"');
- //header('HTTP/1.0 401 Unauthorized');
- //die('This api requires login');
- throw new UnauthorizedException("This API requires login");
- }
-
- // Don't refresh the login date more often than twice a day to spare database writes
- $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
-
- DI::auth()->setForUser($a, $record, false, false, $login_refresh);
-
- $_SESSION["allow_api"] = true;
-
- Hook::callAll('logged_in', $a->user);
-}
-