Welcome Guest, Not a member yet? Register   Sign In
avoid adding authentication on each function
#1

[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.
#2

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

[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
#4

[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');
}
#5

[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');
}

}
#6

[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.
#7

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

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

[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.
#10

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




Theme © iAndrew 2016 - Forum software by © MyBB