CodeIgniter 4 Tutorial- Authentication Login And Registration Example

CodeIgniter Authentication System Tutorial

Friends, if you are not having ample knowledge of how to create a basic CodeIgniter Authentication System, then surely you are going to get help from this tutorial.

In this guide, we will get to know to create a simple authentication system with login and signup functionalities. Most of us very well know that login is a process in which the user logs into the application using a registered email and password. After he has successfully logged in, he can further access the resources of the application. Whereas, signup is the process where the user registers himself using the name, email and password properties.

CodeIgniter 4 Authentication (Sign in And Sign up) System Example

Step 1- Create CodeIgniter Project

Step 2- Display Errors

Step 3- Generate Table Into Database

Step 4- Connect CI To Database

Step 5- Create And Update User Model

Step 6- Register Auth Controllers

Step 7-Create Auth View

Step 8- Protect Route With Filter

Step 9- Run CI Application

 

Create CodeIgniter Project

The very first step is to download the CodeIgniter app which we can do by two methods.

One method is to invoke the given command after we have configured the Composer in our system:

composer create-project codeigniter4/appstarter

In the second method, we simply visit the CodeIgniter site and download the CI app.

https://codeigniter.com/download

 

Display Errors

We can turn on the feature to errors, go to the app/Config/Boot/production.php and change display_errors prop value to 1 from 0.

ini_set('display_errors', '1');

 

Generate Table Into Database

The primary archetype of auth table contains users table in the database with like name, email, password and created_at properties. Head over to PHPMyAdmin, type the given SQL query and hit enter.

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(150),
    email VARCHAR(150),
    password VARCHAR(150),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;

 

Connect CI To Database

The below step shows to connect CI app to the database, its facile process, add the database name and password in the app/Config/Database.php:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

 

Create And Update User Model

Here, in this step, we have to create a new model file and then define the user table name and also the values in the $table and $allowedFields. Afterward, we create UserModel.php file in the app/Models folder. Then, we have to update the below code in the app/Models/UserModel.php file:

<?php 

namespace App\Models;  
use CodeIgniter\Model;

  
class UserModel extends Model{

    protected $table = 'users';
    
    protected $allowedFields = [
        'name',
        'email',
        'password',
        'created_at'
    ];

}

 

Register Auth Controllers

A controller is a file that holds the functions and methods used to handle the application’s business logic. In this step, you have to create Signup and Signin controller files.

Create SignupController.php file in the app/Controllers directory. Then, insert the below code into the app/Controllers/SignupController.php file:

<?php 

namespace App\Controllers;  
use CodeIgniter\Controller;
use App\Models\UserModel;
  
class SignupController extends Controller
{
    public function index()
    {
        helper(['form']);
        $data = [];
        echo view('signup', $data);
    }
  
    public function store()
    {
        helper(['form']);
        $rules = [
            'name'          => 'required|min_length[2]|max_length[50]',
            'email'         => 'required|min_length[4]|max_length[100]|valid_email|is_unique[users.email]',
            'password'      => 'required|min_length[4]|max_length[50]',
            'confirmpassword'  => 'matches[password]'
        ];
          
        if($this->validate($rules)){
            $userModel = new UserModel();

            $data = [
                'name'     => $this->request->getVar('name'),
                'email'    => $this->request->getVar('email'),
                'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
            ];

            $userModel->save($data);

            return redirect()->to('/signin');
        }else{
            $data['validation'] = $this->validator;
            echo view('signup', $data);
        }
          
    }
  
}

 

Lastly, we create SigninController.php file in the app/Controllers directory and then, insert the below code into the app/Controllers/SigninController.php file:

<?php 

namespace App\Controllers;  
use CodeIgniter\Controller;
use App\Models\UserModel;
  

class SigninController extends Controller
{
    public function index()
    {
        helper(['form']);
        echo view('signin');
    } 
  
    public function loginAuth()
    {
        $session = session();

        $userModel = new UserModel();

        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        
        $data = $userModel->where('email', $email)->first();
        
        if($data){
            $pass = $data['password'];
            $authenticatePassword = password_verify($password, $pass);
            if($authenticatePassword){
                $ses_data = [
                    'id' => $data['id'],
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'isLoggedIn' => TRUE
                ];

                $session->set($ses_data);
                return redirect()->to('/profile');
            
            }else{
                $session->setFlashdata('msg', 'Password is incorrect.');
                return redirect()->to('/signin');
            }

        }else{
            $session->setFlashdata('msg', 'Email does not exist.');
            return redirect()->to('/signin');
        }
    }
}

 

