CodeIgniter Forums
Need tips about authentication check (cookies) - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Need tips about authentication check (cookies) (/showthread.php?tid=63469)



Need tips about authentication check (cookies) - Rashid - 11-03-2015

What is the most common and robust auth check pattern in CI?

I personally see two ways:

1) insert check routine into a hook-function ('pre_controller' or 'post_controller_constructor' ?) - one for all controllers - nice
2) write it in __construct() directly, but it forces to duplicate code a lot, for each controller. bad..

I tried 1st way but got this:

PHP Code:
$hook['pre_controller'] = function ()
{
    
$id $this->input->cookie('user_id'); // ERROR: Undefined property: CI_Hooks::$input
    // ...
}; 

It seems that $this->input is absent in function's scope. Maybe I should create standalone class? or entirely different approach?

Please nudge me in a right direction.


RE: Need tips about authentication check (cookies) - InsiteFX - 11-03-2015

Create a MY_Controller and do your checks in it, then extend all your other controller's from your MY_Controller.


RE: Need tips about authentication check (cookies) - sintakonte - 11-03-2015

Besides the fact that you want to check a user id from a cookie i think you are on the right path.
Try the following:

in your config/hooks.php

PHP Code:
$hook['pre_controller'][] = array(
    
"class" => "AppCookieValidator",
    
"function" => "initialize",
    
"filename" => "AppCookieValidator.php",
    
"filepath" => "hooks"
); 


and create a File named AppCookieValidator.php in the application/hooks/ directory and do something like this

PHP Code:
class AppCookieValidator
{

    private 
$ci;

    public function 
__construct()
    {
        
$this->ci = &get_instance();
    }
    
    public function 
initialize()
    {
        
$id $this->ci->input->cookie('user_id'); 
    }




RE: Need tips about authentication check (cookies) - Rashid - 11-03-2015

Thank you, guys!


RE: Need tips about authentication check (cookies) - Rashid - 12-29-2015

(11-03-2015, 04:45 AM)sintakonte Wrote:
PHP Code:
$hook['pre_controller'][] = array(
 
"class" => "AppCookieValidator",
 
"function" => "initialize",
 
"filename" => "AppCookieValidator.php",
 
"filepath" => "hooks"
); 

Tried it. Should be $hook['post_controller_constructor'] otherwise get_instance() returns NULL.