Authorization Middleware¶
Introduction¶
The AuthorizationMiddleware
class is responsible for checking if a user has the necessary roles to access a certain page or perform a certain action. It is used in conjunction with the AuthenticationMiddleware
to ensure that a user is logged in before checking their authorization.
Usage¶
To use the AuthorizationMiddleware
, simply call the handle
method and pass in an array of roles that are allowed to access the page or perform the action. For example:
AuthorizationMiddleware::handle(['admin', 'editor']);
This code will check if the logged in user has either the admin
or editor
role before allowing access. If the user does not have one of these roles, they will be redirected to an error page with a 403
status code.
Code Explanation¶
The handle
method takes in an array of roles as its parameter. It first calls the AuthenticationMiddleware::handle()
method to ensure that the user is logged in. Then, it checks if the user's role is included in the provided array of roles. If it is not, the user is redirected to an error page with a 403
status code.
Here is a breakdown of the code:
class AuthorizationMiddleware
{
public static function handle($roles)
{
AuthenticationMiddleware::handle();
if (!in_array($_SESSION['USER']->role, $roles)) {
redirect("error/403");
exit();
}
}
}
- The
handle
method is a static method, which means it can be called without creating an instance of theAuthorizationMiddleware
class. - The
$roles
parameter is an array of roles that are allowed to access the page or perform the action. - The
AuthenticationMiddleware::handle()
method is called to ensure that the user is logged in. - The
in_array
function is used to check if the user's role is included in the provided array of roles. - If the user's role is not included in the array of allowed roles, the
redirect
function is called to redirect the user to an error page with a403
status code. Theexit
function is called to stop the execution of the script.