简体   繁体   中英

What is a good technique to prevent unauthenticated users from accessing controller methods?

I have an event(s) controller:

class Event extends CI_Controller{

   public function index(){
   }

   public function foo(){
   }

   //Shouldn't be able to use this method unless logged in
   public function bar(){
   }


}

And I'm trying to organise my code so it's fairly tidy and straightforward. Just now I have a controller named MY_Controller so that only authenticated users can access the methods(edit_event(),add_event()) of any controllers extending it.

However, some of the methods in my controller need to be accessed by unauthenticated users (such as get_event()).

What is a good way of handling this? Should I make two completely separate controllers or extend from the basic event controller and add authenticated methods?

Previously I've had a manager controller that handled all methods which required authentication such as add_user,delete_user,add_doc,delete_doc. But it became blotted very quickly and wasn't easy to update or modify the controller (plus it was messy and didn't seem to follow good programming etiquette).

usually i use hooks

read about them.

for example i created a url_hook.php and it controls everytime a page load if uri is allowed for the user:

class url_hook{

function allowed_urls(){

$allow = array('login','logout','search');

if(in_array($allow,$this->uri->segment(2)) && $this->session->userdata('user_id')){

 //ok user allowed

return true;

}else{

//user not allowed

 redirect();

} } }

then in config/config.php i do:

$config['enable_hooks'] = TRUE;

and in config/hooks.php somenthing like this:

 $hook['pre_controller'][] = array(
                                'class'    => 'url_hook',
                                'function' => 'allowed_urls',
                                'filename' => 'url_hook.php',
                                'filepath' => 'hooks'

                                );

all this will run automatically everytime a url is called in your app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM