I'm trying to make a simple routing rule to allow only authenticated users to certain controllers.
To achieve this, I would like to run precontroller hook and check if the user is logged in using ci session. However, I have to know which controller the user wants to access. How do I know this in a hook function?
$this->router->fetch_class();
Extend CI_Controller and this should work.
Cant you just put the authentication on the controller constructor ? It will be called when item instantiate and you can do the check there. Also you can always extend the CI_Controller and put the logic in there so that you can do your check in there (and use this->router->fetch_class() as suggested).
I dont think that hooks are best practice for what you want to achieve here
you may try the following: You need to create middle controller that you will extend instead of CI_Controller that will have authentication check and redirect the user to right controller
read this tutorial created by jondavidjohn step by step
http://jondavidjohn.com/blog/2011/01/scalable-login-system-for-codeigniter-ion_auth
You shoud be able to get the idea after 10 mins
Extend CI_Controller in your autoload library Class.
Something like this:
If you don't want to go the extended controller route, and I can see your logic there, then you have to use native PHP here because the CI object doesn't exist in the pre_controller_hook.
So, get the URI, then parse it to find the controller: