PHP code example of aurorawebsoftware / aauth

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

    

aurorawebsoftware / aauth example snippets


use Illuminate\Foundation\Auth\User as Authenticatable;
use AuroraWebSoftware\AAuth\Traits\AAuthUser;
use AuroraWebSoftware\AAuth\Contracts\AAuthUserContract;

class User extends Authenticatable implements AAuthUserContract
{
    use AAuthUser;

    // ...
}

return [
    'permissions' => [
            'system' => [
                'edit_something_for_system' => 'aauth/system.edit_something_for_system',
                'create_something_for_system' => 'aauth/system.create_something_for_system',
            ],
            'organization' => [
                'edit_something_for_organization' => 'aauth/organization.edit_something_for_organization',
                'create_something_for_organization' => 'aauth/organization.create_something_for_organization',
            ],
        ],
];

[
    // Top-level logical operator
    '&&' => [
        // Condition 1
        ['=' => ['attribute' => 'status', 'value' => 'active']],
        // Condition 2
        ['>' => ['attribute' => 'amount', 'value' => 100]],
        // Nested group of conditions
        ['||' => [
            ['=' => ['attribute' => 'category', 'value' => 'electronics']],
            ['=' => ['attribute' => 'category', 'value' => 'books']]
        ]]
    ]
]

    [
        '&&' => [
            // Condition A
            // Condition B
        ]
    ]
    // Both Condition A AND Condition B must be true.
    

    [
        '||' => [
            // Condition X
            // Condition Y
        ]
    ]
    // Either Condition X OR Condition Y (or both) must be true.
    

[
    '&&' => [ // Outer AND
        ['=' => ['attribute' => 'is_published', 'value' => true]], // Condition 1
        ['||' => [ // Inner OR
            ['=' => ['attribute' => 'visibility', 'value' => 'public']], // Condition 2a
            ['=' => ['attribute' => 'owner_id', 'value' => '$USER_ID']] // Condition 2b (assuming $USER_ID is a placeholder you'd replace)
        ]]
    ]
]
// Access if: is_published is true AND (visibility is 'public' OR owner_id matches the user's ID)

[
    // Conditional Operator (e.g., '=')
    '=' => [
        'attribute' => 'model_column_name', // The column name on your Eloquent model
        'value'     => 'the_value_to_compare_against'
    ]
]

    [
        '&&' => [
            ['=' => ['attribute' => 'status', 'value' => 'active']]
        ]
    ]
    

    [
        '&&' => [
            ['>=' => ['attribute' => 'order_value', 'value' => 1000]]
        ]
    ]
    

    [
        '&&' => [
            ['=' => ['attribute' => 'is_urgent', 'value' => true]],
            ['>' => ['attribute' => 'priority', 'value' => 5]]
        ]
    ]
    

    [
        '||' => [
            ['=' => ['attribute' => 'department', 'value' => 'sales']],
            ['=' => ['attribute' => 'department', 'value' => 'support']]
        ]
    ]
    

    [
        '&&' => [ // Top level can be && if this is the only group
            ['IN' => ['attribute' => 'department', 'value' => ['sales', 'support']]]
        ]
    ]
    

    [
        '||' => [ // Top-level OR
            [ // First group: document conditions
                '&&' => [
                    ['=' => ['attribute' => 'type', 'value' => 'document']],
                    ['=' => ['attribute' => 'file_format', 'value' => 'pdf']]
                ]
            ],
            [ // Second group: image conditions
                '&&' => [
                    ['=' => ['attribute' => 'type', 'value' => 'image']],
                    ['=' => ['attribute' => 'resolution', 'value' => 'high']]
                ]
            ]
        ]
    ]
    

    [
        '&&' => [
            ['=' => ['attribute' => 'product_category', 'value' => 'electronics']],
            ['=' => ['attribute' => 'brand', 'value' => 'AwesomeBrand']],
            [
                '||' => [
                    ['=' => ['attribute' => 'region', 'value' => 'EU']],
                    ['=' => ['attribute' => 'region', 'value' => 'US']]
                ]
            ]
        ]
    ]
    // Access if: category is 'electronics' AND brand is 'AwesomeBrand' AND (region is 'EU' OR region is 'US')
    

