1

I am currently doing a project and on my project there's an login modal. The things that I've done so far using ajax are: 1) Check the both field username and password have a value; 2) The username field only has a value(password field is blank); 3) Check if the account is verified or not

NOTE: I just tried if($data['validateLogin'] > 0) if it is has a value, yes it is working but when I inputted the correct username and password it still give me an error "Incorrect username or password"

Question: How can check if the username and password is correct? Is my condition wrong? if($data['validateLogin'] > 0)?

Login Modal view

<!-- Login -->
            <div id="myLogin" class="modal fade" role="dialog">
                <div class="modal-dialog">
                    <!-- Modal content-->
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Login</h4>
                        </div>
                        <div class="modal-body">
                            <form id="login" encrypt="multipart/form-data">
                                <div class="form-group">
                                    <label> Username: </label>
                                    <input type="text" class="form-control" name="username" id="username">
                                </div>
                                <div class="form-group">
                                    <label> Password: </label>
                                    <input type="password" class="form-control" name="password" id="password">
                                </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary"> Login </button>
                            </form>
                            <a data-toggle="modal" href="#mySignup" data-dismiss="modal">Sign up</a>
                        </div>
                    </div>

                </div>
            </div>

AJAX for my login modal

$("#login").on('submit',function(event){

          $.ajax({
              url: "http://localhost/itsq/User/validate_user",
              type: "POST",
              data: $(this).serialize(),
              success: function(data) {
                  var result = JSON.parse(data);
                  //alert(data);
                  if(result===1)
                          {
                                swal({
                                  type: 'success',
                                  html: 'Update Successful!',
                                  timer: 2000,
                                  })
                                setTimeout(function() {

                                  document.location.href=base_url + "User/";

                                }, 2000);
                            // document.location.href="http://localhost/ecom/Administrator/view_staff_Account";

                          }
                          else
                          {

                                swal({
                                  type: 'error',
                                  html: result,
                                  timer: 2000,
                                  })

                            console.clear();
                          }
                  // $.LoadingOverlay("hide");
              },
              error: function (xhr, ajaxOptions, thrownError) {
           console.log(xhr.status);
           console.log(xhr.responseText);
           console.log(thrownError);
       }
          })
          event.preventDefault();
    });

Controller

public function validate_user()
    {
        $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert" style="padding:2px">', '</div>');
        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');
        if ($this->form_validation->run() == FALSE)
        { //if validation is false go to itemList
            echo json_encode(validation_errors());

        }
        else
        {

            $username = $_POST['username'];
            $password = $_POST['password'];

            $data['validateLogin'] = $this->CrudModel->validate_user($username,md5($password));

            if($data['validateLogin'] > 0) // If there's no match then do this
            {

                echo json_encode("Incorrect username or password");
            }
            else // Get all the information for that account
            {
                foreach($data['validateLogin'] as $vl) // Save it to one variable
                {
                     $user_id = $vl->id;
                     $status = $vl->status;
                }

                if($status != "Verified") // Is not verified
                {
                    echo json_encode("Your account is not verified");


                }
                else
                {
                    $this->session->set_userdata(array('user' => true, 'first_name' => $first_name, 'middle_name' => $middle_name, 'last_name' => $last_name,'gender' => $gender,'age' => $age, 'email' => $email,'username' => $username,'address' => $address, 'credit_card' => $credit_card, 'bank_name' => $bank_name));
                    redirect('administrator/index',$data);
                    echo json_encode(1); 
                }
            }


            // $this->CrudModel->insert('users', $customer);
            // echo json_encode(1); 
        }


    }

Model

// public function validate_user($table,$username_column,$email_column,$password_column,$username, $password)
public function validate_user($table,$username, $password)
{
    $this->db->select('username,email,password');
    $this->db->where("(email = $username OR username = $username) AND password = $password");
    // $query = $this->db->get($table);
    $query = $this->db->get();
    echo $this->db->last_query();
    return $query->result();
    // $query = $this->db->get_where($table,array($username_column => $username,$password_column => $password));
 //    return $query->result();
}
Angel
  • 966
  • 4
  • 25
  • 60
  • 1
    make sure you are not using encrypted password in database!! – Shihas Jun 11 '17 at 07:50
  • Don't use MD5 for passwords not secure any more use the php http://php.net/manual/en/function.password-hash.php and to verify callback http://php.net/manual/en/function.password-verify.php –  Jun 11 '17 at 08:50
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky Jun 12 '17 at 16:57

2 Answers2

2

You need to change your condition

if(count($data['validateLogin']) == 0) // If there's no match then do this
B. Desai
  • 16,414
  • 5
  • 26
  • 47
1

If there is a result from validate_user it will return true. If there isn't any results it will return false.

You can check the validity of validate_user result by doing the following. Which will check "If this value is false we will echo error. Else we will continue with login process".

// if NOT true
if(!$data['validateLogin']){
  echo json_encode("Incorrect username or password");
}
else {
...
}
levi
  • 1,566
  • 3
  • 21
  • 37