Cato Yeung
Cato Yeung

Reputation: 701

Codeigniter authentication before every controller and action

I am writing a web application using codeigniter.
I want to authenticate the privilege of our users before they access the page.
Actually nearly all controller action except the log in page need to call the model and use

$this->Users->validate($username, $password)

I want to make it general for every controller. Do I need to inherit the controller class? How could i do that?

Upvotes: 2

Views: 12473

Answers (5)

b126
b126

Reputation: 1254

in CodeIgniter 4, you should put your logic in BaseController.php

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger){
            // Do Not Edit This Line
            parent::initController($request, $response, $logger);
    
            // Preload any models, libraries, etc, here.
            // E.g.: $this->session = \Config\Services::session();
}

Upvotes: 0

Azam Alvi
Azam Alvi

Reputation: 7055

The best way is that you should make a helper file in your application/helper folder with this name or any of you want but don't remove _helper, you should use this name authentication_helper, and put the following code as yours

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    function varify_session(){
       $CI = &get_instance();
       $user_session_id = $CI->session->userdata('logged_in');

       if($user_session_id  ==  '') {
        redirect('login');
       }
   }
   ?>  

chage code with yours code. then in your autoload file and in put this into helper

     $autoload['helper'] = array('authentication');

then you just need to put this line into your every controller constructor like this

     function __construct()
     {
         parent::__construct();
         varify_session();  
     }

hope it will help.

Upvotes: 2

Praveen kalal
Praveen kalal

Reputation: 2129

please write below code in constructor of each controller

$this->load->library(‘session’);
$this->load->model(‘login_model’,'login’,TRUE);

/* check whether login or not */
if(!$this->login->check_session()){
redirect(‘/login’);
}

Upvotes: 1

Bogdan Burym
Bogdan Burym

Reputation: 5512

Correct before filter usage:

class Test extends Controller {

    var $before_filter = array();

    var $after_filter = array();

    function __construct() {
        parent::Controller();

        $this->before_filter[] = array(
            'action' => 'before_filter_run',
        );

    }

    function before_filter_run() {
        // Auth here
    }
}    

For details read here

Upvotes: 0

Tarek
Tarek

Reputation: 3798

We have a project using Codeigniter and the way we are doing it :

When you have a new controller :

class xxxx extends MY_Controller { }

And Inside the MY_Controller class

function __construct() {
 // do your validations
}

Upvotes: 13

Related Questions