Securing Admin Login in CodeIgniter 4
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
- Create a Database: Create a new database (e.g.,
ci4_admin
). - 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
- Generate the Controller: Create
Auth.php
in theapp/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
- Create UserModel: In
app/Models
, createUserModel.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
- Create the Login View: In
app/Views/auth
, createlogin.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
- 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
- Create an Auth Filter: In
app/Filters
, createAuthFilter.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
- 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!