PHP/MySQL Authentication Scheme





-8
Date Submitted Tue. Nov. 7th, 2006 11:06 AM
Revision 1 of 1
Helper kahotep
Tags mysql | PHP
Comments 6 comments
This class is a simple authentication scheme which makes it easy to add authentication to any page by including one class and adding one table to your MySQL database.

The following functions are employed by this authentication class:

auth()
this is the default constructor; it automatically checks for the POST vars "username" and "password", it also checks to see if the user passed the GET variable "logout", which would prompt it to set the authentication status to un-authenticated.

is_authorized()
Checks the SESSION variable "authorized" and returns true or false depending on that variable.

mysql_bind()
This is automatically called by the constructor each time the class is instantiated and $_POST['username'] and $_POST['password'] are present. It queries the db for a valid username and MD5 encoded password.

user_create($username,$email,$password)
Creates a user, if the username is available, and creates an MD5 hash based on username, password and date, to be used in the "activation" of the account.

user_activation_message($username)
Sends the custom activation message to the email address for the username specified

user_activation($activation_hash)
Checks to see if the activation hash is valid, if it is, the activation_hash variable is set to NULL, thus signifying that the account is active.

user_password_change($username,$password_old,$password_new)
Quick and easy way to change the user's password with one function call.

user_logout()
Sets the authorization status in $_SESSION['authorized'] to FALSE

is_username_available( $username )
Returns TRUE or FALSE depending on whether or not the username is free.
CREATE TABLE auth_users
(
  id                            INT(11)      AUTO_INCREMENT NOT NULL,
  username                      VARCHAR(33)  UNIQUE NOT NULL,
  password                      VARCHAR(33)  NOT NULL,
  email                         VARCHAR(64)  NOT NULL,
  activation_hash               VARCHAR(128) NULL,
  PRIMARY KEY ( id )
);

<?
class auth {

    // default constructor
    function auth() {
        if( isset( $_POST['username'] ) && isset( $_POST['password'] ) )
        {   $this->mysql_bind(); }
        else if ( isset( $_GET['logout'] ) ) {
            $this->user_logout();
        }
    }

    // is the user authorized already
    function is_authorized() {
        return $_SESSION['authorized'];
    }

    // is the account currently activated
    function is_activated() {
        return $_SESSION['active_account'];
    }

    // bind to the mysql server
    function mysql_bind() {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $query = "SELECT username, activation_hash FROM auth_users " .
                 "WHERE username = '" . $username . "' AND password =MD5('" . $password . "')";
        $result = mysql_query( $query );
        $user_data = mysql_fetch_assoc( $result );

        // if the account exists in the system
        if( mysql_num_rows( $result ) == 1 ) {
            $_SESSION['authorized'] = true;
            $_SESSION['username']   = $username;

            // check to see whether or not the account is active
            if( ! isset( $user_data['activation_hash'] ) ) {
                $_SESSION['active_account'] = false; // if an activation hash is present, the account is not active
            } else {
                $_SESSION['active_account'] = true// if no activation hash present, the account is active
            }

        // if the account is not in the system
        } else {
            $_SESSION['authorized'] = false;
        }
    }

    // create a new barterjunk user
    function user_create($username,$email,$password) {

        if( $this->is_username_available($username) == false ) {
            return false;
        }

        // create an activation hash
        $activation_hash = md5( $username . $password . time() );

        // add the username, password, email and activation hash to the user's table
        $query = "INSERT INTO auth_users (username,password,email,activation_hash) " .
                 "VALUES ('" . $username . "'," .
                           "MD5('" . $password . "')," .
                           "'" . $email . "'," .
                           "'" . $activation_hash . "' )";
        mysql_query( $query );

        $this->user_activation_message( $username );

        return true;
    }

    function user_activation_message($username) {

        // get the activation hash for this account
        $query = "SELECT activation_hash, email FROM auth_users WHERE username = '" . $username . "'";
        $result = mysql_query( $query );
        $user_data = mysql_fetch_assoc( $result );

        // send a message to the user's email account with a verification link
        $subject = 'BarterJunk.com account activation for ' . $username;
   
        // header of the verification email message
        $header  = 'From: AccountActivation@barterjunk.com' . "\r\n" .
                   'Reply-To: webmaster@barterjunk.com' . "\r\n" .
                   'X-Mailer: PHP/' . phpversion();
   
        // text of the verification email message
        $verification_message =
        "{$username},\n\n" .
        "Please visit the link below to activate your new BarterJunk.com account.\n\n" .
        "http://www.barterjunk.com/?activation_code=" . $user_data['activation_hash'] . "\n";
   
        // send the message
        mail( $user_data['email'], $subject, $verification_message, $header );
    }

    // activate a locked account
    function user_activation($activation_hash) {
        // check to see that the activation hash is valid
        $query = "SELECT username FROM auth_users WHERE activation_hash='" . $activation_hash . "'";
        $result = mysql_query( $query );

        // if the hash is invalid, terminate
        if( mysql_num_rows( $result ) != 1 ) {
            return false;
        }

        // if the hash is valid, remove the activation hash from the system
        $user_data = mysql_fetch_assoc( $result );
        $query = "UPDATE auth_users SET activation_hash=NULL WHERE activation_hash = '" . $activation_hash . "'";
        mysql_query( $query  );
        // get the username previously associated with this activation hash, return it
        return $user_data['username'];
    }

    // change a user's password
    function user_password_change($username,$password_old,$password_new) {
        $query = "SELECT username FROM auth_users " .
                 "WHERE username = '" . $username . "' AND password = MD5('" . $password_old . "')";
        $result = mysql_query( $query );
        if( mysql_num_rows( $result ) != 1 ) {
            return false;
        }
        $query = "UPDATE auth_users " .
                 "SET password = MD5('" . $password_new . "') " .
                 "WHERE username = '" . $username . "'";
        mysql_query( $query );
    }
   
    // logout of the current session
    function user_logout() {
        $_SESSION['authorized'] = false;
    }

    // is the requested username available?
    function is_username_available( $username ) {
        if( $username == '' ) {
            return false;
        }
        $query = "SELECT username FROM auth_users WHERE username='" . $username . "'";
        $result = mysql_query( $query );
        if( mysql_num_rows( $result ) == 0 ) {
            return true;
        } else {
            return false;
        }
    }
}

// create the auth object
$auth = new auth();
?>
 

session_start();
require_once('auth.php');

if ( $auth->is_authorized() == true && $auth->is_activated() == true) {
    require('templates/authorized.php');
}
else if ( $auth->is_authorized() == true && $auth->is_activated() == false ) {
    require('templates/activation_needed.php');
} else {
    require('templates/unauthorized.php');
}
 

session_start();
require_once('auth.php');
user_password_change
($_GET['username'],$_GET['password_old'],$_GET['password_new'])
 

chris c

Comments

Comments SQL injection
Tue. Nov. 7th, 2006 11:55 AM    Scripter SCoon
  Comments SQL Injection Prob Fixed
Sat. Nov. 11th, 2006 8:44 PM    Helper kahotep
    Comments How to submit revision??
Sat. Nov. 11th, 2006 8:47 PM    Helper kahotep
Comments /agreed
Wed. Nov. 8th, 2006 7:23 AM    Scripter ctiggerf
Comments Logout
Tue. Dec. 5th, 2006 3:18 PM    Newbie hbilgen
  Comments Hmm.. not sure...
Sat. Dec. 16th, 2006 11:21 PM    Helper kahotep

Voting