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/core/User.php
2022-02-23 16:45:12 +01:00

86 lines
2.4 KiB
PHP

<?php
// TODO:
class User
{
private Session $session;
private Database $database;
public bool $loggedIn;
public int $powerLevel; // Set to 0 when not logged in
public string $username; // Username and password is only initalized if logged in
public string $password;
public function __construct(Session $session, Database $database)
{
$this->session = $session;
$this->database = $database;
$user = $this->session->get('user');
if ($user)
{
// User session was set previously
$this->loggedIn = $user['loggedIn'];
$this->username = $user['username'];
$this->password = $user['password'];
} else {
// User session has not been set yet
$this->loggedIn = FALSE;
}
// Check if username and password matches
if ($this->loggedIn && !$this->authenticate($this->username, $this->password))
{
$this->logout();
$this->session->flash('Kontodetaljer endret, vennligst logg inn igjen', 'warning');
}
// Set powerLevel
if ($this->loggedIn)
{
$sth = $this->database->conn->prepare(
'SELECT * FROM brukertabell WHERE Navn = ? AND Passord = ?'
);
$sth->execute([$this->username, $this->password]);
$row = $sth->fetch(PDO::FETCH_ASSOC);
$this->powerLevel = $row['Nivå'];
} else {
$this->powerLevel = 0;
}
}
// Set session if user and password match
public function login(string $username, string $password): bool
{
if ($this->authenticate($username, $password))
{
$this->session->set('user', [
'loggedIn' => TRUE,
'username' => $username,
'password' => $password
]);
return TRUE;
}
return FALSE;
}
// Check if user 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('user');
}
}