CodeIgniter 4 Authorization tutorial in English, a way to create a custom middleware and protect zones of our application
CodeIgniter 4 Roles and Privileges
In this tutorial we are going to manage the roles and privileges, for two types of users called administrator and normal user, first we proceed to create the trait
namespace App\Traits;
trait MiddlewareAuthorization
{
public function checkAdmin()
{
if ($this->session->get('id_role') == 2 || $this->session->get('id_role') == null ) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
}
public function checkUser()
{
if ($this->session->get('id_role') == 1 || $this->session->get('id_role') == null ) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
}
}
CodeIgniter 4 Exceptions – Implementation
We will use the session library of codeigniter in its version 4 and the exceptions of the framework
namespace App\Controllers;
use App\Traits\Authorization;
class Dashboard extends BaseController
{
use MiddlewareAuthorization;
public function __construct()
{
$this->session = \Config\Services::session();
$this->checkAdmin();
}
public function index()
{
$data['title'] = 'Dashboard';
return view('admin/dashboard',$data);
}
}
Then we will add the checkAdmin() or checkUser() method in the zone that we want to protect, in this example the role with the id number 2 corresponds to an administrator and the role number 1 corresponds to a user, if this condition is not met we will display an exception with a view 404, first remember to create a login here is an article that may interest you
Migrations – Integration
Finally, for this structure to work, it is necessary to create a table with our migrations, we will add the following code
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
$this->forge->addField([
'id_user' => [
'type' => 'INT',
'auto_increment' => TRUE
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '50',
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '50',
'unique' => true,
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'id_role' => [
'type' => 'INT',
'constraint' => '11',
],
]);
$this->forge->addKey('id_user', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}
In this was an example of how to apply CodeIgniter 4 Authorization