Create Auth View Templates

Since, we have to define the view files, do remember to get inside the app/Views folder and create signin.php and signup.php files. These files will be used for login and user registration in CodeIgniter.

We have to create the user registration form using Bootstrap 5 and tie with the methods to handle the user registration. After that, we open and place the code in the app/View/signup.php file:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <title>Codeigniter Auth User Registration Example</title>
</head>

<body>
    <div class="container mt-5">
        <div class="row justify-content-md-center">
            <div class="col-5">
                <h2>Register User</h2>

                <?php if(isset($validation)):?>
                <div class="alert alert-warning">
                   <?= $validation->listErrors() ?>
                </div>
                <?php endif;?>

                <form action="<?php echo base_url(); ?>/SignupController/store" method="post">
                    <div class="form-group mb-3">
                        <input type="text" name="name" placeholder="Name" value="<?= set_value('name') ?>" class="form-control" >
                    </div>

                    <div class="form-group mb-3">
                        <input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
                    </div>

                    <div class="form-group mb-3">
                        <input type="password" name="password" placeholder="Password" class="form-control" >
                    </div>

                    <div class="form-group mb-3">
                        <input type="password" name="confirmpassword" placeholder="Confirm Password" class="form-control" >
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn btn-dark">Signup</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>

</html>

Further, we open and place the given code in the app/View/signin.php file:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <title>Codeigniter Login with Email/Password Example</title>
  </head>
  <body>
    <div class="container">
        <div class="row justify-content-md-center">
            <div class="col-5">
                
                <h2>Login in</h2>
                
                <?php if(session()->getFlashdata('msg')):?>
                    <div class="alert alert-warning">
                       <?= session()->getFlashdata('msg') ?>
                    </div>
                <?php endif;?>

                <form action="<?php echo base_url(); ?>/SigninController/loginAuth" method="post">
                    <div class="form-group mb-3">
                        <input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
                    </div>

                    <div class="form-group mb-3">
                        <input type="password" name="password" placeholder="Password" class="form-control" >
                    </div>
                    
                    <div class="d-grid">
                         <button type="submit" class="btn btn-success">Signin</button>
                    </div>     
                </form>
            </div>
              
        </div>
    </div>
  </body>
</html>

 

Set + Protect Routes With Filter

In this step, we will get inside the app/Config/Filters.php, look for $aliases array and replace the whole array with the recommended code:

/**
	 * Configures aliases for Filter classes to
	 * make reading things nicer and simpler.
	 *
	*/

	public $aliases = [
		'csrf'     => \CodeIgniter\Filters\CSRF::class,
		'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
		'honeypot' => \CodeIgniter\Filters\Honeypot::class,
		'authGuard' => \App\Filters\AuthGuard::class,
	];

 

In this step, we have to create an AuthGuard.php file inside the app/Filters folder. This file will check if the user is logged in and redirect to the signing page if the user is not signed in.

Open and add the code in the app/Filters/AuthGuard.php file:

<?php 

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;


class AuthGuard implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (!session()->get('isLoggedIn'))
        {
            return redirect()
                ->to('/signin');
        }
    }
    
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        
    }
}

In this step, we will move towards routes file to create routes, we need to set routes to execute the controller functions. Likewise, we protect the profile route which will be restricted for unauthenticated users.

Get into the app/Config/Routes.php file and define the given routes into the file:

// custom routes

$routes->get('/', 'SignupController::index');
$routes->get('/signup', 'SignupController::index');
$routes->get('/signin', 'SigninController::index');
$routes->get('/profile', 'ProfileController::index',['filter' => 'authGuard']);

 

Run CI Application

Since we have reached the last step of this tutorial, we will use the below code for running the CI app:

php spark serve

 

Summary

So, friends, we have seen in this guide how to implement or build auth system in CideIgniter 4 app.

We have learned how to create login or signing and registration or signup features in the CI app.

 

Thanks

Leave a Reply

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