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

Rbac Bundle Laravel Package

admin-platform/rbac-bundle

Symfony2 Role-Based Access Control (RBAC) bundle powered by the Sylius RBAC component. Integrate roles and permissions into your app, with phpspec examples for testing and an MIT license.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require admin-platform/rbac-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        AdminPlatform\RbacBundle\AdminPlatformRbacBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run migrations to create RBAC tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Assigning a Role

    use AdminPlatform\RbacBundle\Entity\Role;
    use AdminPlatform\RbacBundle\Entity\User;
    
    $role = $roleRepository->findOneBy(['name' => 'ROLE_ADMIN']);
    $user = $userRepository->find(1);
    $user->addRole($role);
    $entityManager->flush();
    
  4. Check Permissions in Controller

    use Symfony\Component\HttpFoundation\Response;
    use AdminPlatform\RbacBundle\Security\Authorization\Voter\RoleVoter;
    
    public function secureAction(RoleVoter $voter, UserInterface $user): Response
    {
        if (!$voter->vote($user, 'EDIT', $this->getParameter('some_entity'))) {
            throw $this->createAccessDeniedException();
        }
        // ...
    }
    

Implementation Patterns

Role Hierarchy Management

  • Define Hierarchy in YAML (config/packages/admin_platform_rbac.yaml):
    admin_platform_rbac:
        hierarchy:
            ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_USER]
            ROLE_ADMIN: [ROLE_USER]
    
  • Dynamic Role Assignment:
    $role = $roleRepository->findOneBy(['name' => 'ROLE_EDITOR']);
    $user->addRole($role); // Automatically inherits ROLE_USER if defined in hierarchy
    

Permission-Based Access Control

  • Custom Voters:
    namespace App\Security\Voter;
    
    use AdminPlatform\RbacBundle\Security\Authorization\Voter\AbstractVoter;
    
    class ProductVoter extends AbstractVoter
    {
        protected function supports($attribute, $subject): bool
        {
            return in_array($attribute, ['EDIT', 'DELETE']) && $subject instanceof Product;
        }
    
        protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
        {
            $user = $token->getUser();
            return $user->hasRole('ROLE_PRODUCT_MANAGER');
        }
    }
    
    Register in security.yaml:
    security:
        access_control:
            - { path: ^/admin/product, roles: ROLE_PRODUCT_MANAGER }
    

Workflows

  1. User Onboarding:

    • Assign default role (ROLE_USER) via POST_PERSIST event listener.
    • Example:
      $user->addRole($roleRepository->findOneBy(['name' => 'ROLE_USER']));
      $entityManager->flush();
      
  2. Bulk Role Updates:

    $query = $entityManager->createQuery('SELECT u FROM App\Entity\User u WHERE u.isActive = true');
    $users = $query->getResult();
    foreach ($users as $user) {
        $user->addRole($roleRepository->findOneBy(['name' => 'ROLE_ACTIVE_USER']));
    }
    $entityManager->flush();
    
  3. API Integration:

    • Use Symfony\Bundle\FrameworkBundle\Controller\AbstractController to inject RoleVoter:
      public function apiAction(RoleVoter $voter, UserInterface $user): JsonResponse
      {
          if (!$voter->vote($user, 'VIEW', $resource)) {
              return $this->json(['error' => 'Unauthorized'], 403);
          }
          return $this->json($resource);
      }
      

Gotchas and Tips

Pitfalls

  1. Circular Dependencies in Role Hierarchy:

    • Validate hierarchy in post_load lifecycle callback:
      public function postLoad(LifecycleEventArgs $args)
      {
          $role = $args->getObject();
          $this->validateHierarchy($role);
      }
      
    • Use Symfony\Component\Validator\Constraints\Valid with a custom constraint.
  2. Permission Caching:

    • Clear cache after role updates:
      php bin/console cache:clear
      
    • Or manually in code:
      $this->container->get('security.token_storage')->setToken(new AnonymousToken());
      
  3. Symfony 5.4+ Compatibility:

    • Override security.yaml to avoid deprecation warnings:
      security:
          access_control:
              - { path: ^/, roles: PUBLIC_ACCESS }
              - { path: ^/admin, roles: ROLE_ADMIN }
      

Debugging

  • Check User Roles:
    dump($user->getRoles()); // Returns array of Role objects
    
  • Enable RBAC Debugging: Add to config/packages/dev/admin_platform_rbac.yaml:
    admin_platform_rbac:
        debug: true
    
    Logs will show role inheritance and permission checks.

Extension Points

  1. Custom Role Storage:

    • Implement AdminPlatform\RbacBundle\Repository\RoleRepositoryInterface for non-DB storage (e.g., Redis).
  2. Dynamic Role Loading:

    • Extend AdminPlatform\RbacBundle\Security\Authorization\Voter\RoleVoter to load roles from external APIs.
  3. Event Listeners:

    • Subscribe to admin_platform_rbac.role.pre_persist to validate roles before save:
      $event->setRole($event->getRole()->setName(strtoupper($event->getRole()->getName())));
      

Configuration Quirks

  • Hierarchy Overrides:
    • Use admin_platform_rbac.hierarchy to override defaults at runtime:
      $container->getParameter('admin_platform_rbac.hierarchy')['ROLE_CUSTOM'] = ['ROLE_USER'];
      
  • FOSUserBundle Integration:
    • Ensure User entity extends AdminPlatform\RbacBundle\Entity\UserInterface:
      use AdminPlatform\RbacBundle\Entity\UserInterface;
      class AppUser implements UserInterface { ... }
      

Performance Tips

  • Batch Role Assignment:
    $role = $roleRepository->findOneBy(['name' => 'ROLE_USER']);
    $users = $userRepository->findBy(['active' => true]);
    foreach ($users as $user) {
        $user->addRole($role);
    }
    $entityManager->flush(); // Single flush for all users
    
  • Denormalize Roles:
    • Add roles field to User entity for faster access:
      #[ORM\Column(type: 'json')]
      private array $rolesJson = [];
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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