Log user in automatically if a request with HTTP auth is received

This commit is contained in:
Alex Cabal 2022-07-12 11:30:03 -05:00
parent 216e63f014
commit c457af896c
6 changed files with 25 additions and 10 deletions

View file

@ -28,3 +28,15 @@ if(SITE_STATUS == SITE_STATUS_LIVE){
}
$GLOBALS['User'] = Session::GetLoggedInUser();
if($GLOBALS['User'] === null){
$httpBasicAuthLogin = $_SERVER['PHP_AUTH_USER'] ?? null;
if($httpBasicAuthLogin !== null){
// If there's no logged in user, but a username was sent via HTTP basic auth,
// log them in while we're here.
$session = new Session();
$session->Create($httpBasicAuthLogin);
}
}

View file

@ -48,17 +48,18 @@ class Session extends PropertiesBase{
$this->Created = new DateTime();
Db::Query('INSERT into Sessions (UserId, SessionId, Created) values (?, ?, ?)', [$this->UserId, $this->SessionId, $this->Created]);
}
$this->SetSessionCookie($this->SessionId);
}
public static function GetLoggedInUser(): ?User{
$sessionId = HttpInput::Str(COOKIE, 'sessionid');
if($sessionId !== null){
$result = Db::Query('select u.* from Users u inner join Sessions s using (UserId) where s.SessionId = ?', [$sessionId], 'User');
$result = Db::Query('SELECT u.* from Users u inner join Sessions s using (UserId) where s.SessionId = ?', [$sessionId], 'User');
if(sizeof($result) > 0){
// Refresh the login cookie for another 2 weeks
setcookie('sessionid', $sessionId, time() + 60 * 60 * 24 * 14 * 1, '/', SITE_DOMAIN, true, false); // Expires in two weeks
self::SetSessionCookie($sessionId);
return $result[0];
}
}
@ -66,6 +67,10 @@ class Session extends PropertiesBase{
return null;
}
public static function SetSessionCookie($sessionId): void{
setcookie('sessionid', $sessionId, time() + 60 * 60 * 24 * 14 * 1, '/', SITE_DOMAIN, true, false); // Expires in two weeks
}
public static function Get(?string $sessionId): Session{
if($sessionId === null){
throw new Exceptions\InvalidSessionException();