Jump to content

How good is this auth class


Madchen

Recommended Posts

So to get started somewhere i decided to build auth class. How good is this? how secure? What would you do to improve it? Thx

 

Some info:

  • phpass is used from password hashing
  • many things/features aren't finished

 

<?php
class UserAuth{

   /**
   * User name
   * 
   * @var mixed
   */
   private $userName;

   /**
   * User email
   * 
   * @var mixed
   */
   private $userEmail;

   /**
   * User password
   * 
   * @var mixed
   */
   private $userPassword;

   /**
   * Database handler
   * 
   * @var PDO 
   */
   private $dbh;

   /**
   * Hashed password
   * 
   * @var PasswordHash
   */
   private $hasher=null;

   /**
   * Holds session object
   * 
   * @var Session
   */
   private $session;

   public function __construct()
   {
       $this->hasher = new PasswordHash(8, false); 
       $this->dbh=new PDO('mysql:dbname=auth;host=localhost','root','ssdksdskdj'); 
       $this->session=new Session();
   }

   /**
    * Set user input data
    * 
    * @param string $userName
    * @param string $userEmail
    * @param string $userPassword
    */
   public function setData($userName=null, $userEmail=null, $userPassword=null)
   {
       $this->userName=$userName;
       $this->userEmail=$userEmail;
       $this->userPassword=$userPassword;
   }

   /**
    * Check  is user logged in or not
    * 
    * @return boolean
    */
   public function isLoggedIn()
   {
       if(isset($this->session->currentUser)){
           return true;
       }
       else{
           return false;
       }
   }

   /**
   * Insert new user in db
   * 
   * @return bool If user is inserted returns true
   */
   public function register()
   {
       //get hashed password using phpass library
       $hash=$this->hasher->HashPassword($this->userPassword);

       try{

          //hash fail if its below 20 chars
          if(strlen($hash) > 20){

              //user data
               $data=array(
                   $this->userName,
                   $hash,
                   $this->userEmail
               );

               //prepare
               $sth = $this->dbh->prepare("INSERT INTO users (userName, userPassword, userEmail) value (?, ?, ?)");

               //go
               if($sth->execute($data)){
                   return true;
               }
               else{
                   throw new Exception('Faild to insert user!');
               }
           }
           else{
               throw new Exception('Hash faild');
           }

       }
       catch(Exception $e){
           echo '<p>Something bad happend!</p>'; 
           //todo: after this save error 
       }

   }

   /**
   * Login user into system
   * 
   * @return boolen Returns true if user was succesufully logged in 
   */

   public function login()
   {    
       //grabb user data
       $sth=$this->dbh->prepare("SELECT userId,userName,userEmail,userPassword FROM users WHERE userName=?");

       //data
       $data=array(
           $this->userName
       );

       //go
       $sth->execute($data);
       $userData=$sth->fetch(PDO::FETCH_ASSOC);
       try{
           //if we've got something go
           if($userData){  

               //compare passwords           
               $result=$this->hasher->CheckPassword($this->userPassword, $userData['userPassword']);


               //if fine store user id in session
               if($result){

                   //if user is not already logged in then proceed
                    if(!isset($this->session->currentUser)){

                       $this->session->currentUser=$userData['userId'];
                       $this->session->currentToken=$this->hashToken();


                       //insert user data into loggedin table
                       $data=array(
                           $userData['userId'],
                           session_id(),
                           $this->session->currentToken
                       );


                       //prepare
                       $sth = $this->dbh->prepare("INSERT INTO loggedinusers (loggedInUser, loggedInSession, loggedInToken) value (?, ?, ?)");
                       if($sth->execute($data)){
                           return true;
                       }
                   }
                }                 
           }
           else{
               throw new Exception('Faild to retrive data from db!');
           }
       }
       catch(Exception $e){
           echo '<p>Something bad happend!</p>'; 
           //todo: after this save error
       }
   }

   /**
   * Logout user
   * 
   */

