TCM
TCM

Reputation: 16900

How to verify if user is logged in?

I am using CodeIgniter framework for PHP. There are some pages that are exclusively for Admin and they are located in Admin/*. When the user logs in, i store some value in session as a flag and verify it in my controller to test whether the user is logged or not. I wrote the code to check session in every method in my controller. But, then I realized i didn't want to write the same line of code in each and every method since many issues are created from maintainability point of view. Then i decided to create a exclusive Controller which will load only Admin views and thus in it's constructor i check the session value. Is there any other method apart from this approach. Am i doing it right? Or any other secure mechanism is available in CodeIgniter?

Upvotes: 4

Views: 510

Answers (3)

Vasil Dakov
Vasil Dakov

Reputation: 2039

For example:

class Admin extends Controller {

 function __construct()
 {
     parent::__construct(); 
     $this->is_logged_in();
 }

 function is_logged_in()
 {

   $is_logged_in = $this->session->userdata('is_logged_in');
   if(!isset($is_logged_in) || $is_logged_in != true) 
   {
     redirect('login');
   }
 }

Upvotes: 1

sea_1987
sea_1987

Reputation: 2954

you could do it in your constructor method something like this,

function __construct {
    parent::construct();
    /* Do you login check here */
}

Upvotes: 1

Flakron Bytyqi
Flakron Bytyqi

Reputation: 3254

You've taken one of the best approaches (my opinion), just make the other admin controllers extend from that controller so you can have specialized controllers (admin blog, admin gallery etc). If you need help, I'll gladly help you.

Upvotes: 4

Related Questions