I have Ion Auth properly installed and working on my server. I also have the default CodeIgniter 2 "news" tutorial working in the same CI installation. I'm just playing around and curious about the proper way to use the authentication system to "enclose" or protect an entire application.
For this question, let's use the "news" tutorial that comes with CI.
Inside the index()
function in my news.php
controller, I added conditional code to check if the user is logged in. If not, the user is just taken to the login screen.
public function index() {
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
if ($this->ion_auth->logged_in()) {
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
} else {
redirect('auth/login', 'refresh');
}
}
I can see this works, but the immediate downside is that every function within the controller would also have to be modified with similar conditional logic to protect all other page views. e.g. - check for login, display page, else go to login page... over and over.
Is this the way it's supposed to be done?
What if an application is already built and working and one simply wants to protect it all? Adding conditional logic to check login status on every single page view within the controller seems unnecessarily verbose.
Can the whole application (all views) be protected in one place to minimize code modification? If so, how?
I think the right logic would be to check the user status inside the
__construct
method as it will be done each time the controller is used. it won't protect the entire ci application, just the methods in this controller, but i think this will do for your case.Try this :
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:
And then, in each controller (note MY_Controller, not CI_Controller):
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:
Constructor is the way to go. Something else to think about -- its going to be more flexible if you call your own method instead of Ion Auth directly. typically part of the logged in process is getting unique values that are shown in the view, or an id used to keep track of the session, etc etc. Example: show the user name on the page.
So push the ion auth logged in check to a model, add a method for getting the user info or whatever you need. for each method return false if it doesn't work. and then in your constructor check if it was returned