PHP Prevent Users from being deleted while logged in

I’m working on modifying my users list in one of my applications.

I have an Action column that is used for editing and deleting users. I’ve created a query where if an administrator is logged in, they cannot delete their own account.

However, I need to improve this functionality for other users where administrators cannot delete any user that is currently logged in whether they are an admin or an operator. I’ve read about using session_status() but I’m not sure how that works.

What is the best way to accomplish this?

My current code looks like this:

<?php if($_SESSION['id'] !== $row['id']) { ?>
	<a href="#" data-toggle="modal" data-target="#deleteModal_<?php echo $row['id'];?>">
                  <i style="color: #a40000;"class="fas fa-trash fa-sm fa-fw mr-2"></i>
        </a>
<?php } else { ?>

	<a data-toggle="tooltip" title="You cannot delete the active user!"><i style="color: #808080;"class="fas fa-lock fa-sm fa-fw mr-2"></i></a>

<?php } ?>

This doesn’t make sense. If an admin has cause to delete a user, what difference does it make if they are logged in or not?

My thinking is I don’t want someone to delete another person’s account while they are logged in using the system because they would get kicked off the system without warning or anything. The admin already can’t delete their own account. In my mind they shouldn’t be able to delete anyone’s account if they are logged into it (unless this really isn’t necessary).

Are you saying that your system somehow warns the user before they show up to their next unscheduled session with your site, at any faster rate than you would do so when the user tries to perform an action and is told their user no longer exists?

What if the user never logs off, or has the same schedule as your admin? Is your administrator just… stuck with a user they can never delete?

1 Like

So what happens is that when a user logs in, my code checks to see if the user’s account is active and if the password they entered matches the password in the database (which is provided when an account is created by an admin).

When an admin is logged into their own account, they cannot go in a delete their own account (as shown by the grey lock):

image

However, if the admin needs to delete another user account, they can without hassle:

image

But what if the user they are trying to delete is logged in to the system and actively working?

This is sensible.

This is also sensible

The the next action they take should log them out as they are no longer a valid user.

What’s the best way to add that functionality to the page?

<?php

include('nav/head.php');

if($role_id != '1') {
	header('Location: error.php');
	exit();
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>CABGOP | Users</title>

  <?php include('nav/header.php') ?>

          <!-- Page Heading -->
          <h1 class="h3 mb-2 text-gray-800">Users List</h1><br>
          <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> -->

          <!-- DataTables Example -->
          <div class="card shadow mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">Add, Edit or Remove User Accounts</h6>
            </div>
            <div class="card-body">
			<a class="btn btn-success" href="user_new.php"><i class="fa fa-user-plus"></i>&nbsp Add New User</a>
			<br><br>
              <div class="table-responsive">
                <table class="table table-bordered" id="userTable" width="100%" cellspacing="0">
                  <thead>
                    <tr>
                      <!--<th onclick="sortTable(0)">ID <i class="fas fa-sort"></i></th>-->
					  <th onclick="sortTable(1)">User Role <i class="fas fa-sort"></i></th>
                      <th>First Name</th>
                      <th>Last Name</th>
                      <th>Email Address</th>
                      <th>Username</th>
					  <th>Status</th>
					  <th>Action</th>
                    </tr>
                  </thead>
				  <?php

				  	$stmt = $pdo->prepare("SELECT id, role_id, first_name, last_name, email, username, status FROM users");
					$stmt->execute();
					while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

				  ?>
				  	<tr>
					<!--<td><?php print($row['id']); ?></td>-->
						<td>

						<?php

						if ($row['role_id'] === '1') {
							echo 'Administrator';
						} elseif ($row['role_id'] === '2') {
							echo 'Operator';
						}

						?>

						</td>
						<td><?php print($row['first_name']) ?></td>
						<td><?php print($row['last_name']) ?></td>
						<td><?php print($row['email']) ?></td>
						<td><?php print($row['username']) ?></td>
						<td>

						<?php

						if ($row['status'] === '1') {
							echo '<strong style="color: #009900;">Active</strong>';
						} elseif ($row['status'] === '0') {
							echo '<strong style="color: #a40000;">Inactive</strong>';
						}

						?>

						</td>
						<td>
							<a href="user_edit.php?edit_id=<?php print($row['id']); ?>"><i class="fa fa-user-edit"></i></a>
							<?php if($_SESSION['id'] !== $row['id']) { ?>
							<a href="#" data-toggle="modal" data-target="#deleteModal_<?php echo $row['id'];?>">
                  				<i style="color: #a40000;"class="fas fa-trash fa-sm fa-fw mr-2"></i>
                			</a>
							<?php } else { ?>

							<a data-toggle="tooltip" title="You cannot delete the active user!"><i style="color: #808080;"class="fas fa-lock fa-sm fa-fw mr-2"></i></a>

							<?php } ?>

							<!-- Delete Modal -->
							<div class="modal fade" id="deleteModal_<?php echo $row['id'];?>" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
							  <div class="modal-dialog" role="document">
							    <div class="modal-content">
							      <div class="modal-header">
							        <h5 class="modal-title" id="exampleModalLabel">Delete User</h5>
							        <button class="close" type="button" data-dismiss="modal" aria-label="Close">
							          <span aria-hidden="true">×</span>
							        </button>
							      </div>
							      <div class="modal-body">Are you sure you want to delete <?php print($row['first_name'] . ' ' . $row['last_name']);?> from the users list?</div>
							      <div class="modal-footer">
							        <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
									<form action="api/users/delete.php" method="post">
									<input type="submit" class="btn btn-danger" name="Delete_User[<?php echo $row['id'];?>]" value="Delete" />
									</form>
							      </div>
							    </div>
							  </div>
							</div>
						</td>
					</tr>
					<?php } ?>
                </table>
              </div>
            </div>
          </div>

        </div>
        <!-- /.container-fluid -->

      </div>
      <!-- End of Main Content -->
<script type="text/javascript" src="js/user_sort.js"></script>

	  <?php include('nav/footer.php'); ?>

</html>

<?php

if($_SESSION['id'] === $row['id']) {
	echo '<i class="fas fa-lock"></i>';
}

?>

Same way as when you logged them in. Check the DB for the active user_id. If it doesn’t exist, force a logout. A function would be appropriate here since you would call it on every page load.

So, do I add this to every page header to check if the user id exists?

Optimally you would have a single point of entry so it would only have to be in one place.

So then what does session_status() do?

https://www.php.net/manual/en/function.session-status.php

I would probably refine that slightly to ‘every page header in which a user-required database action is performed’, but yes.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.