CodeIgniter Forums

Full Version: avoid adding authentication on each function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]jtan[/eluser]
is there a way to avoid adding authentication code on each function in Codeigniter? I ask because virtually all functions require authentication.

what the function does it route to login page when it's not authenticated.

Thanks.

El Forum

[eluser]WanWizard[/eluser]
Create a MY_Controller, and do your check in the constructor of that controller.

El Forum

[eluser]jtan[/eluser]
great, got it working, i now put all controllers to use MY_Controller and only the login page not using MY_Controller to avoid the endless loop

El Forum

[eluser]WanWizard[/eluser]
That works as long as you don't do other things in your MY_Controller that need to be available everywhere (including your login controller).

It's better to check the controller being called, and redirect if it's not the login controller:
Code:
if ( $this->router->fetch_class() != 'login' && $this->router->fetch_method() != 'auth' )
{
    redirect('login/auth');
}

El Forum

[eluser]jtan[/eluser]
here's what I have

function __construct()
{
parent::Controller();

if($this->session->userdata('authenticated')==0)
{
redirect('login');
}
if(is_null($this->session->userdata('authenticated')))
{
redirect('login');
}

}

El Forum

[eluser]WanWizard[/eluser]
I assume that works to. You can do
Code:
if ( empty($this->session->userdata(‘authenticated’)) )
{
    redirect(‘login’);
}
to capture both in one go.

El Forum

[eluser]jtan[/eluser]
great, thanks.

El Forum

[eluser]jtan[/eluser]
strange, I used your code and it returns empty, did you use any library for the "empty" command

El Forum

[eluser]WanWizard[/eluser]
The userdata() method of the session class returns FALSE if the variable does not exist, otherwise it returns the stored value.

I think the issue is that empty() is a language construct, you might not be able to use it on a method call. In that case (assuming that you store 0 and 1), you can just use
Code:
if ( ! $this->session->userdata(‘authenticated’) )
{
    redirect(‘login’);
}
taking advantage of the fact that 0 evaluates to false.

El Forum

[eluser]jtan[/eluser]
is it possible to share the code across several controllers instead of just functions within the controller?