Jump to content

User authentication class


boha

Recommended Posts

Hello

I made my own authentication class, and I wonder if someone could tell me what he thinks about it.

Is there anything I should add or remove ? I'm also interested what do you think of security of this code.

 

This is how my database table looks:

user_uiduser_passuser_sid

bohab4793a35a6ccd8a21eb690ad1d9b85f9098f6bcd4621d373cade4e832627b4f6

 

My auth class:

<?php

class Auth
{
    //Database object
    private $_db;
    
    //Parameters (db tables, ...)
    private $_params;
    
    public function __construct(PDO $db, $params)
    {
        $this->_db = $db;
        $this->_params = $params;
    }
    
    //Check if user is authenticated
    public function isAuthenticated()
    {
        if (isset($_SESSION['auth']['sid']) && isset($_SESSION['auth']['uid'])) {
            return $this->_validateSid($_SESSION['auth']['uid'], 
                                       $_SESSION['auth']['sid']);
        }
       
        return false;
    }
    
    //Get username
    public function getAuth()
    {
        if (isset($_SESSION['auth']['sid']) && isset($_SESSION['auth']['uid']))
        {
            return $_SESSION['auth']['uid'];
        }
       
        return false;
    }
    
    // Set session cookies
    public function setAuth($uid, $pass)
    {
        if ($this->_validate($uid, $pass))
        {
            $_SESSION['auth']['uid'] = $uid;
            $_SESSION['auth']['sid'] = $this->_updateSid($uid);
          
            if ($_SESSION['auth']['sid']) {
                return true;
            }
        }
       
        return false;
    }
    
    // logout
    public function clearAuth()
    {
        $_SESSION['auth']['uid'] = false;
        $_SESSION['auth']['sid'] = false;
    }
    
    private function _validate($uid, $pass) 
    {
        $query = sprintf('SELECT COUNT(*) FROM %s WHERE user_uid = ? AND user_pass = ?', 
                          $this->_params['table']);
        $sth = $this->_db->prepare($query);

        $sth->execute(array($uid, $this->_cryptPassword($pass)));

        return ($sth->fetchColumn() == 1) ? true : false;
    }
    
    private function _validateSid($uid, $sid)
    {
        $query = sprintf('SELECT COUNT(*) FROM %s WHERE user_uid = ? AND user_sid = ?',
                         $this->_params['table']);
        $sth = $this->_db->prepare($query);
       
        $sth->execute(array($uid, $sid));
       
        return ($sth->fetchColumn() == 1) ? true : false;
    }
    
    private function _updateSid($uid)
    {
        $sid = $this->_generateSid();
        $query = sprintf('UPDATE %s SET user_sid = ? WHERE user_uid = ?',
                         $this->_params['table']);
       
        $sth = $this->_db->prepare($query);
        $result = $sth->execute(array($sid, $uid));
       
        if ($result) {
           return $sid;
        }
       
        return false;
    }
    
    private function _cryptPassword($pass)
    {
        return md5($pass);
    }
    
    private function _generateSid()
    {
        return md5(mt_rand() . time());
    }
}


?>

 

And example:

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

/* Connect to an database */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'username';
$password = 'password';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$auth = new Auth($dbh, array('table' => 'users'));

if ($_POST['login']) {
try {	
    $auth->setAuth($_POST['username'], $_POST['password']);
} catch (PDOException $e) {
            echo $e->getMessage();
}
}
var_dump($auth->getAuth());
var_dump($auth->isAuthenticated());

?>


<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <input type="submit" value="login" name="login" />
</form>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.