使用Codeigniter-bcrypt登录Codeigniter [英] Codeigniter login with codeigniter-bcrypt

查看:92
本文介绍了使用Codeigniter-bcrypt登录Codeigniter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 https://github.com/dwightwatson/codeigniter-bcrypt,带有codeigniter.我有一个向我的主控制器提交帖子数据的表格.然后,我通过模型检查数据库的记录.我用过

I am using codeigniter-bcrypt from https://github.com/dwightwatson/codeigniter-bcrypt, with codeigniter. I have a form that is submitting post data to my main controller. I then check via a model the DB for the record. I have used the

$hash = $this->bcrypt->hash_password($password);

在创建帐户时对密码进行哈希处理.而且有效.密码已在数据库中正确散列.但是,现在我不确定在哪里可以使用反向来检查在表单中输入的密码是否与数据库的哈希密码相同.

To hash the password on account creation. And it works. Password is properly hashed in DB. Now however I am unsure of where to use the reverse to check if the password entered in the form to post is the same as the DB's hashed password.

if ($this->bcrypt->check_password($password, $stored_hash))
{
    // Password does match stored password.
}
else
{
    // Password does not match stored password.
} 

我在模型中的代码是

function getUserByLogin($login, $password) {        
    $this->db->where('login',$login);
    $this->db->where('password',$password);

    $result = $this->getUsers();

    if (count($result) > 0) {
        return $result[0];
    } else {
        return null;
    }
}
function getUsers() {
    $query = $this->db->get('users');

    if ($query->num_rows() > 0) {
        return $query->result();
    } else {
        return array();
    }
}

和我的控制器

if (isset($_POST['email']) && isset($_POST['password'])) {
            $login = $_POST['email'];
            $password = $_POST['password'];
            $user = $this -> user_model -> getUserByLogin($login, $password);
            $this -> saveUserToSession($user);
            $loggedIn = ($user == null ? false : true);
        }

任何帮助将不胜感激.

推荐答案

这不会:

  $this->db->where('password',$password);

您正在检查数据库中的实际原始密码.

You're checking for the actual raw password inside the DB.

您应该从数据库中获取哈希,然后将其与用户密码进行比较:

You should get the hash from the database and then compare it to the user's password:

function getUserByLogin($login, $password) {        
    $this->db->where('login',$login);

    $result = $this->getUsers($password);

    if (!empty($result)) {
        return $result;
    } else {
        return null;
    }
}
function getUsers($password) {
    $query = $this->db->get('users');

    if ($query->num_rows() > 0) {

        $result = $query->row_array();

        if ($this->bcrypt->check_password($password, $result['password'])) {
            //We're good
            return $result;
        } else {
            //Wrong password
            return array();
        }

    } else {
        return array();
    }
}

这篇关于使用Codeigniter-bcrypt登录Codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