简体   繁体   中英

CodeIgniter authenticate the user in every Controller

I'm building my first project in Codeigniter, using Tank_auth to handle my CMS authentication.

It's working ok but I have a question about best practices. Currently, every function in every controller has the following structure:

public function add()
    {
        if ($this->tank_auth->is_logged_in())
        {

            $data['stuff'] = 'stuff';

            $this->load->view('admin/cms_add',$data);


        } else
        {
            redirect('/admin/login/');  
        }
    }

With quite a few controllers, and a few functions in each, it's starting to get repetitive, and I wonder if this is the correct way to go about it, or if there's a cleaner method of ensuring non-logged in users can't access these functions.

Thanks in advance.

If every method in every controller should check whether user is logged-in, you can use __construct() method in each controllers as the following:

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

    if (! $this->tank_auth->is_logged_in()) {
        redirect('/admin/login/');
    }
}

You can also extend the CI Controller and create a custom MY_Controller and check the if statement inside. then the Controllers only accept logged-in users, should inherit the My_Controller :

application/core/MY_Controller.php :

class MY_Controller extends CI_Controller {

    public function __construct()
    {
        // Execute CI_Controller Constructor
        parent::__construct();

        if (! $this->tank_auth->is_logged_in()) {
            redirect('/admin/login/');
        }
    }
}

application/controllers/welcome.php :

class Welcome extends MY_Controller {

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

    function index()
    {
        $this->load->view('welcome_message');
    }
}

Take a look at CI user guide for more info.

I did this too. There's no better way for it, because you could have controllers that are visible for non-logged-in users, you can't add this to constructor or something.

The best, and in my opinion the most clean way is to add it to every function standard. This way you are always able to edit it if you want to have that controller function public for everybody.

Function that aren't allowed to anybody could be set to private.

private function add()
    { 
         // do private stuff
    }

So you're best off using your current code :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM