我想为我的登录表单添加条件 - 如果用户尚未激活,则不登录。我使用CodeIgniter。那是我的控制者:
public function login ()
{
$this->load->model('user_model');
$user=$this->user_model->login();
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_login_check');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE)
{
$this->index();
}
else
{
if(count($user) > 0 )
{
$this->load->library('session');
$data = array(
'username' => $user['username'],
'user_id' => $user['user_id'],
'is_logged_in' => TRUE,
'role_id' => $user['role_id']
);
$this->session->set_userdata($data);
redirect('index/home_page');
}
}
}

我的模特是:
public function login()
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('username', $this->input->post('username'));
$this->db->where('password',sha1($this->input->post('password')));
//$this->db->where('deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL');
$result=$this->db->get();
return $result->row_array();
}

我在我的登录功能中尝试了这个:$this->db->where('deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL');
但它不起作用。如果不是活动用户,我怎么能进行这种身份验证,根本不登录?
答案 0 :(得分:2)
我会说你的代码有些错误。
首先,您在表单验证完成之前尝试登录用户。这应该在之后完成,或者我没有看到验证的必要性?
这将是我的登录功能版本,位于您的控制器中。
function login()
{
$this->load->model('users_model');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if (!$this->form_validation->run())
{
$this->index(); // Show the login form..
}
else
{
// This is where we try to login the user, now the validation has passed
if ($user = $this->users_model->login())
{
// Start the session...
}
else
{
// The model returned false..
}
}
}
所以你不要去模型,直到表单验证通过。然后,在你的模型中;
function login()
{
$where = array(
'username' => $this->input->post('username'),
'password' => sha1($this->input->post('password'))
);
// $this->db->select('*'); No need for this line
$query = $this->db->get_where('users', $where);
if ($query->num_rows() > 0)
{
// Found a match
// Are they activated?
if (!is_null($query->row('deactivated_at'))
{
// The user isn't deactivated
return $query->row_array();
}
else
{
// The user is deactivated
return false;
}
}
else
{
// The username and/or password is wrong...
return false;
}
}
希望这有帮助。