I have an event(s) controller:
class Event extends CI_Controller{
public function index(){
}
public function foo(){
}
//Shouldn't be able to use this method unless logged in
public function bar(){
}
}
And I’m trying to organise my code so it’s fairly tidy and straightforward. Just now I have a controller named MY_Controller
so that only authenticated users can access the methods(edit_event()
,add_event()
) of any controllers extending it.
However, some of the methods in my controller need to be accessed by unauthenticated users (such as get_event()
).
What is a good way of handling this? Should I make two completely separate controllers or extend from the basic event controller and add authenticated methods?
Previously I’ve had a manager controller that handled all methods which required authentication such as add_user
,delete_user
,add_doc
,delete_doc
. But it became blotted very quickly and wasn’t easy to update or modify the controller (plus it was messy and didn’t seem to follow good programming etiquette).
How about
public function bar() {
if (notLoggedIn)
// display error page
else
// perform authorized action
}
OK, so it’s not very sexy, certainly not as fancy as decorating the methods with some thing, but it does have the virtue of giving you full access to the database for authentication purposes, which is more than can be said for, say, the [Authorized]
attribute in C#
7
In a medium to large project I separate the controllers. This keeps the implementation of each controller a bit cleaner. And since security should be a core concern, this ensures you never forget to explicitly check the user is logged in. Plus you can easily swap your security implementation later if it needs to change.
1