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-15 12:29:40 +01:00

78 lines
2.2 KiB
PHP

<?php
// TODO: this shit stinks...
class User
{
private Session $session;
private Database $database;
public ?bool $loggedIn;
public ?string $username;
public ?string $password;
public ?int $powerLevel;
public function __construct(Session $session, Database $database)
{
$this->session = $session;
$this->database = $database;
$this->setProps();
}
private function setProps(): void
{
$this->loggedIn = $this->session->get('loggedIn');
$this->username = $this->session->get('username');
$this->password = $this->session->get('password');
if ($this->loggedIn && !$this->authenticate($this->username, $this->password))
{
$this->logout();
$this->session->flash('Kontodetaljer endret, vennligst logg inn igjen', 'warning');
}
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('loggedIn', TRUE);
$this->session->set('username', $username);
$this->session->set('password', $password);
$this->setProps();
return TRUE;
}
return FALSE;
}
// Check if user and pass match
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('loggedIn');
$this->session->remove('username');
$this->session->remove('password');
$this->setProps();
}
}