-1

I'm trying to design a basic website for use internally...

In the database I have a user table and that table consists of "id, username, password, email, admin" The value of admin can be either 0 or 1

I want to validate whether the logged in user is an admin and then choose what to display to them based on that result.

I have tried quite a few different suggestions from multiple sites including here... The most recent code I've tried using was

if (!isset($_SESSION['id']) || !in_array($_SESSION['id'], array('1'))) {

I will post the full code below and explain what I was hoping to achieve as the outcome

<?php
session_start();
// check to see if the user is logged in
if ($_SESSION['loggedin']){
// user is logged in
  ?><div id="container"><?php
    echo 'Welcome ' . $_SESSION['name'] . '!' . '|' . '<a href="logout.php">logout?</a></div>';

?>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<img src="images/logo.gif" class="bg">
<?php if (!isset($_SESSION['admin']) || !in_array($_SESSION['admin'], array('1'))) {
?>
<div id="container">
<div id="box">
  <h2>: Add User :</h2>
<p>
  <form action="action_adduser.php" method="post">
Username:  <input type="username" id="newuser" name="username"> <br />
Password:  <input type="password" id="newpassword" name="password"><br />
Email:  <input type="email" id="email" name="email"><br />
  <input type="submit" value="Add!">
  </form>
</p>
</div>
</div>



<?php
}
}elseif ($_SESSION['loggedin']) {
  # User is Logged in without any special permissions.
}else{
    // user is not logged in, send the user to the login page
    header('Location: login.php');
}
?>

I expected to (ONCE LOGGED IN) see a form to add a new user to the database if my account had the admin column set to '1'. Otherwise I expected to not see the add user form or be able to add a new user.

I can confirm when echoing out $_SESSION['admin'] it does echo out whatever that field is set to i,e 1 or 0 so the code is wrong in the validation part I'm guessing?

I wanted to do it at the start where it checks if the $_SESSION['logged_in'] is set by maybe doing something like && $_SESSION['admin'] but I don't know how to actually verify if its 1 or 0 as apposed to the code then just checking if its set at all?

Hope this makes sense and appreciate any help towards my question :)

Auth.php

    <?php
session_start();
// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = 'withheld';
$DB_NAME = 'withheld';
// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $con->prepare('SELECT id, password, admin FROM accounts WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();
    $stmt->store_result();
    // Store the result so we can check if the account exists in the database.
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password, $admin);
        $stmt->fetch();
        // Account exists, now we verify the password.
        if (password_verify($_POST['password'], $password)) {
            // Verification success! User has loggedin!
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['admin'] = $admin;
            $_SESSION['id'] = $id;
            echo 'Welcome ' . $_SESSION['name'] . '!';
            header('Location: index.php');
        } else {
            echo 'Incorrect username and/or password!';
        }
    } else {
        echo 'Incorrect username and/or password!';
    }
    $stmt->close();
} else {
    echo 'Could not prepare statement!';
}
?>
Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
Brad Andrews
  • 94
  • 1
  • 1
  • 11
  • Add `login.php`'s code and (if not there) the part where you create and populate the session. – Gabriel Dec 30 '18 at 20:45
  • Thanks @rpm192 the code you gave did not work unfortunately but I appreciate the suggestion! – Brad Andrews Dec 30 '18 at 20:48
  • @Gabriel I can post login.php's code if necessary sure! I've made sure that the admin variable is set and readable but I will post the login script also for you! :) – Brad Andrews Dec 30 '18 at 20:49
  • 1
    It looks fine. Replacing `if (!isset($_SESSION['admin']) || !in_array($_SESSION['admin'], array('1')))` with `if($_SESSION['admin']=='1')` should be enough. Although the "User is Logged in without any special permissions" part is not right, look closely, the `elseif` is for the first `if`. – Gabriel Dec 30 '18 at 20:56
  • 1
    have you tried `
    ` to check the value `$_SESSION['admin']` contains?
    – Dut A. Dec 30 '18 at 21:12
  • I'd start by first enabling error reporting http://php.net/manual/en/function.error-reporting.php. You will see what you'll get back and remove the line of code that prevents you from redirecting. Once that's done, check for errors on the query. If that fails silently, then your password column could be the issue, as far as length go. – Funk Forty Niner Dec 30 '18 at 21:13

1 Answers1

0

You are complicating things a lot, make it sample :

You have two (even more) options :

  1. Keep using the session admin, then you just need to :

    if ($_SESSION['admin'] == 1) { ... // You don't need to check if the session exist, because you set it anyway

  2. Check the admin value on each page load using the $_SESSION['id'], I would recommend this because using many different sessions is not a good idea.

Soren
  • 268
  • 5
  • 13
  • Thanks for your answer! I'm a bit confused as I have tried the if ($_SESSION['admin'] == 1) { ... // code but this did not work And for your suggestion 2 I don't really understand how to implement.. The $_SESSION['id'] is for the id column not the admin column no? Thanks! – Brad Andrews Dec 30 '18 at 21:39
  • 1
    Okay, forget the second point and stay on what you understand, in your code replace : if (!isset($_SESSION['admin']) || !in_array($_SESSION['admin'], array('1'))) with : if ($_SESSION['admin'] == 1), that should work :) – Soren Dec 30 '18 at 21:42
  • Thank you! It turns out it was working all along! I was refreshing the page after changing the admin value in the database but I needed to logout and log back in to be able to see changes as it's only recording the admin value thats set in the db once upon login and saving its value as a session variable! – Brad Andrews Dec 31 '18 at 12:57
  • I don't suppose there is a way of having it auto-update if that value changes? I will mark your answer as the solution but leave some time for you to respond as I'm not sure if they lock the ability to respond after an answer is chosen? Thank's again for your help! :) – Brad Andrews Dec 31 '18 at 12:58
  • That's true, because you create your session while your login script is running, you cannot change it just by refreshing the page, and happy to help and hear your problem solved :) @BradAndrews – Soren Dec 31 '18 at 14:17
  • @BradAndrews, write what you found as a solution to your problem here as an answer so this doesn't hang around as unanswered. – Dut A. Dec 31 '18 at 19:40