   public function logout()
   {
       try{
           //check is user logged in
           if(isset($this->session->currentUser)){


               //delete session data
               $sth=$this->dbh->prepare("DELETE FROM loggedinusers WHERE loggedInUser=?");

               //data
               $data=array(
                   $this->session->currentUser
               );

               //go
               if($sth->execute($data)){
                   //unset session
                   $this->session->unsetAll();
                   return true;
               }else{
                   throw new Exception('Session data was not deleted!');
               }              
           }
       }
       catch(Exception $e){
           echo '<p>Something bad happend!</p>'; 
           //todo: after this save error
       }
   }

   /**
    * Check that a users session is legitimate
    * 
    * @return boolean
    */

   public function checkSession()
   {
           //grabb session data
           $sth=$this->dbh->prepare("SELECT loggedInSession,loggedInToken FROM loggedinusers WHERE loggedInUser=?");

           //data
           $data=array(
               $this->session->currentUser
           );

           //go
           $sth->execute($data);
           $sessionData=$sth->fetch(PDO::FETCH_ASSOC);

           try{
               //go
               if($sessionData){

                   //get current session ID
                   $session_id=session_id();
                   //compare
                   if($session_id == $sessionData['loggedInSession']) {
                           //Id and token match, refresh the session for the next request
                           $this->refreshSession();
                           return true;
                   }          
               }
               else{
                   throw new Exception('Faild to retrive data from db!');
               }
           }
           catch(Exception $e){
               echo '<p>Something bad happend!</p>';
           }
   }

   /**
    * Refresh current session id and update databse with new session data
    */
   private function refreshSession()
   {
           //Regenerate id
           session_regenerate_id();
           //Regenerate token
           $random = $this->randomString();
           //Build the token
           $token = $_SERVER['HTTP_USER_AGENT'] . $random;
           $token = $this->hashToken($token); 


           //Store in session
           $this->session->currentToken = $token;

           //delete previous data
           //delete session data
           $sth=$this->dbh->prepare("DELETE FROM loggedinusers WHERE loggedInUser=?");

           //data
           $data=array(
                $this->session->currentUser
           );


           //go
           if($sth->execute($data)){
                //insert new info
                $data=array(
                     $this->session->currentUser,
                     session_id(),
                     $token
                );
                //prepare
                $sessionDataInsert = $this->dbh->prepare("INSERT INTO loggedinusers (loggedInUser, loggedInSession, loggedInToken) value (?, ?, ?)");


                if($sessionDataInsert->execute($data)){
                   return true;
                } 
           }     
   }

   /**
   * Return hashed string
   * 
   * @return string
   */
   private function hashToken()
   {
       $token = $_SERVER['HTTP_USER_AGENT'] . $this->randomString();
       $result = hash_hmac('sha512', $token, 'opjsd4ersdfsadfasdfasdfasdfdfgziqwopjasodjjsdgfw7ezr6342wezrw734');
       return $result;    
   }

   /**
   * Return random string with max lenght of 50 chars (default)
   * 
   * @param int $length
   * @return string $string
   */
   private function randomString($length = 50)
   {
       $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
       $string = '';    


       for ($p = 0; $p < $length; $p++) {
           $string .= $characters[mt_rand(0, strlen($characters)-1)];
       }


       return $string;
   }
}
?>

<?php 
class Session {

   const SECRET='sodifpsodfuspiodf748p5ćoićt3495349eort';
   private $hash;
   private $key;
   private $test;


   public function __construct()
   {
       $this->hash=md5(dirname(__FILE__) . self::SECRET);
       $this->key='sess_' . $this->hash;
   }

   /**
   * Creat new session and set value 
   *   
   * @param mixed $name
   * @param mixed $value
   */
   public function __set($name,$value) 
   {
       $_SESSION[$this->key][$name] = $value;
   }

   public function & __get($name) 
   {
       return $_SESSION[$this->key][$name];
   }


   public function __isset($name) 
   {
       return isset($_SESSION[$this->key][$name]);
   }

   public function __unset($name) 
   {
       unset($_SESSION[$this->key][$name]);
   }

   public function unsetAll() 
   {
       unset($_SESSION[$this->key]);
   }
}
?>

Link to comment
https://forums.phpfreaks.com/topic/272968-how-good-is-this-auth-class/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.