Welcome Guest, Not a member yet? Register   Sign In
My Auth System Problem
#1

[eluser]albertleao[/eluser]
Hey everyone!!! I built my own authentication system which works almost too well. Whenever a user logs in, I create a cookie for the session and a cookie for the userid. I then save the session to the db and check to see if the cookie is valid on every call via an extension of the CI controller.

My problem is that for some reason that I have not been able to track, when I perform a lot of ajax calls that get authenticated, my code seems to think that I'm not logged in, then logs my user out. I find that it is very random, but seems to only happen when performing ajax calls.

Here is my code for authentication.

Code:
public function authenticate_session() {
  if($this->input->cookie("userid") && $this->input->cookie("session")) {
   $userid = $this->input->cookie("userid");
   $cookie_session = $this->input->cookie("session");
  
   $sql = "SELECT `userid`, `sessionid`, `login_type` FROM `user_sessions` WHERE `sessionid` = ?";
   $result = $this->db->query($sql, $cookie_session);
  
   if($result->num_rows() == 1 && $result->row()->userid == $userid) {
    
    $login_type = $result->row()->login_type;    

    $sql = "SELECT * FROM `user_accounts` WHERE `userid` = ?";
    $result = $this->db->query($sql, $userid);
    
    $newdata = array(
      'userid' => $userid,
      'accounttype' => $result->row()->type,
      'login_type' => $login_type,
      'logged_in' => TRUE
     );
    
    $this->session->set_userdata($newdata);
  
    $session = $this->session->all_userdata();
  
    $sql = "UPDATE  `user_sessions`
      SET  `sessionid` = ?,
       `timestamp` = ?
      WHERE  `sessionid` = ?";
    $this->db->query($sql, array($session['session_id'], time(), $cookie_session));
  
    $cookie_session = array(
       'name'   => 'session',
       'value'  => $session['session_id'],
       'expire' =>  time()+(60*60*24*365),
       'domain' => '.example.com',
       'path' => '/',
       'secure' => FALSE
    );
    $this->input->set_cookie($cookie_session);
    
    return TRUE;
   }
   else {
    return FALSE;
   }
  }
  else {
   return FALSE;
  }
}

This code is called in a class that extends the controller class for any controller that handles functions of a user that is logged in. In the controller, I redirect to a logout page if this function returns false.

All help is very welcome. Thank you very much!




Theme © iAndrew 2016 - Forum software by © MyBB