You don't really need to check for is_logged_in
. If you destroy/build the session data correctly all you should care about is "Does a user id exist in the session?", then you can let your main controller handle the rest.
class MY_Controller extends CI_Controller{
//here we just build some constants to check against values
//in the permissions array
const PERM_READ = "read";
const PERM_EDIT = "update";
const PERM_DELETE = "delete";
//here we let the main controller take care of our auth/permissions/roles etc
//first check if a user id exists in the session
//if so assign a user, group, permissions and check for authentication where
//you need it ( ie: child controllers)
protected $_user, $_group, $_permissions = array();
public function __construct(){
parent::__construct();
//check for a user id in the session
$this->user = ( $this->session->userdata('uid') )
? User::find_by_id( $this->session->userdata('uid') )
: NULL;
//if user exists assign permissions and group
if ($this->user !== NULL) {
$this->_assign_group();
$this->_assign_permissions();
$this->_check_for_banned_users();
}
}
protected function _assign_group() {
return $this->group = $this->user->group->name;
}
// {["read", "update", "delete"]}
protected function _assign_permissions() {
return $this->permissions = json_decode($this->user->permissions);
}
protected function _check_for_banned_users() {
if ($this->group === 'banned') {
show_error('You have been banned from this website!');
return;
}
}
protected function _can_read(){
return (bool) ( in_array( self::PERM_READ, $this->permissions) );
}
public function _can_edit(){
return (bool) ( in_array( self::PERM_EDIT, $this->permissions) );
}
public function _can_delete(){
return (bool) ( in_array( self::PERM_DELETE, $this->permissions) );
}
}
This might give you some idea, as your user table won't look like that, I'm sure.
Now, you have control over any child classes.
class some_child extends MY_Controller{
public function __construct(){
parent::__construct();
}
public function show_something(){
if($this->is_ajax_request()){
if($this->user && $this->_can_read()){
//yes a user exists and is logged in,
//yes he has permission to read from this section
$this->load->view('some_view');
}
}
else
show_404();
}
}
Just be careful to destroy your session properly.
function logout(){
$this->session->set_userdata(array(
'uid' => 0,
//any others you created upon user login
));
return (bool) $this->session->sess_destroy();
}