Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Abac Laravel Package

craftcamp/php-abac

Attribute-based access control (ABAC) for PHP apps. Define policies using attributes and evaluate permissions based on user, resource, action, and context. Framework-agnostic with a simple API, suited for fine-grained authorization beyond roles.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require craftcamp/php-abac
    

    Add to composer.json if using a monorepo or custom package.

  2. Basic Initialization

    use CraftCamp\Abac\Abac;
    
    $abac = new Abac();
    $abac->addPolicy('admin', [
        'actions' => ['create', 'read', 'update', 'delete'],
        'resources' => ['posts', 'users'],
    ]);
    
  3. First Use Case: Check Access

    $isAllowed = $abac->isAllowed('admin', 'create', 'posts');
    // Returns `true` if the policy grants access.
    

Where to Look First

  • Documentation: GitHub README (if available) or inline PHPDoc.
  • Core Classes:
    • Abac (main class for policy management).
    • Policy (defines rules for subjects, actions, and resources).
    • AbacException (handle edge cases like invalid inputs).
  • Examples: Check tests (tests/ directory) for real-world usage.

Implementation Patterns

Policy Definition Workflows

  1. Dynamic Policy Loading Load policies from a config file (e.g., config/abac.php) during Laravel bootstrapping:

    $abac = new Abac();
    foreach (config('abac.policies') as $role => $rules) {
        $abac->addPolicy($role, $rules);
    }
    
  2. Role-Based Access Control (RBAC) Integration Combine with Laravel’s Gate or Policy classes:

    // In AuthServiceProvider
    Gate::define('manage-posts', function ($user) {
        $abac = app(Abac::class);
        return $abac->isAllowed($user->role, 'update', 'posts');
    });
    
  3. Attribute-Based Policies Use custom attributes (e.g., department, is_active) for granular control:

    $abac->addPolicy('editor', [
        'actions' => ['update'],
        'resources' => ['posts'],
        'conditions' => [
            'department' => 'news',
            'is_active' => true,
        ],
    ]);
    

Integration Tips

  • Middleware for API Routes Protect API endpoints with ABAC:

    Route::get('/posts', function () {
        $abac = app(Abac::class);
        if (!$abac->isAllowed(auth()->user()->role, 'read', 'posts')) {
            abort(403);
        }
        // ...
    })->middleware('auth:sanctum');
    
  • Laravel Service Container Bind Abac to the container for dependency injection:

    $app->singleton(Abac::class, function ($app) {
        $abac = new Abac();
        // Load policies here or defer to config.
        return $abac;
    });
    
  • Caching Policies Cache policies in Redis/Memcached to avoid reprocessing:

    $cache = Cache::remember('abac_policies', now()->addHours(1), function () {
        return $abac->getPolicies();
    });
    

Gotchas and Tips

Pitfalls

  1. Overly Complex Conditions

    • Issue: Nested conditions (e.g., conditions => ['department' => ['news', 'sports']]) may not work as expected.
    • Fix: Flatten conditions or use helper methods to validate attributes.
  2. Case Sensitivity

    • Issue: Subject/action/resource names are case-sensitive by default.
    • Fix: Normalize inputs (e.g., strtolower()) if needed:
      $abac->isAllowed(strtolower($user->role), 'read', strtolower($resource));
      
  3. Policy Overrides

    • Issue: Adding duplicate policies silently overwrites existing ones.
    • Fix: Use mergePolicy() or track policies explicitly:
      $abac->mergePolicy('admin', ['actions' => ['audit']]); // Adds without replacing.
      
  4. Performance with Large Policies

    • Issue: Linear scans through policies for every isAllowed() call.
    • Fix: Pre-compile policies into a lookup table or use a database-backed solution.

Debugging

  • Enable Logging Temporarily add debug output to track policy evaluation:

    $abac->setDebug(true);
    $abac->isAllowed('user', 'delete', 'posts'); // Logs evaluation steps.
    
  • Validate Inputs Ensure subjects/actions/resources are non-empty strings:

    if (empty($subject) || empty($action) || empty($resource)) {
        throw new AbacException('Missing required parameters.');
    }
    

Extension Points

  1. Custom Condition Handlers Extend ConditionInterface for complex logic (e.g., date ranges):

    class DateCondition implements ConditionInterface {
        public function evaluate(array $attributes): bool {
            return $attributes['created_at'] > now()->subDays(30);
        }
    }
    
  2. Policy Storage Replace in-memory storage with a database or cache layer:

    class DatabasePolicyStore implements PolicyStoreInterface {
        public function getPolicy(string $subject): ?Policy {
            return Policy::fromArray(DB::table('abac_policies')->where('subject', $subject)->first());
        }
    }
    
  3. Event Listeners Trigger events for policy changes (e.g., PolicyAdded, PolicyUpdated):

    $abac->on('PolicyAdded', function ($subject) {
        Log::info("New policy added for: {$subject}");
    });
    

Config Quirks

  • Default Deny vs. Allow The library defaults to deny if no matching policy exists. Explicitly allow all by default if needed:

    $abac->setDefaultAllow(true); // Risky; use cautiously!
    
  • Resource Hierarchies Support hierarchical resources (e.g., posts/*) with a custom ResourceResolver:

    $abac->setResourceResolver(function ($resource) {
        return explode('/', $resource); // ['posts', '123']
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
amashukov/lnd-client-php
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky