Step 3.1 – Creating the login and logout page with Ion Auth

Auth.php which we moved inside controllers, is an example controller, so we can pretty much take whatever we need from there and use it where we need it.

As you can see, the index() method first verifies if the user is logged in by using the method $this->ion_auth->logged_in() .

So, if we need to verify this on our admin area why not move the method inside the constructor of the Admin_Controller?

class Admin_Controller extends MY_Controller
{
  function __construct()
  {
    parent::__construct();
    $this->load->library('ion_auth');
    if (!$this->ion_auth->logged_in())
    {
      //redirect them to the login page
      redirect('admin/user/login', 'refresh');
    }
    $this->data['page_title'] = 'CI App - Dashboard';
  }
  protected function render($the_view = NULL, $template = 'admin_master')
  {
    parent::render($the_view, $template);
  }
}

Now, you may ask, where did we load the session? We didn’t. We left that one to the Ion_Auth library.

OK. As you can see, in the constructor we first verified that the user is logged in. If is not, we redirect to the login() method of the User controller.

So, let’s create a User.php file inside application/controllers/admin and create a login()  and a logout() method inside it:

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

class User extends MY_Controller
{
  function __construct()
  {
    parent::__construct();
    $this->load->library('ion_auth');
  }

  public function index()
  {
  }

  public function login()
  {
  }
  public function logout()
  {
  }
}

As we won’t extend the Admin_Controller (we can’t because Admin_Controller’s constructor calls the ion_auth library, which is also called by the User controller…), we should load the ion_auth library inside the constructor of our controller to work with users.

In the login() method we first want to see if a form was submitted. If it was, then we try to see if the credentials are ok:

public function login()
{
  $this->data['page_title'] = 'Login';
  if($this->input->post())
  {
    //here we will verify the inputs;
  }
  $this->load->helper('form');
  $this->render('admin/login_view','admin_master');
}

As we are going to create a form, we will load the form helper in the controller. Now, let’s create the form in the login_view.php inside application/views/admin directory:

<div class="row">
  <div class="col-lg-4 col-lg-offset-4">
    <h1>Login</h1>
    <?php echo $this->session->flashdata('message');?>
    <?php echo form_open('',array('class'=>'form-horizontal'));?>
      <div class="form-group">
        <?php echo form_label('Username','identity');?>
        <?php echo form_error('identity');?>
        <?php echo form_input('identity','','class="form-control"');?>
      </div>
      <div class="form-group">
        <?php echo form_label('Password','password');?>
        <?php echo form_error('password');?>
        <?php echo form_password('password','','class="form-control"');?>
      </div>
      <div class="form-group">
        <label>
          <?php echo form_checkbox('remember','1',FALSE);?> Remember me
        </label>
      </div>
      <?php echo form_submit('submit', 'Log in', 'class="btn btn-primary btn-lg btn-block"');?>
    <?php echo form_close();?>
  </div>
</div>

It looks ok, but we shouldn’t see the menu unless we are logged in. So let’s go into our admin_master_header_view.php and make sure that the menu is only shown to the logged in users:

<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $page_title;?></title>
<link href="<?php echo site_url('assets/admin/css/bootstrap.min.css');?>" rel="stylesheet">
<?php echo $before_head;?>
</head>
<body>
<?php
if($this->ion_auth->logged_in()) {
?>
<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand"
href="<?php echo site_url('admin');?>"><?php echo $this->config->item('cms_title');?></a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li><a href="#">A link</a></li>
        <li><a href="#">Another link</a></li>
      </ul>
    </div>
    <!--/.nav-collapse -->
  </div>
</nav>
<?php
}?>

Now, if we visit http://localhost/admin we will be greeted by the login form.

Let’s return to our login() method and do the checks for those who fill the form and submit it:

public function login()
{
  $this->data['page_title'] = 'Login';
  if($this->input->post())
  {
    $this->load->library('form_validation');
    $this->form_validation->set_rules('identity', 'Identity', 'required');
    $this->form_validation->set_rules('password', 'Password', 'required');
    $this->form_validation->set_rules('remember','Remember me','integer');
    if($this->form_validation->run()===TRUE)
    {
      $remember = (bool) $this->input->post('remember');
      if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
      {
        redirect('admin', 'refresh');
      }
      else
      {
        $this->session->set_flashdata('message',$this->ion_auth->errors());
        redirect('admin/user/login', 'refresh');
      }
    }
  }
  $this->load->helper('form');
  $this->render('admin/login_view','admin_master');
}

Now, if we give the wrong credentials we should get returned to the login form.

Also, if we try to login with user: “admin@admin.com” and password: “password” we should be greeted by the dashboard.

What about the logout?