$this->app->singleton('aauth', function ($app) {
    return new AAuth(
        Auth::user(),
        Session::get('roleId')
    );
});

AAuth::can();

$organizationService = new OrganizationService()

public function index(OrganizationService $organizationService)
{
    .....
}

$data = [
    'name' => 'Org Scope1',
    'level' => 5,
    'status' => 'active',
];

$organizationService->createOrganizationScope($data);


$orgScope = OrganizationScope::first();

$data = [
    'name' => 'Created Org Node 1',
    'organization_scope_id' => $orgScope->id,
    'parent_id' => 1,
];

$organizationService->createOrganizationNode($data);

$rolePermissionService = new RolePermissionService()

public function index(RolePermissionService $rolePermissionService)
{
    .....
}

$organizationScope = OrganizationScope::whereName('Root Scope')->first();

$data = [
    'organization_scope_id' => $organizationScope->id,
    'type' => 'system',
    'name' => 'Created System Role 1',
    'status' => 'active',
];

$createdRole = $rolePermissionService->createRole($data);

$role = Role::whereName('System Role 1')->first();
$permissionName = 'test_permission1';

$rolePermissionService->attachPermissionToRole($permissionName, $role->id);

$role = Role::whereName('System Role 1')->first();
$permissionName1 = 'test_permission1';
$permissionName2 = 'test_permission2';
$permissionName3 = 'test_permission3';

$rolePermissionService->syncPermissionsOfRole(
    compact('permissionName1', 'permissionName2', 'permissionName3'),
    $role->id
);

$rolePermissionService->detachSystemRoleFromUser($role->id, $user->id);

$organizationScope = OrganizationScope::whereName('Root Scope')->first();
$organizationNode = OrganizationNode::whereName('Root Node')->first();

$data = [
    'organization_scope_id' => $organizationScope->id,
    'type' => 'organization',
    'name' => 'Created Organization Role 1 for Attaching',
    'status' => 'active',
];

$createdRole = $rolePermissionService->createRole($data);
$rolePermissionService->attachOrganizationRoleToUser($organizationNode->id, $createdRole->id, $user->id);

namespace App\Models\ExampleModel;

use AuroraWebSoftware\AAuth\Interfaces\AAuthOrganizationNodeInterface;
use AuroraWebSoftware\AAuth\Traits\AAuthOrganizationNode;
use Illuminate\Database\Eloquent\Model;

class ExampleModel extends Model implements AAuthOrganizationNodeInterface
{
    use AAuthOrganizationNode;
    
    // implementation
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use AuroraWebSoftware\AAuth\Contracts\AAuthABACModelInterface;
use AuroraWebSoftware\AAuth\Traits\AAuthABACModel;

class Order extends Model implements AAuthABACModelInterface
{
    use AAuthABACModel;

    // Your model's other properties and methods...

    /**
     * Get the type of the model for ABAC.
     * This is typically a string that identifies your model.
     *
     * @return string
     */
    public static function getModelType(): string
    {
        return 'order'; // Or any unique string identifier for this model type
    }

