Codeigniter Shield Authorization
CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provides a flexible role-based access control (RBAC) system, allowing you to manage user permissions effectively.
Key Concepts:
Groups: Users can belong to multiple groups, which can represent traditional roles (e.g., admin, moderator) or be used to group users based on features or other criteria.
Permissions: Permissions define what actions a user is allowed to perform within your application. Permissions are typically associated with groups.
Users: Each user has a set of permissions based on the groups they belong to, and can also have permissions directly assigned to them.
Defining Groups:
Groups are defined in the Shield\Config\AuthGroups configuration file. Each group has a key, a title, and an optional description.
php
public array $groups = [
'superadmin' => [
'title' => 'Super Admin',
'description' => 'Optional description of the group.',
],
'editor' => [
'title' => 'Editor',
'description' => 'Can edit content.'
],
'user' => [
'title' => 'User',
'description' => 'Basic user access.'
]
];
Defining Permissions:
php
public array $permissions = [ 'superadmin.access' => 'Can access the sites admin area', 'superadmin.settings' => 'Can access the main site settings', 'editor.create' => 'Can view/edit site content', 'users.create' => 'Can create new non-admin users', 'users.edit' => 'Can edit existing non-admin users', 'users.delete' => 'Can delete existing non-admin users', ];
Checking Permissions:
You can check if a user has a specific permission using the can() method on the User entity. This method checks permissions within the groups the user belongs to, as well as any permissions directly assigned to the user.
php
if (! auth()->user()->can('users.create')) {
return redirect()->back()->with('error', 'You do not have permissions to access that page.');
}
Example:
Let's say you have a 'superadmin' group with the permission users.create. You can check if the current user has this permission like this:
php
if (auth()->user()->can('users.create')) {
// Allow user to create a new user
} else {
// Redirect or show an error message
}
Getting the Current User:
You can get the current user using the auth() helper function:
php
$user = auth()->user();
Adding Group To a User:
php
$user = auth()->user();
$user->addGroup('superadmin', 'editor');
Removing Group From a User:
php
$user = auth()->user();
$user->removeGroup('superadmin', 'editor');
Check if User Belongs to a Group:
php
$user = auth()->user(); if ($user->inGroup('superadmin')) { // do something }
In summary, CodeIgniter Shield's authorization system allows you to:
Define user groups with specific roles and permissions.
Assign users to one or more groups.
Check if a user has the necessary permissions to perform an action.
This provides a flexible and robust way to manage access control in your CodeIgniter application.