97 lines
2.8 KiB
PHP
97 lines
2.8 KiB
PHP
<?php
|
|
|
|
class Auth {
|
|
private bool $isLoggedIn = false;
|
|
|
|
public static function checkLogin(): bool {
|
|
// Start SESSION hvis den ikke alt er startet.
|
|
if(!isset($_SESSION)){
|
|
session_start();
|
|
}
|
|
|
|
return isset($_SESSION['id'], $_SESSION['brukernavn'], $_SESSION['agent']) && $_SESSION['agent'] === md5($_SERVER['HTTP_USER_AGENT']);
|
|
}
|
|
|
|
|
|
public static function requireLogin(){
|
|
if(!self::checkLogin()){
|
|
header("Location: /modul7/login.php");
|
|
exit();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @throws LoginException
|
|
*/
|
|
public static function doLogin(string $brukernavn, string $passord){
|
|
if(empty($brukernavn) || empty($passord)){
|
|
throw new LoginException("Ugyldige input-felt"); // Vag beskrivelse da disse vil bli verifisert først av HTML5
|
|
}
|
|
|
|
try {
|
|
// Hent bruker fra database med passende epost
|
|
$bruker = Bruker::hentFraEpost($brukernavn);
|
|
|
|
if($bruker !== null && password_verify($passord, $bruker->passord)){
|
|
// valid login
|
|
echo "VALID";
|
|
|
|
// Start en session
|
|
session_start();
|
|
|
|
// Lagre id og epost i en SESSION-variabeler
|
|
$_SESSION['id'] = $bruker->dbid;
|
|
$_SESSION['brukernavn'] = $bruker->epost;
|
|
|
|
// Eksta sikkerhet. Hindrer at noen kan ta cookien fra noens nettleser og bruke i en annen nettleser. (versjon må matche 100% for å være gyldig)
|
|
$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
|
|
}
|
|
else {
|
|
throw new LoginException("Feil brukernavn og/eller passord. Prøv igjen eller kontakt administrator.");
|
|
}
|
|
}
|
|
catch (PDOException $e){
|
|
throw new LoginException("SQL-feil: ".$e);
|
|
}
|
|
}
|
|
}
|
|
|
|
class LoginException extends RuntimeException {
|
|
public function __construct($message = "", $code = 0, Throwable $previous = null){
|
|
parent::__construct($message, $code, $previous);
|
|
}
|
|
}
|
|
|
|
class Bruker {
|
|
public int $dbid;
|
|
public string $epost;
|
|
public string $passord;
|
|
|
|
public static function hentFraEpost(string $epost): ?Bruker{
|
|
$hentBrukerSQL = "SELECT * FROM Bruker WHERE epost = ?";
|
|
|
|
$db = getPdoConn(); // DATABASE-tilkobling
|
|
|
|
$stmt = $db->prepare($hentBrukerSQL);
|
|
$stmt->bindValue(1, $epost);
|
|
$stmt->execute();
|
|
|
|
$stmt->setFetchMode(PDO::FETCH_ASSOC);
|
|
|
|
if($stmt->rowCount() != 1){
|
|
return null;
|
|
}
|
|
|
|
foreach($stmt->fetchAll() as $row){
|
|
$bruker = new Bruker();
|
|
$bruker->dbid = $row['brukerId'];
|
|
$bruker->epost = $row['epost'];
|
|
$bruker->passord = $row['passord'];
|
|
|
|
return $bruker;
|
|
}
|
|
$db = null;
|
|
|
|
return null;
|
|
}
|
|
} |