Welcome Guest, Not a member yet? Register   Sign In
Preventing Logged in users from calling methods/functions of a controller directly. N00b here :oP
#2

[eluser]Bas Vermeulen[/eluser]
Welcome Smile

Let me explain what I did to block access to full controllers or methods for people who aren't logged in w/o having to do that check in each secure controller/method. I hope this helps!

I extended the CI base Controller => MY_Controller (check the user guide if you don't know how to do that: http://ellislab.com/codeigniter/user-gui...asses.html). I used the term index for stuff that is allowed to be used by people who aren't logged in.

I added a the following to my config file:
Code:
/*
|--------------------------------------------------------------------------
| Index controllers
|--------------------------------------------------------------------------
|
| This determines which controllers are allowed to be used when a user is
| not logged in to prevent access to the secure controllers.
|
*/
$config['index_controllers'] = array('login', 'register');

/*
|--------------------------------------------------------------------------
| Index methods
|--------------------------------------------------------------------------
|
| This determines which methods are allowed to be used when a user is
| not logged in to prevent access to the secure methods.
|
*/
$config['index_methods'] = array('lost', 'request', 'activate');

The following goes into the construct method of MY_Controller (I removed some stuff to show the part that matters):

Code:
if($is_logged_in) {
    // Doing some stuff here
} else {
    // Not logged in, so I'm checking if the request is permitted.
    // First get the allowed controllers and methods
    $index_controllers = $this->config->item('index_controllers');
    $index_methods = $this->config->item('index_methods');
    // Then get the controller and method of the current request
    $current_controller = $this->router->fetch_class();
    $current_method = $this->router->fetch_method();
    // Now let's do the check
    if (in_array($current_controller, $index_controllers)) {
        // We can continue because the requested controller
        // is an index controller
        // Doing some stuff here
    } elseif (in_array($current_method, $index_methods)) {
        // We can continue because the requested method
        // is an index method
        // Doing some stuff here
    } else {
        // We have to abort this request because the requested
        // controller or method is a secure one, the user need
        // to be logged in.
        // Redirect to the login page.
        redirect('/login');
    }
}

I think with this info you should be able to fix what you want?


Messages In This Thread
Preventing Logged in users from calling methods/functions of a controller directly. N00b here :oP - by El Forum - 10-10-2010, 04:14 AM



Theme © iAndrew 2016 - Forum software by © MyBB