Well… the logout is a simple call of Ion Auth’s logout() method. So let’s just work with our logout() method inside the User controller:

public function logout()
{
  $this->ion_auth->logout();
  redirect('admin/user/login', 'refresh');
}

Now, we should put a Logout link on our horizontal menu, so let’s go to application/views/templates/_parts/admin_master_header_view.php and put the link in there:

<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $page_title;?></title>
<link href="<?php echo site_url('assets/admin/css/bootstrap.min.css');?>" rel="stylesheet">
<?php echo $before_head;?>
</head>
<body>
<?php
if($this->ion_auth->logged_in()) {
?>
<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand"
href="<?php echo site_url('admin');?>"><?php echo $this->config->item('cms_title');?></a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li><a href="#">A link</a></li>
        <li><a href="#">Another link</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="<?php echo site_url('admin/user/logout');?>">Logout</a></li>
      </ul>
    </div>
    <!--/.nav-collapse -->
  </div>
</nav>
<?php
}
?>

Now, that looks great. Hope you enjoyed. Next we will use more of the Ion Auth library methods to administer the groups.

72 comments

    1. Please don’t touch me. But if you want to get in touch with me, you can at any time write me at avenir.ro[at]gmail[dot]com

      1. not abel to access this “http://localhost/admin” link generating error

        Object not found!

        The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

        If you think this is a server error, please contact the webmaster.
        Error 404
        localhost
        Apache/2.4.7 (Unix) OpenSSL/1.0.1e PHP/5.5.6 mod_perl/2.0.8-dev Perl/v5.16.3

  1. Hello,

    I got an error:

    The file/controller MY_Session_files_driver.php does not exist in application\core directory
    Why is that? Do I have to search for that file somewhere? Would you please help? Thanks in advance.

    1. This must be related to using an older version of CodeIgniter, or the fact that you didn’t setup the session config data corectly. First of all make sure you have the latest version of CodeIgniter by downloading it from their site. After that, make sure you’ve setup the session correctly. 🙂

      1. I am using the latest codeigniter version. I set and configure the session files as instructed, but it still showin that error message. I even delete and reset everything relate to the ion_auth as well.
        Back to the learn codeigniter in small steps: Step 9, is it maybe about the hook configuration? Because I don’t follow that step. Thankyou.

        1. Now I remember. Yes, you are right. The problem is at the hook configuration. I’ve met this error before but I didn’t pay any attention to it because in the end I chose Jim Parry’s way of including the files. Could you try this in the App_Controllers.php and tell me if it solved your problem?

  2. Social (twitter, facebook, g+) register and social login with ion auth will be a great tutorial if you create on!

    Thank You!

  3. I have followed all the step but I got this errors:
    Error Number: 1146

    Table ‘ci_admin.ci_sessions’ doesn’t exist

    SELECT `data` FROM `ci_sessions` WHERE `id` = ‘bcbdffa6fd55bc5db0c215c8ee41b5905b895db9’

    Filename: libraries/Session/drivers/Session_database_driver.php

    Line Number: 156
    Can you please tell me why?

  4. Me too…I vote for a tutorial about Social (twitter, facebook, g+) register and social login with ion auth. It will be a great addition! Thanks

  5. Great tutorial, helped me a lot to understand ION Auth… I am trying to learn ION Auth to use in my codeigniter project, how can i create registration or sign up page using ION Auth..

    1. Hello, the library on Github already has an example controller that could help you get started, but if you already are comfortable with CI you could easily create the controller and the views. Maybe this is a good moment to create a tutorial about this subject 🙂

  6. Hi.
    I would like to thank you for the tutorials !!
    Very detailed and easy to understand.
    I don’t have issues yet but on login it doesn’t use bootstrap is there a reason for that?

    1. Hello. As you can probably figure out, the login view is not part of the administration area, as anyone can access that part. That is why I thought it would be better not to use an administration area specific CSS stylesheet 🙂

  7. Hello avenirer,

    I have been reading your tutorials but I have had a little problem completing this one, When I try to access localhost/admin the page does not load. The loading circle on my chrome tab just keeps spinning.

    So far I have been able to narrow it down to a problem loading the ion_auth library. As soon as I add $this->load->library(‘ion_auth’); the page won’t load. I followed the tutorials closely and even tried copy/pasting when I couldn’t get it to work.

    Thanks,
    Aiden

    1. Did you make sure you’ve set up the sessions correctly? Could you send me your application and datatabase in a .zip at avenir.ro@gmail.com? Also, make sure that the controller that has the login() method is extending MY_Controller and not Admin_Controller

  8. Hi .
    I have a problem in login form.
    The problem is after verifying the username and password , if the user password is incorrect and shows no error message, but if you try again to enter the correct data dashboard and displays the above error.

  9. Hello Sir,

    I got a problem, i have followed steps (not yet all) after this sentences of your tutorial “Now, if we visit http://localhost/admin we will be greeted by the login form.”

    I pretty confident have followed all your instruction, but really cannot figure out why the problem appears here.

    Here is my error message:

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: MY_Loader::$ion_auth

    Filename: _parts/admin_master_header_view.php

    Line Number: 14

    The line number 14 mentioned above in my code is:
    if($this->ion_auth->logged_in())

    Looking forward to hear feedback from you Sir

        1. i cannot find the instruction until this step and i am not really sure what you mean about loading the library,
          is that copying from Ion Auth’s libraries directory copy the files into your application/libraries directory as you mentioned on previous step?
          so far the only “Ion Auth Library” that i know is copying the libraries.

          1. actually, i tried to load library by adding a below line on the autoload.php

            $autoload[‘libraries’] = array(‘ion_auth’);

            but then the error is getting worse. Here is the error:
            A PHP Error was encountered

            Severity: Warning

            Message: mkdir() [function.mkdir]: Invalid argument

            Filename: drivers/Session_files_driver.php

            Line Number: 117

  10. Thank you very much Sir,

    I do following your 1-6 steps but skipping the step 8 because it is written ‘Optional’, i think that is my mistake LOL.
    but now I completed all instruction on step 8 and no more problem with session.

    The problem still exists until i add a new parameter on Autoload.php
    $autoload[‘libraries’] = array(‘session’,’ion_auth’);

    And the problem now is disappeared.

    Sir, you are awesome. My respect to you Sir.

  11. I just wanna let you know Sir,
    My stupid mistake is by creating a new php file called Admin_Controller.php inside controller/admin folder instead of modify the content of Admin_Controller class inside MY_Controller.php. I apologize of my stupidity sir LOL.
    Probably you shoud make a note about it on the admin_controller section above sir, to avoid other stupid people asking stupid question as i did LOL. And a little note about using sessions with database.
    no additional parameter required to add on the autoload libraries like what i mistakenly did before.

  12. Hello
    Very nice tuorial really easy to follow

    I have a problem on when i try to access the admin page it says

    Not Found
    The requested URL /admin was not found on this server.

    I’m working with wamp and all the configuration was done on that side for my project but
    so i can access it localhos/project and directly project can’t find why i don’t access the admin part

    Thank you

      1. Thank you for the info

        Now that i try to access my admin page it gives me this error

        A Database Error Occurred
        Error Number: 1064
        You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE `id` = ‘55152bb2ca8ba53de851e072436b317835dce80e” at line 2

        SELECT `data` WHERE `id` = ‘55152bb2ca8ba53de851e072436b317835dce80e’
        Filename: libraries/Session/drivers/Session_database_driver.php
        Line Number: 160

        Just can’t find where
        thank you

          1. Having almost same issues, but in my case, I see that the ‘identity’ field is not being built within the query.
            Tried to change manually in the models/Ion_auth_model.php file, but it does the same error, with ‘identity’ built in the query, and does not log on.
            What should I do? I’ve even switched the old model.php file for a fresh one to see if the issue was in it.

            Error Number: 1064

            You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘WHERE = ‘administrator’ ORDER BY `id` DESC LIMIT 1′ at line 2

            SELECT `email`, `id`, `password`, `active`, `last_login` WHERE = ‘administrator’ ORDER BY `id` DESC LIMIT 1

            Filename: models/Ion_auth_model.php

            Line Number: 973

          2. Make sure you’ve set up the configuration of ion auth, corect. I am reffering here on setting the identity field. From your error I understand you have “email” set as identity…

  13. Sir,
    i have a request, would you please adding tutorial about creating register page for new user?
    because sometimes we need to let a new user to make a registration process, not created by admin. A verification via email should be fantastic.
    There is no a very clear tutorials about this in other website

  14. Hello Sir,
    Sorry for spamming your website,

    Just wanna let you know that (and maybe other user who is seeking the same thing as i did), i already successfully created a Register page.
    How it works is very similar to function create() inside controllers/admin/Users.php, at the end of the function, it calls ION AUTH register() function.
    Thanks

  15. Thank you for this tutorial.
    after following the step the login display but if i login its will refresh and display 404 error .
    Please am newbie to codeigniter i need your help

  16. I finished this step: thanks for your tutorial…
    Just a note: with ‘refresh’ it does not work: it returns a white (empty) page.
    Without this parameter, it’s works well.
    I don’t know why. but not very important cause it work.

      1. Hello, just to know if you have any other ideas about my problem.

        Maybe is problem of my Apache (I use WAMP)

        Thank you for your support

        🙂

    1. I do not understand. What do you mean when you say “is not working for post requests”? Ion Auth has nothing to do with post requests, you pass it the values from controllers.

  17. is there a way to remove the /user/ from the login process? So essentially it would be localhost/login rather than localhost/user/login…You have published some great tutorials on this site and I would also like to take the time to thank you for that!

    1. Of course. You can open application/config/routes.php (or maybe you’ve put routes in an environment directory) and create a route

      $route[‘login’] = ‘user/login’;

        1. You’re welcome. The “Buy me a coffee” button is in the sidebar 😉 …or at least disable any adblock you have enabled for my site 🙂

  18. Hi Avenir,

    Im learning & following your tutorial until this stage.
    But, i have an issue here. after submit a log in it always back to login form.
    is there any clue about this ?

    thanks. 🙂

    1. I have no clue unless you send me your code. Usually the redirection comes if what the visitor entered didn’t pass the validation rules.

  19. Hi, guys!
    I fixed that “Error Number: 1064” issue, it was simpler than usually these things can be!
    I got some free time yesterday to check things out, and the code was perfect, both in my App and in the tutorial clone…
    So out of options, I’ve decided to look into an obvious hint: “Mysql error[..]”. Then that little cog began to turn inside my head: collation and the sorts in the database!
    Since my server has default lang as pt_BR, it uses latin-1 as collations. I’ve dumped the database .sql script, dropped it, changed to utf8 and utf8_something_ci it’s collation…
    Now it’s working like a charm!
    Just a little reminder that the error can be into small details, and it will sure bug you!

    Great tutorial, BTW!

  20. Hi Avenir,

    I keep getting an error

    ” The configuration file ion_auth.php does not exist.”

    Checked the sessions, changed the ion_auth , checked hooks and unused them also but not changes ..
    Any pointers please?

    Thanks alot

    1. Well… did you make sure you have the ion_auth.php configuration file inside application/config directory?

  21. Hello Avenirer,

    thanks for this tutorial !
    Sorry if someone already asked this question…
    If I well understand, your user.php controller with login and logout classes can only work if you have only one page to display (admin page).
    My concerne is that I have multiple pages which require an authentication. How can I handle that with your authentication method ?
    thank you very much !

      1. hello and thanks for your quick reply !
        I’m not sur to understand your answer :-)…
        the problem is that on your login() function you perform a redirect(‘admin’, ‘refresh’);
        The problem I have is that “admin” is one of my multiple pages I have. Do I have to create a “user.php” page for each other pages where I need a authentication ?
        Hope I’m understandable 😉

        1. Oh… you are referring to the redirect… OK… Let’s suppose a member (a user which is inside the “members” group) logged in. Also another user which is part of the “special” group logged in. You want to redirect them depending on the group they are part of… You simply do an if/else block:
          if($this->ion_auth->in_group(“special”))
          {
          redirect(‘aspecialcontroller’);
          }
          elseif($this->ion_auth->in_group(“members”))
          {
          redirect(‘amemberscontroller’);
          }
          else
          {
          redirect(”);
          }

          Does it make sense?

          1. the pages a user will be redirected to doesn’t depend on the group it belongs to.
            Let say I have 4 html pages. Page1 and Page2 requiere an authentication, but not Page3 and Page4.
            How can I redirect to Page1 or Page2 when an user authenticates ? May be I have to record the page name he tried to access in a session variable and use it to redirect ?

          2. Yes, you do have to save that inside a session variable. Inside a Page1 and Page2 you verify if the user is member of that group. If it’s not, you save two session variables: one that represents the url and one that represents the group name that the user must be part of in order to access the url. After that you redirect the user to the unique login page. If the user logs in and is part of the group saved inside the session, you redirect him/her to the url that is also saved inside the session variable. If he is not part of that group you simply redirect him to a default page (maybe with a message that he is not part of the group needed in order to access that specific url).

  22. Ok thank you. This is what I wanted to do but unfortunately I still have a problem with codeigntier session.
    in my page1 controller __contruct function I assign “page1” to $_SESSION[‘sourcePage’] to record the source page.
    The authentication procedure works fine but redirect to home page. I do a isset test on the $_SESSION[‘sourcePage’] variable. If it’s empt I redirect to the homepage.
    Even if I correctly fill this session variable, it seems to be lost in the login controller function.
    I search on internet and it seems that tere’s a lot of troubles with session variables with codeigniter. Are you aware about that ? Any advise ?

    1. I don’t know any “lot of troubles” with session variables within CodeIgniter. Usually the problems appear because people do not configure the sessions correctly. Could you give me a link with people complaining about these “troubles”? Also if you still have problems we can chat on hangouts. My address is avenir.ro@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.