2

I am trying to build a web application with codeigniter. I have installed Ion Auth as my authentication model.

The default Auth.php controller authenticates the user and sets up the session.

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

class Auth extends CI_Controller {



    function __construct()
    {
        parent::__construct();
        $this->load->library('ion_auth');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->helper('url');

        $data['title']="Login Page";
        $this->load->view("view_site_header",$data);

        // Load MongoDB library instead of native db driver if required
        $this->config->item('use_mongodb', 'ion_auth') ?
        $this->load->library('mongo_db') :

        $this->load->database();    

        $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
    }

    //redirect if needed, otherwise display the user list
    function index()
    {
        // if not logged in - go to home page
        if (!$this->ion_auth->logged_in())
        {
            //redirect them to the login page
            redirect('auth/login', 'refresh');
        }
        // if user is an admin go to this page
        elseif ($this->ion_auth->is_admin())
        {
            // if an admin, go to admin area

            //set the flash data error message if there is one
            $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

            //list the users
            $this->data['users'] = $this->ion_auth->users()->result();
            foreach ($this->data['users'] as $k => $user)
            {
                $this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
            }

            $this->_render_page('auth/view_users', $this->data);                
        }   else
    {
        //redirect them to the default home page 
        $data['title']="IMS Home Page";
        $this->load->view("generic/view_site_header",$data);
        $this->load->view("generic/view_generic_nav");
        $this->load->view("generic/view_content_generic");
        $this->load->view("view_site_footer");
    }
}

what I want to do is create a new controller for my application logic and leave the auth controller for authentication.

How can I make use of the auth controller to ensure my user is logged in when accessing my new controller? in addition I need the ession information to be available to the new controller.

my new controller, master_data has the following code:

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

class Masterdata extends CI_Controller{

    function index ()
    {
            $data['title']="Master Data Home Page";
            $this->load->view("master_data/view_master_data_header",$data);
            $this->load->view("master_data/view_master_data_nav");
            $this->load->view("master_data/view_content_master_data_home");
            $this->load->view("master_data/view_master_data_footer");

            echo $this->session->userdata('username');



    }
}

obviously the echo $this->session->userdata('username'); does not work as the new controller has no knowledge of the auth controller session.

any help appreciated as always.

Kind Regards,

Smudger
  • 10,451
  • 29
  • 104
  • 179

3 Answers3

11

First autoload the ion_auth library. If u simply want to check if the user is logged-in, just check it in every controller's constructor u load

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

    if (!$this->ion_auth->logged_in()) {
       // redirect to login view
    } 
}

If u happen to have multiple groups , u can create a new controller inside application/core/MY_controller.This controller will check whether user is logged in.You can extend this base controller to create new controller.A very good explanation on this is given by David john.Check this link .

Arun Unnikrishnan
  • 2,339
  • 2
  • 25
  • 39
2

obviously the echo $this->session->userdata('username'); does not work as the new controller has no knowledge of the auth controller session.

Eh...if the session library is loaded, then yes...the controller calling it will be able to access the session variable $username.

The way we handle this is to create a new controller parent class like MY_Controller in the application/core directory. This class loads common libraries/packages (like session and ion_auth). You could also autoload the libraries and helpers.

Since ion_auth stores all of the user profile data in a session var, all you need (on subsequent, non-authenticated) pages is the session lib to retrieve session data about the logged in user.

You really should check for their auth status though, and fail gracefully:

if (!$this->ion_auth->logged_in()) {
    // echo a login link
} else {
    // echo session var for username
}

Something like that...

John Corry
  • 1,567
  • 12
  • 15
  • Thanks jcorry, the MY_Controller in the application/core directory, is this code processed automatically without being 'autoloaded'? so if I moved my ion auth controller syntax to the MY_Controller, would this automatically be available in all future controllers? is this a standard practice? Thanks for the knowledge and your time. – Smudger Feb 28 '13 at 20:00
  • 1
    What you're doing with MY_Controller is overloading the CI controller class with your own. So, `class MY_Controller extends CI_Controller` will let you inherit all of the functionality of the CI controller class, but make changes for your individual controller that inherit from MY_Controller. You can read about that principle here: [link](http://ellislab.com/codeigniter/user-guide/general/core_classes.html) – John Corry Mar 04 '13 at 15:09
0

jcorrys approach should work. An alternative approach (which will give your entire application a great deal more flexibility is to use a modular layout - https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

You will have to do a bit of fiddling to get it to play nicely with ion auth, but following the instructions in this question worked for me: Using Ion Auth as a separate module in the HMVC structure (have a look at the forks of ion auth on git hub - I think someone may have already done it for you)

This approach will allow you to access any method in any controller from anywhere in your application (even from a view if you need to) using this kind of syntax: modules::run('module/controller/method', $params);

This will essentially allow you to develop the existing ion auth controller into a user management controller which you can access from any other controllers you create (nice and dry).

Community
  • 1
  • 1
SwiftD
  • 5,769
  • 6
  • 43
  • 67