CodeIgniter authenticate the user in every Controller

我是研究僧i 提交于 2020-01-25 10:39:06

问题


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.


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/18101283/codeigniter-authenticate-the-user-in-every-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!