This repository has been archived on 2023-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
web/app/lib/App/Core/User.php
2022-04-14 20:59:42 +00:00

108 lines
2.8 KiB
PHP

<?php
namespace App\Core;
use \Exception;
use \PDO;
/**
* Represents the current user session
*/
class User
{
private const SESSION_KEY = 'UserClass';
private Session $session;
private Database $database;
// always initialized
public bool $logged_in;
// initialized only if logged in
public string $username;
public string $password;
public int $power_level;
public function __construct(Session $session, Database $database)
{
$this->session = $session;
$this->database = $database;
$user = $this->session->get(self::SESSION_KEY);
// check if user session has been set
if (!$user)
{
$this->logged_in = FALSE;
return;
}
// check if username and password match
if (!$this->authenticate($user['username'], $user['password']))
{
$this->logged_in = FALSE;
$this->logout();
$this->session->flash('Kontodetaljer er blitt endret, vennligst logg inn igjen', 'warning');
return;
}
// all is good, we should be logged in now! (hopefully)
$this->logged_in = TRUE;
$this->username = $user['username'];
$this->password = $user['password'];
$this->power_level = $this->getPowerLevel();
}
/**
* Get current user power level
*/
private function getPowerLevel(): int
{
if (!$this->logged_in)
{
throw new Exception("Can't get power level without being logged in!");
}
$sth = $this->database->conn->prepare(
'SELECT Nivå FROM brukertabell WHERE Navn = ? AND Passord = ?'
);
$sth->execute([$this->username, $this->password]);
$row = $sth->fetch(PDO::FETCH_ASSOC);
return $row['Nivå'];
}
/**
* Set session if username and password match
*/
public function login(string $username, string $password): bool
{
if ($this->authenticate($username, $password))
{
$this->session->set(self::SESSION_KEY, [
'username' => $username,
'password' => $password
]);
return TRUE;
}
return FALSE;
}
/**
* Check if username and password match database
*/
private function authenticate(string $username, string $password): bool
{
$sth = $this->database->conn->prepare(
'SELECT * FROM brukertabell WHERE Navn = ? AND Passord = ?'
);
$sth->execute([$username, $password]);
if ($sth->rowCount())
{
return TRUE;
}
return FALSE;
}
public function logout(): void
{
$this->session->remove(self::SESSION_KEY);
}
}