Authentication & RBAC

HexPHP ships with a lightweight, session-based Authentication engine equipped with Role-Based Access Control (RBAC) middleware out of the box.

The User Model

We generated an Eloquent User model located at app/Models/User.php. It connects to the users table which includes a native role column defaulting to 'user'.

Protecting Routes

HexPHP routing now natively supports passing parameters directly to Middleware simply by using a colon :.

<?php
use App\Controllers\Router;

// Require a user to be logged in (Any Role)
Router::get('/dashboard', ['DashboardController', 'index'], ['Auth']);

// Require a user to be logged in AND specifically be an 'admin'
Router::get('/settings', ['SettingsController', 'index'], ['RequireRole:admin']);

// You can also permit multiple roles by separating them with commas
Router::get('/reports', ['ReportsController', 'index'], ['RequireRole:admin,manager']);

How Authentication Works

When a user successfully logs in, your controller must place their ID and Role into the active PHP session.

<?php
// Inside AuthController::login()
$user = \App\Models\User::where('email', $email)->first();

if ($user && password_verify($password, $user->password)) {
    // Authenticate user
    $_SESSION['user_id'] = $user->id;
    $_SESSION['user_role'] = $user->role; // Required for RBAC
    
    header("Location: /dashboard");
    exit;
}

Using the Login / Registration System

We've built a native authentication flow out of the box! You can view the automated registration page at /register and the login page at /login.

Creating System Roles

HexPHP manages available system roles natively in a roles database table. You can register new system roles using the builtin CLI tool:

# Creating an active role within the database
php hex create:role admin
php hex create:role editor

Assigning Roles to Users

When a new user registers, they are automatically assigned the default user role. To grant higher privileges and link them to an existing role (such as admin), update their record using the Eloquent ORM:

<?php
// Retrieve the user you wish to upgrade
$user = \App\Models\User::where('email', 'johndoe@example.com')->first();

// Assign them explicitly to your new custom role
$user->role = 'admin';
$user->save();
Modifying Permissions

You can alter the RBAC logic by modifying app/Middleware/RequireRole.php. By default, if a user's $_SESSION['user_role'] does not match the allowed roles parameter, the system safely aborts to a 403 Access Denied page via the Router::abort(403) method.