Search code examples
phpcodeigniterprofiles

Codeigniter: Restricting user access to own profile page


I'm relatively new to Codeigniter, and attempting to restrict the user profiles to be viewed,edited, or deleted by the profile owner. I have successfully restricted access to the profiles from non-logged on users on another function. My issue is to restrict the user to his or her own profile.

I've made the urls to use the usernames, which in my database is named 'login.' What I'm trying to do is match the username from the database to the url.

Any tips and input would be helpful.

Controller to determine if user is logged in:

public function _is_logged_user() 
{ 
$id = $this->uri->segment(3); 
$data['user_profile'] = $this->user_model->get_user_profile($id);
$logged = $this->session->userdata('user_id');
   if($id == $logged) { 
     return TRUE; 
      }  else { 
     return FALSE; 
     }  
}

The get_user_profile part from my user_model:

public function get($user_id = null) 
{ 

if ($user_id === null) { 
   $query = $this->db->get('user');
   } elseif(is_array($user_id)) {        
   $query = $this->db->get_where('user', $user_id);        
   } else { 
   $query = $this->db->get_where('user',['user_id' => $user_id]); 
   }         
   return $query->result_array();    
}  

Solution

  • In your user edit controller, you should check if the username that's logged in (stored in the $_SESSION variable) matches the user that's being edited.

    In codeigniter, you can access this using the $this->session->userdata() function

    If it matches, show the edit form, otherwise display some error message.

    So in your user edit controller, you might have.

    if $this->_is_logged_user(){
        $data['user_profile'] = $this->user_model->get_user_profile($id);
        $this->display_edit($data);
    } 
    else{
        $this->display_error();
    }
    

    I would probably not fetch the userdata in the _is_logged_user() function

    public function _is_logged_user() 
    { 
        $id = $this->uri->segment(3); 
        // no need for the line below, we're not using the data here
        // $data['user_profile'] = $this->user_model->get_user_profile($id);
        $logged = $this->session->userdata('user_id');
        ...