Snow
Snow

Reputation: 1

CodeIgniter Custom Lib

im trying to create a new lib which will auto load each time a controller is loaded and authenticate to see if a user is logged in

I’m auto loading the script and its loading fine how-ever it doesn’t seam to authenticate

My Lib

class Authentication {

var $CI;
function Authenication() {

    $this->CI =& get_instance();

    $this->CI->load->library('session');
    $is_logged_in = $this->CI->session->userdata('is_logged_in');
    if(!isset($is_logged_in) || $is_logged_in != true)
    {
        echo 'You don\'t have permission to access this page. <a href="../login">Login</a>';    
        die();        
    }
}

}

Any suggestions are greatly appreciated

Upvotes: 0

Views: 95

Answers (1)

Bill H
Bill H

Reputation: 2069

I see what you are trying to do and I would suggest a different approach.

Create MY_Controller and put it in the core folder. Here is a basic representation of what should be in that file.

class Public_Controller extends CI_Controller 
{
    // The data array holds all of the information to be displayed in views
    public $data = array();

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

        // Authentication library handles sessions and authentication, etc...
        $this->load->library('Authentication');

        $this->data['account']['is_logged_in'] = $this->authenication->is_logged_in();
    }
}

class Auth_Controller extends Public_Controller
{   
    function __construct() 
    {
        parent::__construct();

        if ( !$this->data['account']['is_logged_in'] )
        {
            redirect('user/login', 'location');   
        }
    }
}

If you do it this way then for controllers that require authentication you can just extend Auth_Controller otherwise extend Public_Controller.

Upvotes: 2

Related Questions