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

Created at: January 30, 2015; Last update: February 5, 2015

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?

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:

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:

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:

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:

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:

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:

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:

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

71 thoughts on “Step 3.1 – Creating the login and logout page with Ion Auth

    1. avenirer Post author

      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

      Reply
      1. vaibhav

        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

        Reply
  1. jessmoi

    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.

    Reply
    1. avenirer Post author

      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. 🙂

      Reply
      1. jessmoi

        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.

        Reply
        1. avenirer Post author

          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?

          Reply
  2. Tagged

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

    Thank You!

    Reply
  3. suon samoun

    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?

    Reply
  4. Federico

    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

    Reply
  5. John

    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..

    Reply
    1. avenirer Post author

      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 🙂

      Reply
  6. itay joseph

    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?

    Reply
    1. avenirer Post author

      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 🙂

      Reply
  7. Aiden

    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

    Reply
    1. avenirer Post author

      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

      Reply
  8. aleix

    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.

    Reply
    1. avenirer Post author

      You are right… I always wanted to verify what happens in there, but never found the time. Will look into it.

      Reply
  9. fxf999

    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

    Reply
        1. fxf999

          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.

          Reply
          1. fxf999

            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. fxf999

    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.

    Reply
  11. fxf999

    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.

    Reply
  12. Integrator

    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

    Reply
      1. Integrator

        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

        Reply
          1. Eduardo

            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. avenirer Post author

            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. fxf999

    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

    Reply
  14. fxf999

    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

    Reply
  15. Yeye

    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

    Reply
  16. nanart

    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.

    Reply
    1. avenirer Post author

      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.

      Reply
  17. Lewis Wright

    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!

    Reply
    1. avenirer Post author

      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’;

      Reply
        1. avenirer Post author

          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 🙂

          Reply
  18. arie

    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. 🙂

    Reply
    1. avenirer Post author

      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.

      Reply
  19. Eduardo

    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!

    Reply
  20. Emmanuel

    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

    Reply
    1. avenirer Post author

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

      Reply
  21. cedric

    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 !

    Reply
    1. avenirer Post author

      You simply use the groups whenever you need to allow access to different parts of your website.

      Reply
      1. cedric

        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 😉

        Reply
        1. avenirer Post author

          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?

          Reply
          1. cedric

            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. avenirer Post author

            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. cedric

    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 ?

    Reply
    1. avenirer Post author

      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

      Reply

Leave a Reply

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

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