MrD
MrD

Reputation: 5086

Protecting webpage via authentication

I am developing a portal with PHP, and would need to implement a simple PHP authentication system which restricts access to certain pages depending on the credentials of the user.

I have a function CheckAuth() which takes a paramater (Integer). Ie, my database has five authorization levels 1-5. If I call CheckAuth(3) this will return true if the user has authorization level 3 or above. My code right now reads:

if(!CheckAuth(3) {
    die("Sorry, we were unable to deliver the requested content.");
}

The problem with this solution is that it will break the page's layout as other elements such as the page's footer will not be displayed.

What is the best way of conditionally displaying only a portion of the page?

Thanks in advance! Dario

function CheckAuth() {

require("config.php");

//User ain't been logged in?    
if(!isset($_SESSION["login"])) {

    return 0;
}

//Alright user is logged in, lets check the level...
//1 = User, 2 = OP (or Admin)

$query = "SELECT * FROM delegations WHERE id=" . $_SESSION["login"];
$results = mysqli_query($con, $query);

while($row = mysqli_fetch_array($results)) {

        return $row["Level"];

}
}

Upvotes: 0

Views: 56

Answers (2)

Sebastian Kraft
Sebastian Kraft

Reputation: 119

You shouldnt ask for if (!CheckAuth(3)) you should better go the way of if (CheckAuth(3)) and display the Page data if the user has the permission to view the content, if not redirect him to a 403 page something like this

    if(CheckAuth(3))
    {
       //display page content
    }

    function CheckAuth($permissionLevel)
    {
    require("config.php");

    //User ain't been logged in?    
    if(!isset($_SESSION["login"])) {

      return 0;
    }

    //Alright user is logged in, lets check the level...
    //1 = User, 2 = OP (or Admin)

    $query = "SELECT * FROM delegations WHERE id=" . $_SESSION["login"];
    $results = mysqli_query($con, $query);

    while($row = mysqli_fetch_array($results)) {

      if($row["Level"] == $permissionLevel)
      {
        return true;
      }

    }
    header("Status: 403 Forbidden");
    header("Location: /403.html");
    exit;
  }

Upvotes: 0

JimiDini
JimiDini

Reputation: 2069

Solution is not to use die() but to render another version of page.

if (!CheckAuth(3)) {
    // render error page
} else {
    // render normal page
}

Upvotes: 1

Related Questions