Search code examples
phpkohanakohana-3

PHP/Kohana - avoiding repeating code to check if a user is logged in


I am a newbie to PHP/Kohana application development.

In the web app i am developing , whenever a new request come to the controller i am required to check if the user is logged-in or is he having sufficient privileges to commit the action he requested. Since my application have different category of members(having different degree of authority), every controller method ends up having multitude of if/else branches. the code is repeated in other controller methods as well.

Is there any suggested way to centralize these calls and to avoid code repetition? I mean is the only way to achieve this by writing a method to encompass all the user session code ? or am i missing any functionality that is baked into the PHP/Kohana which is already dealing this scenario?

eg:-

if (Auth::instance()->logged_in('commentator')) {

// do something here.

}
else if (Auth:instance()->logged_in('admin')){

// do something here.

}
else if (Auth:instance()->logged_in('reviewer')){

// do something here.

} 

Solution

  • Create a controller named Controller_Authenticated with some code like this:

    protected $login_level;
    
    public function before()
    {
        parent::before();
    
        if (Auth::instance()->logged_in('commentator')) {
            $this->login_level = 'commentator';
        }
        elseif (Auth:instance()->logged_in('admin')){
            $this->login_level = 'admin';
        }
        elseif (Auth:instance()->logged_in('reviewer')){
            $this->login_level = 'reviewer';
        }
        else {
            // Redirect to login page here, or display a "you are not logged in" message
        }
    }
    

    Then, have your other controllers extend Controller_Authenticated instead of just Controller. Then you can check the value of parent::$login_level to see what kind of user this is.

    That way, all of your login-checking code is in one place, and checking what kind of user you are is done automatically when the controller loads (before the action is called).

    The Kohana documentation has almost exactly this example for using a before method to handle login stuff.