Securing Admin Login in CodeIgniter 4

Yash Kumar Prasad
3 min readNov 4, 2024

--

Introduction

Setting up an admin login system is an essential step in developing secure web applications. In CodeIgniter 4, you can enhance your admin login by implementing filters to restrict access to specific routes. This guide will walk you through the process of setting up an admin login system and incorporating filters for added security.

Prerequisites

Before you begin, ensure you have:

  • Basic knowledge of PHP and CodeIgniter 4
  • A local development environment (e.g., XAMPP, WAMP)
  • CodeIgniter 4 installed and configured

Step 1: Database Setup

  1. Create a Database: Create a new database (e.g., ci4_admin).
  2. Create the Users Table: Run the following SQL query to create a users table:
CREATE TABLE users (     id INT AUTO_INCREMENT PRIMARY KEY,     username VARCHAR(50) NOT NULL UNIQUE,     password VARCHAR(255) NOT NULL,     role ENUM('admin', 'user') NOT NULL DEFAULT 'user',     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );

3. Insert a Sample Admin User: Add a sample admin user for testing:

INSERT INTO users (username, password, role) VALUES ('admin', '$2y$10$EIXxZT0tJqYt3IYVg7mDeO3Rk46GxfjRmb5FV0Prz/M5RhHpZp8Za', 'admin');

(Use password_hash() in PHP to generate hashed passwords.)

Step 2: Create the Login Controller

  1. Generate the Controller: Create Auth.php in the app/Controllers directory.
namespace App\Controllers;

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

class Auth extends Controller
{
public function login()
{
return view('auth/login');
}

public function loginProcess()
{
$session = session();
$model = new UserModel();
$username = $this->request->getPost('username');
$password = $this->request->getPost('password');

$user = $model->where('username', $username)->first();

if ($user && password_verify($password, $user['password'])) {
$session->set('isLoggedIn', true);
$session->set('username', $user['username']);
return redirect()->to('/dashboard');
} else {
$session->setFlashdata('msg', 'Invalid username or password');
return redirect()->to('/login');
}
}

public function logout()
{
$session = session();
$session->destroy();
return redirect()->to('/login');
}
}

Step 3: Create the User Model

  1. Create UserModel: In app/Models, create UserModel.php.
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['username', 'password', 'role'];
}

Step 4: Create the Login View

  1. Create the Login View: In app/Views/auth, create login.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Login</title>
</head>
<body>
<h1>Admin Login</h1>
<?php if(session()->getFlashdata('msg')): ?>
<div><?php echo session()->getFlashdata('msg'); ?></div>
<?php endif; ?>
<form action="/loginProcess" method="post">
<label for="username">Username:</label>
<input type="text" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>

Step 5: Define Routes

  1. Update Routes: Open app/Config/Routes.php and add routes for login and logout.
$routes->get('/login', 'Auth::login');
$routes->post('/loginProcess', 'Auth::loginProcess');
$routes->get('/logout', 'Auth::logout');

Step 6: Create Filters

  1. Create an Auth Filter: In app/Filters, create AuthFilter.php.
namespace App\Filters;

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

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

public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something after the request
}
}

2. Register the Filter: Open app/Config/Filters.php and register your new filter.

public $aliases = [
'auth' => \App\Filters\AuthFilter::class,
];

3. Apply the Filter to Routes: In app/Config/Routes.php, apply the filter to the dashboard route.

$routes->get('/dashboard', 'Dashboard::index', ['filter' => 'auth']);

Step 7: Create a Protected Dashboard

  1. Create a Dashboard Controller: Generate a Dashboard.php controller.
namespace App\Controllers;

use CodeIgniter\Controller;

class Dashboard extends Controller
{
public function index()
{
return view('dashboard');
}
}

2. Create Dashboard View: Create dashboard.php in app/Views.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
</head>
<body>
<h1>Welcome to the Admin Dashboard</h1>
<p>Hello, <?= session()->get('username') ?>!</p>
<a href="/logout">Logout</a>
</body>
</html>

Conclusion

You now have a secure admin login system in CodeIgniter 4 with filters to protect your dashboard route. This setup ensures that only authenticated users can access the admin area. As you continue developing, consider adding features such as password recovery, user role management, and other security measures to enhance your application.

Feel free to customize and expand this implementation to suit your project needs. Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.

No responses yet

Write a response