To protect an entire controller, you can put the auth check into the __construct()
call as eric.itzhak mentioned.
To protect an entire application, you can extend the CI_Controller class, put the auth in the constructor of that file, and then finally extend by MY_Controller instead of CI_Controller in each of your controllers.
Code examples:
/* File: application/core/MY_Controller.php */
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
if ( ! $this->ion_auth->logged_in())
{
redirect('auth/login');
}
}
}
And then, in each controller (note MY_Controller, not CI_Controller):
class Controller_name extends MY_Controller
{
function __construct()
{
parent::__construct();
}
// rest of controller methods
}
These code examples assume you're autoloading (you might as well) the ion auth library. If not, load the library in the MY_Controller
file as necessary.
There are two advantages to this method:
- You only have to change the CI_Controller to MY_Controller in each controller you want to protect.
- You don't have to protect everything which is helpful if you need to have an unprotected controller, i.e. the controller containing the auth methods (you won't be able to login if your auth controller requires you to be logged in :P -- there will be a redirect loop).