k1ng440
2/9/2013 - 10:26 AM

PHP: Login class

PHP: Login class

<?php

/**
 * @category  PHP
 * @author Steven King (info@k1ngdom.net) (skype: k1ngs.k1ngdom) (phone: +880 174 202 0548)
 * @link http://k1ngdom.net
 */

class Login extends library {
    private $user_name;
    private $pass;
    private $data;
    private $salt = 'xxxxxxxxxxxxxxx';
    public $cookiename = 'uhash';

    /**
     * Validate login information against database.
     * @param string $username Username to validate
     * @param string $password Password to validate.
     * @return mixed array containing user information if found else boolean false.
     */
    public function Validatelogininformation ($username, $password, $sha1encrypt = true) {
        if($sha1encrypt === true) {
            $password = sha1($password);
        }
        $this->data = parent::querySelectSingle("SELECT user_id, activated, fName, lName, email, user_name, password, last_login, status, country_name, lang FROM tbl_member WHERE user_name = :user_name AND password = :password", array(':user_name' => $username, ':password' => $password));
        return $this->data;
    }

    /**
     * Validate logged in users.
     * @return boolean Return true if the user logged in else false.
     */
    public function validate_loggedin_user() {
        if (isset($_SESSION['user_name'], $_SESSION['password']) === true) {
            if($this->Validatelogininformation($_SESSION['user_name'], $_SESSION['password'], false) === false) {
                echo "string";
                return false;
            } else {
                return true;
            }
        } else if ($this->Hashcheck() === true) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * check if hashed remember cookie exists. if so set the $_SESSION
     * @return boolen
     */
    public function Hashcheck () {
        if (isset($_COOKIE[$this->cookiename]) === true) { // check if remember cookie
            $hash = $this->hash_decrypt($_COOKIE[$this->cookiename], $this->salt);
            $hash = json_decode(base64_decode($hash));
            $username = $hash[0];
            $password = $this->hash_decrypt($hash[1], $this->salt);
            $userinfo = $this->Validatelogininformation($username, $password);
            if ($userinfo !== false) { // check if login information is currect.
                $this->setsession();
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Login user
     * @param  string  $username Username to login
     * @param  string  $password Password to login
     * @param  boolean $remember Set to true for remember me
     * @return mixed   boolean on Success. string on fail.
     */
    public function userlogin ($username, $password, $remember = false) {
        $this->user_name = $username;
        $this->pass = $password;
        if (empty($this->user_name) || empty($this->pass)) {
            return "Please enter valid username &amp; password.";
        } elseif (strlen($this->user_name) < 5 || strlen($this->user_name) > 12) {
            return "Please enter valid username &amp; password.";
        } elseif (strlen($this->pass) < 6 || strlen($this->pass) > 18) {
            return "Please enter valid username &amp; password.";
        }

        $logininfo  = $this->Validatelogininformation($username, $password);
        if ($logininfo !== false) {
            $member_status = $this->member_status($this->data['status']);

            if ($logininfo['activated'] != 'yes') {
                return "You have not activated your account yet.";
            } elseif ($member_status !== false) {
                return $member_status;
            }

            // Set the $_SESSION.
            $this->setsession();

            // if remember me is true set encrypted cookie.
            if ($remember === true) {
                $userhash = $this->hash_encrypt(base64_encode(json_encode(array($username, $this->hash_encrypt($password, $this->salt)))), $this->salt);
                setcookie($this->cookiename, $userhash, time() + (20 * 365 * 24 * 60 * 60));
            }

            // Upgrade last login information on database.
            $userIP=parent::getRealIpAddr(); // get login user computer IP Address
            parent::queryExecute("UPDATE tbl_member SET last_login = :last_login, last_login_ip = :last_login_ip, signin = 'yes' WHERE user_id= :user_id", array(':last_login' => $this->get_local_time('time'), ':last_login_ip' => $userIP, ':user_id' => $_SESSION['user_id']));

            return true;
        } else {
            return "Invalid username and/or password!";
        }
    }

    /**
     * set $_SESSION if $data is an array
     * @return boolean Success result
     */
    private function setsession() {
        if (is_array($this->data) === true) {
            $_SESSION['user_id'] = $this->data['user_id'];
            $_SESSION['fname'] = $this->data['fName'];
            $_SESSION['lname'] = $this->data['lName'];
            $_SESSION['last_login'] = $this->data['last_login'];
            $_SESSION['user_name'] = $this->data['user_name'];
            $_SESSION['password'] = $this->data['password'];
            $_SESSION['user_email'] = $this->data['email'];
            $_SESSION['default_currency'] = $this->data['lang'];

            return true;
        } else {
            return false;
        }
    }

    /**
     * Encrypt with salt
     * @param  string $string string to encrypt
     * @param  string $key    salt to encrypt
     * @return string hash
     */
    private function hash_encrypt($string, $key) {
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
    }

    /**
     * Decrypt encrypted hash with salt
     * @param  string $hash Hash to decrypt
     * @param  string $key  Salt for decrypting (must be same as used to encrypt)
     * @return string Unencrypted string
     */
    private function hash_decrypt($hash, $key) {
        return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($hash), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
    }

    public function check_is_login_user()
    {
        $this->query="SELECT * FROM tbl_member
                      WHERE
                      user_name='".$_SESSION['user_name']."' AND
                      fName='".$_SESSION['fname']."' AND
                      user_id='".$_SESSION['user_id']."'
                      ";

        if (parent::numRows($this->query) != 1) {header("Location: ".ABSOLUTE_HTTPS_PATH."login.php");exit();}
    }

    /**
     * Does nothing but returns string :P
     * @param  String $status Status from tbl_member table.
     * @return Mixed  return false on sccuess else error message.
     */
    public function member_status($status) {
        if ($status=="close") {
            return 'Account close by your self.';
        } elseif ($status=="suspended") {
            return 'Your account is suspended.';
        } else {
            return false;
        }
    }

    /**
     * Email verification for forgotten password
     * @param  string $user_name          Username
     * @param  string $email              Email adress
     * @param  string $activation_number  Activition number (sent via email).
     * @return string                     errors
     */
    public function get_login($user_name, $email, $activation_number) {
        $userinfo = parent::querySelectSingle("SELECT * FROM tbl_member WHERE user_name = :user_name AND email = :email AND activation_number = :activation_number", array(':user_name' => $user_name, ':email' => $email, ':activation_number' => $activation_number));

        if ($userinfo !== false) {
            if ($userinfo['activated'] != 'yes') {
                return "You have not activated your account yet.";
            } elseif ($member_status !== false) {
                return $member_status;
            } else {
                return "You are not active yet.";
            }
        } else {
            return 'You are not a registered user.';
        }
    }

    /**
     * redirect user to user's pevious page or index page.
     * @param  boolean $fail  Set to true to redirect users to login page.
     * @param  mixed   $error set error message to show error on login page. (strign)
     */
    public function redirectuser ($fail = false, $error = false) {
        if($fail === true) {
            if($error !== false) {
                $_SESSION['error_msg'] = $error;
            }
            header("Location: login.php");
        } else if (isset($_SESSION['back_to_page']) === true) {
            header("Location: ".$_SESSION['back_to_page']);
        } else {
            header("Location: ".BASE_URL);
        }
    }

}