Creating a Secure Authentication System in CodeIgniter 4: A Comprehensive Guide

 

Introduction

Security is a top priority in web development, especially when it comes to handling user authentication. In CodeIgniter 4, creating a secure authentication system is not only essential for protecting user data but also for ensuring a smooth user experience. In this comprehensive guide, we'll walk you through the process of building a secure authentication system in CodeIgniter 4, including best practices for managing sessions, implementing auto-login, and adding a screen lock feature.


Setting Up Authentication in CodeIgniter 4

1. Installing CodeIgniter 4

Before diving into authentication, make sure you have CodeIgniter 4 installed and set up. If you haven't installed it yet, you can do so using Composer:

bash

composer create-project codeigniter4/appstarter myApp

Once installed, set up your database connection in the .env file, and run the necessary migrations to create your users table.

2. Creating the User Model

To manage user data, you’ll need a User model. This model will interact with your users table, handling user creation, retrieval, and authentication.

php

namespace App\Models; use CodeIgniter\Model; class UserModel extends Model { protected $table = 'users'; protected $allowedFields = ['username', 'email', 'password', 'pin', 'is_active']; protected $beforeInsert = ['hashPassword']; protected $beforeUpdate = ['hashPassword']; protected function hashPassword(array $data) { if (isset($data['data']['password'])) { $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT); } return $data; } }

Implementing Auto-Login and Session Management

1. Auto-Login Feature

The auto-login feature allows users to stay logged in across sessions without re-entering their credentials. This is achieved by storing a secure token in a cookie that the server verifies upon each request.

  • Storing the Token:
php

public function login() { $user = $this->userModel->where('email', $this->request->getVar('email'))->first(); if ($user && password_verify($this->request->getVar('password'), $user['password'])) { $session = session(); $session->set(['user_id' => $user['id']]); if ($this->request->getVar('remember_me')) { $token = bin2hex(random_bytes(16)); set_cookie('auto_login', $token, 604800); // 7 days $this->userModel->update($user['id'], ['auto_login_token' => hash('sha256', $token)]); } return redirect()->to('/dashboard'); } return redirect()->back()->withInput()->with('error', 'Invalid login credentials.'); }
  • Verifying the Token:
php

public function autoLogin() { $token = get_cookie('auto_login'); if ($token) { $user = $this->userModel->where('auto_login_token', hash('sha256', $token))->first(); if ($user) { session()->set(['user_id' => $user['id']]); return redirect()->to('/dashboard'); } } return redirect()->to('/login'); }

2. Session Management

Managing sessions securely is crucial for protecting user data. In CodeIgniter 4, you can configure session settings in the Config/App.php file to enhance security.

  • Setting a Custom Session Driver: Configure a database session driver for better security:
php

public $sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler';

Adding a Screen Lock Feature

1. Implementing the Screen Lock

The screen lock feature enhances security by locking the screen after a period of inactivity or when triggered manually. Users will need to enter a PIN to unlock it.

  • Lock Screen Trigger:
javascript

let lockTimer; document.addEventListener('mousemove', resetTimer); document.addEventListener('keypress', resetTimer); function resetTimer() { clearTimeout(lockTimer); lockTimer = setTimeout(lockScreen, 300000); // 5 minutes } function lockScreen() { window.location.href = '/lock'; }
  • Lock Screen View:
php

public function lock() { echo view('lock_screen'); } public function unlock() { $pin = $this->request->getVar('pin'); $user = $this->userModel->find(session()->get('user_id')); if ($user['pin'] === $pin) { return redirect()->to('/dashboard'); } return redirect()->back()->with('error', 'Invalid PIN.'); }
  • Lock Screen View (HTML):
html

<form action="/unlock" method="post"> <label for="pin">Enter PIN:</label> <input type="password" name="pin" id="pin" required> <button type="submit">Unlock</button> </form>

Conclusion

Building a secure authentication system in CodeIgniter 4 involves careful planning and the implementation of best practices. By setting up auto-login, managing sessions securely, and adding a screen lock feature, you can enhance the security of your application and protect user data. Remember, security is an ongoing process, so keep your system updated and regularly review your security measures to stay ahead of potential threats.

Comments

Popular posts from this blog

CSS Animations and Transitions

Enhancing User Experience with Bootstrap’s JavaScript Components: A Practical Guide

Creating Stunning Landing Pages with Bootstrap: Tips and Best Practices