CodeIgniter 4 Authentication – Create a Login

CodeIgniter 4 Authentication

In this article we will see how to create authentication in codeigniter 4 and how to implement the models (models), we will create a small custom access system.

How to create custom authentication in Codeigniter 4?

First it is necessary to create a controller called login, if you do not know the basic concepts of this framework read the following article CodeIgniter 4 Tutorial .

php spark make:controller Login

Which will create the base structure of a controller in codeigniter 4, we will work with a controller called Login, where we will add the following code, where we will work with Forms in CodeIgniter 4 .


        namespace App\Controllers;

        use App\Models\UserModel;

        use App\Traits\Auth;

        class Login extends BaseController
        {

            use Auth;

            protected $UserModel;

            protected $session;


            public function __construct()
            {

                $this->UserModel = new UserModel();


                helper(['form', 'url']);


                $this->session = \Config\Services::session();

            }

            public function index()
            {       

                $data['tittle'] = 'Login';

                $data['session'] = $this->session;

                return view('login',$data);

            }   


            public function sign()
            {       

                $email = $this->request->getPost('email');
                $password = $this->request->getPost('password');

                if ($this->checkUser($email,$password)) {


                $this->setSession($email);


                if ($this->session->get('role_id') == 1) {



                    return redirect()->to('/dashboard');

                }

                }else{

                $this->session->setFlashdata('credentials','Invalid credentials');

                return redirect()->to('/');     

            }




            }


            public function out()
            {       

                $this->session->destroy(); 

                return redirect()->to('/');
            }


        }
        

How to implement the models (models) in CodeIgniter?

You need to create a model to validate the required fields and add the following code.


        namespace App\Models;

        use CodeIgniter\Model;

        class UserModel extends Model
        {

            protected $table = 'users';

            protected $primaryKey = 'user_id';

            protected $returnType = 'object';  

            protected $allowedFields = ['img','first_name','last_name','email','password'];

            protected $validationRules = [
                'first_name' => 'required',
                'last_name' => 'required',
                'email' => 'required',
                'password' => 'required'
            ];              


        }
        

We will create 1 trait in nameProject / app / Traits / Auth.php , which will handle the logic when working with sessions and validating user data.

with the method checkuser () We will validate that the user’s mail exists in our table, with the method verifyHash ()  will return true or false if the password submitted by the form matches the hash of the users table and the method setSession () We will start a session with the user data, additionally you can read this article to create an Authorization


        namespace App\Traits;

        trait Auth
        {   

            public function checkUser($email, $password)  
            {   

                $hash = $this->UserModel->where('email',$email)
                ->findColumn('password');

                return $this->verifyHash($password,$hash[0]);


            }

            public function verifyHash($password,$hash )
            {
                return password_verify($password,$hash);

            }


            public function setSession($email)
            {       

                $data = $this->UserModel->where('email',$email)
                ->findAll();

                $data=array(
                    'user_id' => $data[0]->user_id,        
                    'first_name' => $data[0]->first_name,
                    'last_name' =>  $data[0]->last_name,   
                    'email' => $data[0]->email,        
                    'role_id' => $data[0]->role_id                             
                );  


                return $this->session->set($data);

            }
        }
        

After finishing the logic, we will be redirected to the control panel, you need to create this file.

CodeIgniter 4 Authentication Dashboard We have a repository at github, where what is learned in this post is applied.

Author