简体   繁体   English

使用password_verify登录CodeIgniter

[英]Login in CodeIgniter with password_verify

I'm trying to achieve to login implementation in CodeIgniter, I'm hashing password while registration like password_hash($this->input->post('password'),PASSWORD_DEFAULT) in my Controller and in the same Controller I'm trying to write a login method which is as followed : 我正在尝试实现CodeIgniter中的登录实现,我在我的控制器和我正在尝试的同一控制器中注册时对密码进行哈希处理,例如password_hash($this->input->post('password'),PASSWORD_DEFAULT)编写如下登录方法:

public function loginValidation() {
        $this->form_validation->set_rules('email', 'Email', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');

        if ($this->form_validation->run()) {
            // true
            $email  =   $this->input->post('email');
            $password   =   $this->input->post('password');

            // User Model Loaded in constructor
            if ($this->user->canLogin($email, $password)) {
                $session_data   =   array('email' => $email );
                $this->session->set_userdata($session_data);
                redirect('profile/personal','Refresh');

            } else {
                $this->session->set_flashdata('error', 'Invalid Username or Password');
                //redirect('login','Refresh');

            }
        } else {
            // try again to login
            //redirect('login','Refresh');
        }
    }

My user Model function is 我的用户模型功能是

public function canLogin($email, $password) {
    $this->db->where('email',$email);
    $this->db->where('password',$password);
    $query  =   $this->db->get($this->tableName);

    if ($query->num_rows() > 0) {
        return true;
    } else {
        return false;
    }
}

I know I have to password_verify($string,$hash) at some point but I'm unable to figure out. 我知道我必须在某个时候使用password_verify($string,$hash) ,但我无法弄清楚。

How do I validate the password against email and redirect to the desired view ie personal/profile and I'm making request via AJAX call. 如何通过电子邮件验证密码并重定向到所需的视图(即personal/profile并且正在通过AJAX调用进行请求。

What you need to do is fetch the record from the DB where only the email matches (assuming it is the Unique key). 您需要做的是从只有电子邮件匹配的数据库中获取记录(假设它是唯一键)。 Then you compare the returned value using password_verify() . 然后,使用password_verify()比较返回的值。
This is very rough and untested, but should give you an idea: 这是很粗糙且未经测试的,但是应该给您一个想法:

public function canLogin($email, $password) {
    $this->db->where('email',$email);
    // $this->db->where('password',$password);
    $query  =   $this->db->get($this->tableName);

    $row = $query->row();
    return $row ? password_verify($password, $row->password) : false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM