Register users using Ion Auth in CodeIgniter 3

What we will learn in this episode

OK… We’ve installed Ion Auth and made the login page. How about allowing users to register an account? In this tutorial we will find out how we can use Ion Auth in order to allow users to register for an account. After this we will see how to change the controller so that only administrators can register new users.

Again about the configuration

For starters, we need to return to our configuration file (application/config/ion_auth.php). For this tutorial we will need to start by changing it a bit (or at least make sure they are set as below), specifically the $config[’email_activation’] and $config[‘manual_activation’]. We will set both to FALSE. Also we must make sure that the default group is not the “admin”. You don’t want everyone to have a word to say about your own site. So make sure that $config[‘default_group’] is set to “members”.

Creating the Register controller

After this we will need a new controller. So let us create a file named Register.php inside application/controllers directory:

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

class Register extends MY_Controller
{

    public function index()
    {
	$this->load->helper('form');
        $this->render('register/index_view');
    }
}

As you can see, the controller (the class) extends MY_Controller and not Auth_Controller, as this area must be accessed by every user, not the authenticated ones.

The controller calls an index_view, so let’s also create a file named index_view.php inside application/views/register directory (which, by the way, we must create):

<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<div class="container">
    <?php
    echo isset($_SESSION['auth_message']) ? $_SESSION['auth_message'] : FALSE;
    ?>
    <h1>Register</h1>
    <?php
    echo form_open();
    echo form_label('First name:','first_name').'<br />';
    echo form_error('first_name');
    echo form_input('first_name',set_value('first_name')).'<br />';
    echo form_label('Last name:','last_name').'<br />';
    echo form_error('last_name');
    echo form_input('last_name',set_value('last_name')).'<br />';
    echo form_label('Username:','username').'<br />';
    echo form_error('username');
    echo form_input('username',set_value('username')).'<br />';
    echo form_label('Email:','email').'<br />';
    echo form_error('email');
    echo form_input('email',set_value('email')).'<br />';
    echo form_label('Password:', 'password').'<br />';
    echo form_error('password');
    echo form_password('password').'<br />';
    echo form_label('Confirm password:', 'confirm_password').'<br />';
    echo form_error('confirm_password');
    echo form_password('confirm_password').'<br /><br />';
    echo form_submit('register','Register');
    echo form_close();
    ?>
</div>

Of course, you can set any sort of fields, as long as these fields are also in your database table. By the way… you can even delete the “company” and “phone” fields from the “users” table, as we won’t need them in this tutorial.

Now let’s return to our controller and do the form validations. We start of course by loading the form validation library first.

$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name','trim|required');
$this->form_validation->set_rules('last_name', 'Last name','trim|required');
$this->form_validation->set_rules('username','Username','trim|required|is_unique[users.username]');
$this->form_validation->set_rules('email','Email','trim|valid_email|required');
$this->form_validation->set_rules('password','Password','trim|min_length[8]|max_length[20]|required');
$this->form_validation->set_rules('confirm_password','Confirm password','trim|matches[password]|required');

As you can see, almost all the form fields are required… What can I say… I like to feel like NSA.

Also, the username must be unique as this field is the field that uniquely identifies the users. You can also force the users to have a unique email, so that no two users can have same email. I didn’t want to enforce that in here, but you are free to do whatever you feel like.

What about the password? Why set a minimum length of 8 characters and a maximum length of 20? If you look into the configuration file (application/config/ion_auth.php), you will find two configuration parameters:

$config['min_password_length'] = 8;
$config['max_password_length'] = 20;

That means that if we didn’t set the length rules in our validation forms, the library would have sent the users the errors because they didn’t respect their requests.

We also need to make sure the users know what password they chose by putting them to retype their chosen password and verifying that the two passwords are the same.

The validation and… the registration

Now… if the validation was unsuccessful we will render the form, and if was successful we register them. If you take a look at the Ion Auth manual (http://benedmunds.com/ion_auth/#register), you will see that in order to create a user we call the register() method (or the create_user() method, which is an alias of register()).

The register() method accepts minimum three parameters, but can also receive four parameters. The parameters that must be completed are the identity, the password, the email. The optional parameters must be an array with additional data (in our case the first and the last name, and also any other fields you added in the form), and the group in which we want to insert the user. If we do not mention a group in which the user should be inserted, the library will use the default group which in our case is the “members” group. So let’s do the logic:

if($this->form_validation->run()===FALSE)
{
	$this->load->helper('form');
	$this->render('register/index_view');
}
else
{
	$first_name = $this->input->post('first_name');
	$last_name = $this->input->post('last_name');
	$username = $this->input->post('first_name');
	$email = $this->input->post('email');
	$password = $this->input->post('first_name');

	$additional_data = array(
		'first_name' => $first_name,
		'last_name' => $last_name
	);

	$this->load->library('ion_auth');
	if($this->ion_auth->register($username,$password,$email,$additional_data))
	{
		$_SESSION['auth_message'] = 'The account has been created. You may now login.';
		$this->session->mark_as_flash('auth_message');
		redirect('user/login');
	}
	else
	{
		$_SESSION['auth_message'] = $this->ion_auth->errors();
		$this->session->mark_as_flash('auth_message');
		redirect('register');
	}
}

OK… Now let us see the Register controller in its entirety:

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

class Register extends MY_Controller
{

    public function index()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('first_name', 'First name','trim|required');
        $this->form_validation->set_rules('last_name', 'Last name','trim|required');
        $this->form_validation->set_rules('username','Username','trim|required|is_unique[users.username]');
        $this->form_validation->set_rules('email','Email','trim|valid_email|required');
        $this->form_validation->set_rules('password','Password','trim|min_length[8]|max_length[20]|required');
        $this->form_validation->set_rules('confirm_password','Confirm password','trim|matches[password]|required');

        if($this->form_validation->run()===FALSE)
        {
            $this->load->helper('form');
            $this->render('register/index_view');
        }
        else
        {
            $first_name = $this->input->post('first_name');
            $last_name = $this->input->post('last_name');
            $username = $this->input->post('username');
            $email = $this->input->post('email');
            $password = $this->input->post('password');

            $additional_data = array(
                'first_name' => $first_name,
                'last_name' => $last_name
            );

            $this->load->library('ion_auth');
            if($this->ion_auth->register($username,$password,$email,$additional_data))
            {
                $_SESSION['auth_message'] = 'The account has been created. You may now login.';
                $this->session->mark_as_flash('auth_message');
                redirect('user/login');
            }
            else
            {
                $_SESSION['auth_message'] = $this->ion_auth->errors();
                $this->session->mark_as_flash('auth_message');
                redirect('register');
            }
        }
    }
}

And that’s it. Now, if you want to register a new user, you simply go to http://localhost/register and fill the form.

The GOD MODE

“What in the hell is GOD MODE?”, you may ask (do you like the way I said hell and God in same sentence?…).

There are times when we don’t want users to create on their own accounts. We only want the admins to create accounts. So how can we change the controller so that only admins can register new users? First of all we must make sure that only authenticated users reach the “register” page. In order to make this possible, instead of letting the controller extend MY_Controller, we make it extend the Auth_Controller:

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

class Register extends Auth_Controller
{
   ...
}

Now, if we visit the “register” page we will be redirected to the “login” page. So let us login with “administrator” username and “password” password… After login, we can visit the “register” page. And yet… that means that all authenticated users can access the “register” page. So how are we going about this problem? As you remember the default group in which we insert users is “members”. But “administrator” is in “admin” group. So why not only let those that are in admin group to register new members?

Ion Auth thought of that and created a method called is_admin(), which is verifying if a user is an administrator or not. How does the library know what group is the administrators group? It finds out from our configuration file (application/config/ion_auth.php). You will find in there the following line: $config[‘admin_group’] = ‘admin’; . So, if you want to have another group be the admin group you must change it in here too.

So… we want the whole controller to be accessible only to administrators. Why not use the constructor to verify if a user is an administrator and only if he/she is to allow them to use the controller?

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

class Register extends Auth_Controller
{
	function __construct()
        {
            parent::__construct();
            $this->load->library('ion_auth');
            if($this->ion_auth->is_admin()===FALSE)
        {
            redirect('/');
        }
    }
	
	...
}

Now only those that are administrators can access the “register” page.

Leave a Reply

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

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