PHP code example of ttpryg / auth-user

1. Go to this page and download the library: Download ttpryg/auth-user 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/ */

    

ttpryg / auth-user example snippets


use PDO;
use Ttpryg\AuthUser\Repositories\PdoUserRepository;
use Ttpryg\AuthUser\Repositories\PdoRbacRepository;
use Ttpryg\AuthUser\Services\RbacManager;

$pdo = new PDO("mysql:host=localhost;dbname=my_db", "root", "secret");
$userRepo = new PdoUserRepository($pdo);
$rbacRepo = new PdoRbacRepository($pdo);
$rbacManager = new RbacManager($rbacRepo, $userRepo);

// 1. Create Roles & Permissions
$adminRole = $rbacManager->createRole('admin', 'Administrator');
$deleteUserPerm = $rbacManager->createPermission('user:delete', 'Delete User Account');

// 2. Assign Permission to Role
$rbacManager->assignPermissionToRole($adminRole, $deleteUserPerm);

// 3. Assign Role to User
$user = $userRepo->findById(1);
$rbacManager->assignRoleToUser($user->getId(), $adminRole);

// 4. Load User RBAC & Check Access
$user = $rbacManager->loadUserWithRbac($user);

if ($user->hasRole('admin')) {
    echo "User is an Admin!";
}

if ($user->hasPermission('user:delete')) {
    echo "User can delete other accounts!";
}