PHP code example of bspdx / keystone

1. Go to this page and download the library: Download bspdx/keystone library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bspdx / keystone example snippets


'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication([
        'confirm' => true,
        'confirmPassword' => true,
    ]),
],

'features' => [
    'registration' => true,
    'email_verification' => true,
    'two_factor' => true,
    'passkeys' => true,
    'passkey_2fa' => true,
    'api_tokens' => true,
    'update_profile' => true,
    'update_passwords' => true,
    'account_deletion' => false,
    'passwordless_login' => true,
    'show_permissions' => true,

    // Enable multi-tenant mode (adds tenant_id column to users, roles, and permissions tables)
    'multi_tenant' => env('KEYSTONE_MULTI_TENANT', false),
],

use BSPDX\Keystone\Models\KeystoneRole;

// Create global role (accessible to all tenants)
$superAdmin = KeystoneRole::withoutTenant()->create([
    'name' => 'super_administrator',
    'tenant_id' => null,
]);

// Create tenant-specific role (auto-scoped)
Auth::login($userInTenantA);
$manager = KeystoneRole::create(['name' => 'manager']);
// tenant_id automatically populated from auth()->user()->tenant_id

'rbac' => [
    'default_role' => 'user',
    'super_admin_role' => 'super-admin',
],

'passkey' => [
    'rp_name' => env('APP_NAME', 'Laravel'),
    'rp_id' => env('PASSKEY_RP_ID', 'localhost'),
    'user_verification' => 'preferred',
    'allow_multiple' => true,
    '

'two_factor' => [
    'qr_code_size' => 200,
    'recovery_codes_count' => 8,
    '



namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use BSPDX\Keystone\Traits\HasKeystone;

class User extends Authenticatable
{
    use Notifiable, HasKeystone;

    // ... rest of your model
}

use App\Models\User;

$admins = User::role('admin')->get();
$staff = User::role(['admin', 'manager'])->get();



namespace App\Http\Controllers;

use BSPDX\Keystone\Services\Contracts\RoleServiceInterface;
use BSPDX\Keystone\Services\Contracts\PermissionServiceInterface;
use BSPDX\Keystone\Services\Contracts\AuthorizationServiceInterface;
use BSPDX\Keystone\Services\Contracts\PasskeyServiceInterface;

class AdminController extends Controller
{
    public function __construct(
        private RoleServiceInterface $roleService,
        private PermissionServiceInterface $permissionService,
        private AuthorizationServiceInterface $authService
    ) {}

    public function assignRole(User $user)
    {
        // Get all roles
        $roles = $this->roleService->getAllWithPermissions();

        // Assign roles to user
        $this->authService->assignRolesToUser($user, ['admin', 'editor']);

        // Check if user has role
        if ($this->authService->userHasRole($user, 'admin')) {
            // User is admin
        }
    }
}

// Include in your routes/web.php

// Include in your routes/api.php

Route::middleware(['auth', 'role:admin'])->group(function () {
    // Only users with 'admin' role can access
});

// Multiple roles (OR logic)
Route::middleware(['auth', 'role:admin,editor'])->group(function () {
    // Users with 'admin' OR 'editor' role can access
});

Route::middleware(['auth', 'permission:edit-posts'])->group(function () {
    // Only users with 'edit-posts' permission
});

// Multiple permissions
Route::middleware(['auth', 'permission:edit-posts,publish-posts'])->group(function () {
    // Users with either permission can access
});

Route::middleware(['auth', '2fa'])->group(function () {
    // Ensures users with 

// Check role
if (auth()->user()->hasRole('admin')) {
    // User is an admin
}

// Check permission
if (auth()->user()->can('edit-posts')) {
    // User can edit posts
}

// Check multiple roles
if (auth()->user()->hasAnyRole(['admin', 'editor'])) {
    // User has at least one of these roles
}

// Super admin check
if (auth()->user()->isSuperAdmin()) {
    // User is super admin (bypasses all permission checks)
}

use BSPDX\Keystone\Services\Contracts\AuthorizationServiceInterface;

class PostController extends Controller
{
    public function __construct(
        private AuthorizationServiceInterface $authService
    ) {}

    public function edit(Post $post)
    {
        if ($this->authService->userHasPermission(auth()->user(), 'edit-posts')) {
            // User can edit posts
        }
    }
}

// Login endpoint (you need to create this)
Route::post('/login', function (Request $request) {
    $credentials = $request->validate([
        'email' => '1);
    }

    $user = $request->user();
    $token = $user->createToken('api-token')->plainTextToken;

    return response()->json([
        'token' => $token,
        'user' => $user,
    ]);
});

use BSPDX\Keystone\Models\KeystoneRole;

// Create a global role accessible to all tenants
$superAdmin = KeystoneRole::withoutTenant()->create([
    'name' => 'super_administrator',
    'title' => 'Super Administrator',
    'tenant_id' => null,  // Global role
]);

// tenant_id is auto-populated from authenticated user
Auth::login($userInTenantA);

$manager = KeystoneRole::create([
    'name' => 'department_manager',
    'title' => 'Department Manager',
    // tenant_id automatically set from auth()->user()->tenant_id
]);

// View all roles across all tenants
$allRoles = KeystoneRole::withoutTenant()->get();

// Check if user can bypass tenant filtering
if ($user->canBypassPermissions()) {
    // User is super-admin
}



namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use BSPDX\Keystone\Traits\HasKeystone;

class User extends Authenticatable
{
    use HasKeystone;

    protected $fillable = ['name', 'email', 'password'];
}

// routes/web.php
Route::get('/login', function () {
    return view('auth.login');
})->name('login');

// Include Keystone routes
bash
php artisan migrate
bash
php artisan db:seed --class=KeystoneSeeder
bash
# Create roles and permissions
php artisan keystone:make-role manager
php artisan keystone:make-permission edit-posts

# Assign and remove roles/permissions
php artisan keystone:assign-role admin --user={user_id}
php artisan keystone:unassign-role admin --user={user_id}
php artisan keystone:assign-permission edit-posts --role=editor
php artisan keystone:unassign-permission edit-posts --role=editor

# User management
php artisan keystone:make-user
php artisan keystone:change-password
bash
php artisan vendor:publish --tag=keystone-views
bash
composer vendor:publish --tag=keystone-config
php artisan vendor:publish --tag=keystone-migrations
php artisan migrate
php artisan db:seed --class=KeystoneSeeder