I have the following code that checks for both the username and password but I would like to change it so that it checks to see if the username or password is valid.
I was thinking of making two different functions checkUsername and checkPassword as functions and have two call backs for each input.
I just would like to know if I am on the right track or if my controller and model can be altered how they are?
Model:
function check_login($username,$password) {
$query = $this->db->query("SELECT id, first_name, last_name, email, password FROM users WHERE email = ? and password = ?", array($username, md5($password))); // Result
return ($query->num_rows() == 1) ? $query->row() : FALSE;
}
}
Controller:
function _checkUsernamePassword() {
// adding the _ makes the function 'private' so it can't be called from the URI.
extract($_POST); // Gets data from form and creates vars
$user = $this->login_model->check_login($username,$password);
if(! $user){ // != If username or password are not correct
$this->session->set_flashdata('login_error',TRUE); //does not add the non valid login to the session
$this->form_validation->set_message('_checkUsernamePassword', 'Sorry %s is not correct.');
return FALSE;
} else {
$this->session->set_userdata('logged_in',TRUE);
$this->session->set_userdata('user_id',$user->id);
$this->session->set_userdata('user_name',$user->first_name);
$this->session->set_userdata('user_email',$user->email);
return TRUE;
}
Will you ever have a scenario where you want to determine if a user name exists on its own? If not, I see no reason to add the extra functions. It’s generally considered a bad practice to let the client know that a username was valid if an invalid password was submitted. It lets a malicious person know that they’ve solved 50% of the puzzle, freeing them to crack the password only. Further, I can’t imagine a scenario where you’d want to check if a password exists on its own.
One thing I would note from your code is that
md5has been broken andsha1is really a better option for storing passwords these days. Otherwise, without poring over the code looking for tiny improvements I’d say that you’ve used prepared statements with your inputs and everything else looks okay, so you’re probably fine.