CodeIgniter Authentication Design Principles
CodeIgniter is a SUPER powerful framework and I have picked up some tricks along the road. If you are looking for a simple way to jail access to parts of your application, the following is tried and tested – I use a similar approach in almost every application I write.
When you want to lock users out of just one function or an entire controller just create a new model (call it auth.php or something useful) and autoload it in the autoload.php file under config/
For a simple explanation consider the following :
Really all we are doing is determining which script they are trying to access and if they are allowed to be there or not based on their user permission level (set in a session at login authentication (usually from the database)).
To lock down a controller simply add $this->auth->jail(); to the constructor or whatever method / function you want to lock. This may not be the most elegant solution but it works and is tough to screw up – if you do not need group permissions and only a boolean result, take a look at this one :
As you can see, much simpler however only allows a check to see if the user is logged in or not. Once again, this can be loaded per function or per controller (in the constructor).
Hope this helps, I really do need to get to bed - probably have twenty revisions for this code after a wink of sleep. Always welcome feedback (criticism is expected with insomniatic posts).
PS. I am aware “insomniatic” is not a real word.





In this example, class method names are tied into the auth library, meaning you need to update auth if a new method is added to a controller. Also, since there is no relation between the method and the controller, allowing a “user” to have insert or update permissions would allow this for every controller that makes use of auth.
Why not just pass allowed roles as an argument and match the the role of the logged in user against it? This would work within a controller constructor as well as inside specific controller methods (if you need granular security)
$this->auth->allowed_roles(‘user’,'admin’);
On the downside, if roles change or a new role is introduced, you need to update your controllers.
I would have loved to have demonstrated this technique in full, unfortunately this tutorial was meant for an absolute basic explanation. Last night we did a screencast (about 45 minutes) I am syncing the audio from the call to the video which demonstrates exactly your method.
Thank you very much for your feedback.
Cool. Looking forward to see your screencast on this. Always great to compare methods.