Login Script with hidden buttons

In your menu file or w/e you put:

<? require 'auth.php' ?>
<ul>
    <li><a href="">Home</a></li>
    <li><a href="">Products</a></li>
    <? if( loggedin() ): ?><li><a href="">Secret area</a></li><? endif; ?>
</ul>

Then in pages that require auth just do this:

<?php 
    require 'auth.php';
    require_login();
?>

Where auth.php may contain:

<?php
    function loggedin(){
        return isset( $_SESSION['loggedin'] );
    }

    function require_login(){
        if( !loggedin() ){
            header( 'Location: /login.php?referrer='.$_SERVER['REQUEST_URI'] );
            exit;
        }
    }
?>

If you use javascript to hide the buttons, you open a security hole in the application. A malicious user could either disable javascript or apply some of their own to get around your security.

I suggest using PHP to chose to either render the buttons or not. I do this in .NET quite often.

You should be able to check the user's access on the server-side whenever they try to use a restricted button as well.


What we have done at my work is have a library the provides functions such as checking if the user is logged in. For example:

<?php
require_once 'Auth.php';
// output some html
if (isLoggedIn()) {
    echo 'html for logged in user';
}
// rest of html

For pages that only authenicated users should see, the controller checks if they are logged in and if not it redirects them to the login page.

<?php
public function viewCustomer($customerId) {
    if (!isLoggedIn())
        redirectToLoginPage();
}

Regarding security, you cannot trust what comes from the client:

  • The visitor can see all your code (HTML and Javascript, not PHP) and try stuff
  • The visitor may not even use a browser; it's trivially easy to send a request with a script

This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it.

If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.

Tags:

Javascript

Php