    /**
     * Define the ABAC rules for this model.
     * These rules determine how access is granted based on attributes.
     * The detailed structure and syntax for these rules are covered in the "Defining ABAC Rules" section.
     * This method can serve as a fallback or default if no specific rule is found for the current user's role
     * via the `RoleModelAbacRule` model, or it can be the primary source if role-specific ABAC rules are not used.
     *
     * @return array
     */
    public static function getABACRules(): array
    {
        // Example: Return an empty array as a placeholder, or define default/fallback rules here.
        // For instance, to allow access if 'status' is 'active' by default:
        // return [
        //     '&&' => [
        //         ['=' => ['attribute' => 'status', 'value' => 'active']]
        //     ]
        // ];
        // If no role-specific rule is found via RoleModelAbacRule, these rules (if any) might be applied.
        // If you exclusively use RoleModelAbacRule for all ABAC logic, this method can safely return an empty array.
        return [];
    }
}

$permissions = AAuth::permissions();

AAuth::can('create_something_for_organization');

if (AAuth::can('create_something_for_organization')) {
    // codes here
}

AAuth::passOrAbort('create_something_for_organization');

$organizationNodes = AAuth::organizationNodes();

$isDescendant = AAuth::descendant(1, 3);

$data = ['name' => 'Test Organization Node-able Example'];

$createdModel = ExampleModel::createWithAAuthOrganizationNode($data, 1, 2);

$exampleModel = ExampleModel::find(1);
$relatedOrganizationModel = $exampleModel->relatedAAuthOrganizationNode()

ExampleModel::all();

use AuroraWebSoftware\AAuth\Models\Role;
use AuroraWebSoftware\AAuth\Models\RoleModelAbacRule;
use App\Models\Order; // Your ABAC-enabled Order model

// Assume $regionalManagerRole is an existing Role instance
$regionalManagerRole = Role::where('name', 'Regional Manager')->first();

if ($regionalManagerRole) {
    // Define the ABAC rules for the 'Order' model specifically for this role
    $orderRulesForRole = [
        '&&' => [
            ['=' => ['attribute' => 'status', 'value' => 'approved']],
            ['>=' => ['attribute' => 'amount', 'value' => 100]]
        ]
    ];

    // Create or update the rule for this role and model type
    RoleModelAbacRule::updateOrCreate(
        [
            'role_id' => $regionalManagerRole->id,
            'model_type' => Order::getModelType(), // This will return 'order'
        ],
        [
            'rules_json' => $orderRulesForRole // Provide the array directly
        ]
    );

    echo "ABAC rules for Orders assigned to Regional Manager role.\n";
}

    // Get all rules for a specific role
    $rulesForRole = RoleModelAbacRule::where('role_id', $role->id)->get();

    // Get the rule for a specific role and model
    $specificRule = RoleModelAbacRule::where('role_id', $role->id)
                                     ->where('model_type', Order::getModelType())
                                     ->first();
    if ($specificRule) {
        $rulesArray = $specificRule->rules_json; // Accesses the casted array
    }
    

    $ruleToUpdate = RoleModelAbacRule::find(1); // Or fetch by role_id and model_type
    if ($ruleToUpdate) {
        $newRules = [ /* ... new rule definition ... */ ];
        $ruleToUpdate->update(['rules_json' => $newRules]);
    }
    

    $ruleToDelete = RoleModelAbacRule::find(1);
    if ($ruleToDelete) {
        $ruleToDelete->delete();
    }

    // Or delete by role and model type
    RoleModelAbacRule::where('role_id', $role->id)
                     ->where('model_type', Order::getModelType())
                     ->delete();
    

    // Rule stored in RoleModelAbacRule for the user's role and 'order' model_type:
    // [
    //     '&&' => [
    //         ['=' => ['attribute' => 'status', 'value' => 'completed']]
    //     ]
    // ]
    

use App\Models\Order;

// Fetch all orders
// Despite no explicit where('status', 'completed') here,
// AAuth will automatically add this condition based on the user's role's ABAC rules.
// $completedOrders will only contain orders where status is 'completed'.
$completedOrders = Order::all();

foreach ($completedOrders as $order) {
    // echo $order->status; // Will always output 'completed'
}

// Fetch a specific order by ID
$order1 = Order::find(1); // If Order ID 1 has status 'pending', $order1 will be null.
$order2 = Order::find(2); // If Order ID 2 has status 'completed', $order2 will be the Order model.

// Even more complex queries are filtered:
$highValueCompletedOrders = Order::where('amount', '>', 500)->get();
// This will return orders where amount > 500 AND status is 'completed'.

use AuroraWebSoftware\AAuth\Scopes\AAuthABACModelScope;
use App\Models\Order;

// Retrieve all orders, ignoring ABAC rules for this specific query
$allOrdersIncludingNonCompleted = Order::withoutGlobalScope(AAuthABACModelScope::class)->get();

// Find a specific order by ID, ignoring ABAC rules
$anyOrder = Order::withoutGlobalScope(AAuthABACModelScope::class)->find(1);

ExampleModel::withoutGlobalScopes()->all()
bash
php artisan migrate
bash
php artisan vendor:publish --tag="aauth-seeders"
php artisan db:seed --class=SampleDataSeeder
bash
php artisan db:seed --class=SampleDataSeeder
bash
php artisan vendor:publish --tag="aauth-config"