Mala
Mala

Reputation: 14803

CodeIgniter only allow access to certain controllers when logged in

I have some CodeIgniter controllers which should only be accessed by users who have logged in (i.e. where $this->session->userdata('username') is not null). If a non-authenticated person attempts to access said controllers they should receive:

header('location: /auth/login');

There has got to be a better way to do this than to put a

if (!$this->session->userdata('username'))
    header('location: /auth/login');
else
{
    [rest of function]
}

in front of every function in the controller...

I know DX_Auth has a similar functionality, but I am not using an authentication plugin and I am not open to doing so.

Thanks!
Mala

Upvotes: 4

Views: 3756

Answers (1)

johnnyArt
johnnyArt

Reputation: 4436

Do the user login check when the class is created, so it doesn't matter what function the user is accessing it will check for the session variable and redirect to the login page on failure:

function className()
{
    parent::Controller();
    if(!$this->session->userdata('username')) header('location: /auth/login');
}

That's the way of calling the __constructor or it's equivalent in codeigniter when you create controllers/models, or at least that's what I understood!

Upvotes: 5

Related Questions