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

Relay Authorization Bundle Laravel Package

dbp/relay-authorization-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require dbp/relay-authorization-bundle
    

    Ensure your config/bundles.php includes:

    return [
        // ...
        DigitalBlueprint\RelayAuthorizationBundle\DbpRelayAuthorizationBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run migrations to create the required tables (groups, grants, etc.):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Granting Access Inject the AuthorizationManager service and define a grant:

    use DigitalBlueprint\RelayAuthorizationBundle\Authorization\AuthorizationManager;
    
    class MyController {
        public function __construct(private AuthorizationManager $authManager) {}
    
        public function index(): void {
            $this->authManager->grant('group:admin', 'resource:dashboard', 'read');
        }
    }
    
  4. Check Authorization Verify if a user (via group) has access:

    $hasAccess = $this->authManager->check('group:admin', 'resource:dashboard', 'read');
    
  5. Documentation First Review the ./docs for:

    • Resource/grant naming conventions.
    • Predefined grant types (read, write, delete, admin).
    • Integration with Relay API Server.

Implementation Patterns

Core Workflows

  1. Group Management

    • Create/update groups dynamically:
      $this->authManager->createGroup('group:editor', ['description' => 'Content Editors']);
      
    • List groups:
      $groups = $this->authManager->getGroups();
      
  2. Grant-Based Authorization

    • Resource Patterns: Use resource:{type}:{id} (e.g., resource:post:123).
    • Bulk Grants: Assign multiple grants at once:
      $this->authManager->grantMultiple('group:admin', [
          'resource:dashboard' => ['read', 'write'],
          'resource:settings'  => ['admin'],
      ]);
      
    • Revoke Grants:
      $this->authManager->revoke('group:admin', 'resource:dashboard', 'read');
      
  3. Integration with Relay API

    • Use the RelayAuthorizationChecker in controllers to gate API endpoints:
      use DigitalBlueprint\RelayAuthorizationBundle\Relay\RelayAuthorizationChecker;
      
      public function updatePost(RelayAuthorizationChecker $checker, int $id): void {
          if (!$checker->check('group:admin', "resource:post:$id", 'write')) {
              throw new AccessDeniedException();
          }
          // Proceed with update
      }
      
  4. Event-Driven Extensions

    • Listen for grant/group changes via events:
      // config/services.yaml
      DigitalBlueprint\RelayAuthorizationBundle\EventListener\AuthorizationListener:
          tags:
              - { name: kernel.event_listener, event: authorization.grant.created, method: onGrantCreated }
      
  5. Custom Grant Types

    • Extend the GrantType enum or create a custom validator:
      use DigitalBlueprint\RelayAuthorizationBundle\Authorization\GrantType;
      
      // Add to config/packages/relay_authorization.yaml
      relay_authorization:
          custom_grant_types:
              - 'publish'
              - 'archive'
      

Gotchas and Tips

Pitfalls

  1. Resource Naming Collisions

    • Avoid ambiguous resource names (e.g., resource:user vs. resource:user:1). Use resource:{type}:{id} strictly.
    • Debug Tip: Enable SQL logging (APP_DEBUG=1) to verify queries:
      $this->authManager->getGrant('group:admin', 'resource:dashboard');
      
  2. Caching Quirks

    • Grants are cached by default. Clear cache after bulk operations:
      php bin/console cache:clear
      
    • Disable caching in config/packages/relay_authorization.yaml:
      relay_authorization:
          cache_grants: false
      
  3. Symfony Security Integration

    • The bundle does not integrate with Symfony’s security component by default. Use RelayAuthorizationChecker for Relay-specific logic.
    • Workaround: Create a custom voter:
      use DigitalBlueprint\RelayAuthorizationBundle\Relay\RelayAuthorizationChecker;
      use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
      
      class RelayVoter implements Voter {
          public function __construct(private RelayAuthorizationChecker $checker) {}
      
          public function vote(TokenInterface $token, $subject, array $attributes): bool {
              $group = $token->getUser()->getGroup();
              return $this->checker->check($group, $subject, 'read');
          }
      }
      
  4. Migration Order

    • Run migrations after installing the bundle but before using the AuthorizationManager in code.
  5. Grant Inheritance

    • Grants are not inherited by default. If you need hierarchical groups (e.g., group:admin inherits from group:user), implement a custom resolver:
      use DigitalBlueprint\RelayAuthorizationBundle\Authorization\AuthorizationManagerInterface;
      
      class HierarchicalAuthorizationManager implements AuthorizationManagerInterface {
          public function check(string $group, string $resource, string $grant): bool {
              // Custom logic to check parent groups
              return $this->fallbackManager->check($group, $resource, $grant) ||
                     $this->checkParentGroups($group, $resource, $grant);
          }
      }
      

Tips

  1. Audit Logging

    • Enable audit logs in config/packages/relay_authorization.yaml:
      relay_authorization:
          audit_log: true
      
    • Logs are stored in authorization_audit_log table.
  2. Performance

    • For high-traffic APIs, preload grants in a warmup command:
      use DigitalBlueprint\RelayAuthorizationBundle\Authorization\AuthorizationManager;
      
      class WarmupCommand extends Command {
          protected function execute(InputInterface $input, OutputInterface $output): int {
              $this->authManager->getAllGrants(); // Forces cache population
              return Command::SUCCESS;
          }
      }
      
  3. Testing

    • Use the AuthorizationManagerTestCase base class for unit tests:
      use DigitalBlueprint\RelayAuthorizationBundle\Tests\AuthorizationManagerTestCase;
      
      class MyTest extends AuthorizationManagerTestCase {
          public function testGrantCreation() {
              $this->assertTrue($this->authManager->grant('group:test', 'resource:test', 'read'));
          }
      }
      
  4. Relay API Integration

    • Ensure your relay-server-template is configured to use the same database as your Symfony app. Share the DATABASE_URL in .env.
  5. Custom Resource Resolvers

    • Override resource resolution for dynamic resources (e.g., soft-deleted items):
      use DigitalBlueprint\RelayAuthorizationBundle\Authorization\ResourceResolverInterface;
      
      class CustomResourceResolver implements ResourceResolverInterface {
          public function resolve(string $resource): ?string {
              if (str_starts_with($resource, 'resource:post:')) {
                  $postId = substr($resource, 12);
                  return $this->postRepository->findActive($postId) ? $resource : null;
              }
              return $resource;
          }
      }
      
      Register in services.yaml:
      DigitalBlueprint\RelayAuthorizationBundle\Authorization\ResourceResolverInterface: '@custom_resource_resolver'
      
  6. Bulk Operations

    • Use transactions for bulk grant/group updates:
      $entityManager = $this->authManager->getEntityManager();
      $entityManager->beginTransaction();
      try {
          $this->authManager->grantMultiple('group:admin', [...]);
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware