edgarmtze
edgarmtze

Reputation: 25048

add tank_auth validation to several controllers in codeigniter

I have several controllers using Tank Auth like:

class Buscar_animal extends CI_Controller {


     function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        $this->load->library('tank_auth');        
    }



    function index()
    {
        if (!$this->tank_auth->is_logged_in()) {
            redirect('/auth/login/');
        } else {
            $data['user_id']    = $this->tank_auth->get_user_id();
            $data['username']   = $this->tank_auth->get_username();
            $this->load->view('menu.php',$data);        
            $this->load->view('v_search',$data);        
            $this->load->view('footer');            
        }       
    }


    //:...Several other functions
}

I am wondering How can I apply the condition:

if (!$this->tank_auth->is_logged_in()) {
                redirect('/auth/login/');
            } 

to all my controllers.

I was thinking to change all controllers like

class Buscar_animal extends MY_custom_controller {

}

and in custom apply the if logic.

Is there a efficient way to do that?

Upvotes: -1

Views: 115

Answers (1)

Yang
Yang

Reputation: 8701

Since you do restrict access to a controller in case $this->tank_auth->is_logged_in() === FALSE, it would make sense to define abstract class with a constructor that handles logic.

abstract class My_Controller extends CI_Controller
{
     public function __construct()
     {
         if ($this->tank_auth->is_logged_in() !== TRUE) {
            redirect('/auth/login/');
         }
     }
}

class Buscar_Animal extends My_Controller
{
    public function __construct()
    {
        parent::__construct();
    } 

    public function index()
    {
       $data['user_id']    = $this->tank_auth->get_user_id();
       $data['username']   = $this->tank_auth->get_username();
       $this->load->view('menu.php',$data);        
       $this->load->view('v_search',$data);        
       $this->load->view('footer');            
    }

}

Upvotes: 1

Related Questions