I'm currently coding a blog to get experience with php in which I can log in. In the table:
user( id, username, password, permission)
there is one user that has the permission "admin", every other user has the permission "normal".
I want that only an admin can edit posts, so I need to find out what permission the currently logged in user has. I tried to do it with Sessions, but somehow I didn't manage to get it work.
This is the query in the UserRepository.php
in which I interact with the db
public function isAdmin($username)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("SELECT `permission` FROM `{$table}` WHERE username = :username");
$stmt->execute(['username' => $username]);
$stmt->setFetchMode(PDO::FETCH_CLASS, $model);
$isAdmin = $stmt->fetch(PDO::FETCH_CLASS);
return $isAdmin;
}
Here is the part of a function from the LoginService.php
in which I call the upper function in the repository:
public function attempt($username, $password)
{
$user = $this->userRepository->findByUsername($username);
if (password_verify($password, $user->password)) {
if ($this->userRepository->isAdmin($user->username) == "admin") {
$_SESSION['admin'] = "admin";
}
$_SESSION['login'] = $user->username;
session_regenerate_id(true);
return true;
}
This is a part of the __construct
in the PostsAdminController.php
in which I'm trying to get the value of the permission of the logged in user and save it into the session if it is "admin" and not "normal":
$username = $_SESSION['login'];
$permission = $this->userRepository->isAdmin($username);
if ($permission == "admin") {
$_SESSION['admin'] = $permission;
I also have a part of the header, because for admins there is a different navigation as for normal user.
<?php if(!empty ($_SESSION['login'])):?>
<div class="logged-in-user">
<div class="dropdown">
<button class="dropbtn">
<a href="http://localhost:8888/blog/public/index.php/dashboard">
<?php echo e($_SESSION['login']);?>
</a>
</button>
<div class="dropdown-content">
<?php if ($_SESSION['admin'] == "admin"): ?>
<a href="http://localhost:8888/blog/public/index.php/dashboard">
dashboard
</a>
This won't give me the dashboard for both, the admin and the normal user. But if I ask if it's set:
<?php if (isset($_SESSION['admin'])): ?>
Then it shows the dashboard in the dropdown-navigation for both again...
I don't know why it doesn't work, so how do I correctly find out the permission of the logged in user and show them different things based on their permission?