Nofu/app/login/Login.php
2024-06-14 17:20:01 +02:00

93 lines
2.4 KiB
PHP

<?php
namespace Login;
use Symfony\Component\Yaml\Yaml;
class Login {
private $listUser;
/**
* Construct a new instance of the class.
*
* Initialize the listUser property as an empty array and call the loadUser method.
*/
function __construct() {
$this->listUser = [];
$this->loadUsers();
}
/**
* Add a new user to the list of users.
*
* @param string $login The login name of the new user.
* @param string $password The password of the new user.
* @param string $role The role of the new user.
*
* @return bool True if the user was successfully added, false otherwise.
*/
public function addUser(string $login, string $password, string $role): bool {
if ($this->listUser[$login]) {
return false;
}
$newUser = [$login => ['password' => password_hash($password, PASSWORD_DEFAULT), 'role' => $role]];
$listUser = array_merge($newUser, $this->listUser);
$yaml = Yaml::dump($listUser);
return file_put_contents('../data/users.yaml', $yaml);
}
/**
* Load the users from the YAML file.
*
* @return void
*/
private function loadUsers() {
if (file_exists('../data/users.yaml')) {
$listUser = Yaml::parseFile('../data/users.yaml');
if (!empty($listUser)) {
$this->listUser = $listUser;
}
}
}
/**
* Log in a user with the given credentials.
*
* @param string $user The username.
* @param string $password The password.
*
* @return bool True if the user is logged in successfully, false otherwise.
*/
public function logIn(string $user, string $password): bool {
if ($this->listUser[$user] && password_verify($password, $this->listUser[$user]['password'])) {
$_SESSION['isLogged'] = true;
return true;
}
return false;
}
/**
* Log out the user and redirect to the index page.
*
* @return void
*/
static function logOut(): void {
session_destroy();
header("Location: index.php");
}
/**
* Check if the user is logged in.
*
* @return bool True if the user is logged in, false otherwise.
*/
static function isLogged(): bool {
if (isset($_SESSION['isLogged']) && $_SESSION['isLogged'] === true) {
return true;
}
return false;
}
}