Weave 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

Security Bundle Laravel Package

austral/security-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle via Composer:
   ```bash
   composer require austral/security-bundle

Register in config/bundles.php:

Austral\SecurityBundle\AustralSecurityBundle::class => ['all' => true],
  1. Database Migration Run migrations (assuming Doctrine ORM):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  2. First Use Case: User Creation Use the UserManager service to create a user:

    use Austral\SecurityBundle\Entity\User;
    use Austral\SecurityBundle\Manager\UserManager;
    
    $userManager = $this->container->get(UserManager::class);
    $user = $userManager->createUser([
        'username' => 'john_doe',
        'email' => '[email protected]',
        'password' => 'secure_password', // Auto-hashed
        'roles' => ['ROLE_USER'],
    ]);
    $userManager->persist($user);
    
  3. Key Classes to Explore

    • Austral\SecurityBundle\Entity\User: Base user entity.
    • Austral\SecurityBundle\Entity\Role: Role management.
    • Austral\SecurityBundle\Entity\UserGroup: Group-based permissions.
    • Austral\SecurityBundle\Manager\UserManager: Core user operations.

Implementation Patterns

Core Workflows

1. User Management

  • CRUD Operations:
    // Create
    $user = $userManager->createUser($data);
    
    // Update
    $user->setEmail('[email protected]');
    $userManager->updateUser($user);
    
    // Delete (soft-delete by default)
    $userManager->deleteUser($user);
    
  • Password Handling: Use UserManager::hashPassword() for manual hashing or let the bundle auto-hash during creation.

2. Role and Group Integration

  • Assign roles to a user:
    $user->addRole('ROLE_ADMIN');
    $userManager->updateUser($user);
    
  • Create a group and assign users:
    $groupManager = $this->container->get(\Austral\SecurityBundle\Manager\GroupManager::class);
    $group = $groupManager->createGroup('Editors');
    $group->addUser($user);
    $groupManager->persist($group);
    

3. Authentication Integration

  • Extend Symfony’s security system by configuring security.yaml:
    providers:
        austral_users:
            entity:
                class: Austral\SecurityBundle\Entity\User
                property: username
    firewalls:
        main:
            provider: austral_users
            form_login: ~
    

4. Event-Driven Extensions

  • Listen to user events (e.g., UserCreatedEvent):
    use Austral\SecurityBundle\Event\UserEvents;
    use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
    
    #[AsEventListener(event: UserEvents::USER_CREATED)]
    public function onUserCreated(UserCreatedEvent $event) {
        $user = $event->getUser();
        // Send welcome email, etc.
    }
    

5. API Resource Integration

  • Use with API Platform or similar:
    # config/api/resources.yaml
    resources:
        Austral\SecurityBundle\Entity\User:
            operations:
                get:
                    security: "is_granted('ROLE_ADMIN')"
    

Integration Tips

Doctrine ORM

  • The bundle uses Doctrine’s lifecycle callbacks. Ensure your User entity extends Austral\SecurityBundle\Entity\AbstractUser:
    use Austral\SecurityBundle\Entity\AbstractUser;
    
    class User extends AbstractUser { ... }
    

Custom User Fields

  • Extend the User entity:
    use Austral\SecurityBundle\Entity\User as BaseUser;
    
    class User extends BaseUser {
        #[ORM\Column]
        private ?string $customField = null;
    
        // Getters/setters...
    }
    

Command-Line Tools

  • Use the bundle’s console commands for bulk operations:
    php bin/console austral:security:create-user jane_doe [email protected]
    

Gotchas and Tips

Pitfalls

  1. Entity Inheritance

    • If extending AbstractUser, do not override __construct() or Doctrine’s lifecycle methods (e.g., prePersist). The bundle handles these internally.
    • Fix: Use __set_state() or static factory methods for initialization.
  2. Password Hashing

    • Avoid manually hashing passwords unless using UserManager::hashPassword(). Directly passing plaintext to setPassword() may fail silently.
    • Debug: Check logs for InvalidPasswordException.
  3. Role Hierarchy

    • The bundle does not enforce role hierarchy (e.g., ROLE_ADMIN > ROLE_USER). Implement this in your Voter or AccessControl logic.
    • Tip: Use Symfony’s RoleHierarchyVoter for this.
  4. Soft Deletes

    • Users are soft-deleted by default (deletedAt field). Use UserManager::forceDeleteUser() for hard deletes.
    • Warning: Soft-deleted users may still appear in queries unless filtered:
      $users = $userManager->findAll(['deletedAt' => null]);
      
  5. Group Permissions

    • Groups are not automatically synced with user roles. Manually assign roles to users or use a PostPersist event to mirror group roles.

Debugging

  1. Event Dispatching

    • Verify events are fired by enabling debug mode and checking logs:
      # config/services.yaml
      Austral\SecurityBundle\:
          resource: '../vendor/austral/security-bundle/config/services.yaml'
          autowire: true
      
  2. Migration Issues

    • If migrations fail, check for:
      • Missing austral/entity-bundle dependencies.
      • Schema conflicts (e.g., custom User fields not in migrations).
    • Fix: Run php bin/console doctrine:schema:update --force.
  3. Permission Denied

    • Ensure your security.yaml firewall matches the bundle’s user provider:
      # Wrong (if using custom property)
      property: email
      
    • Tip: Use php bin/console debug:security to inspect providers.

Extension Points

  1. Custom User Providers

    • Implement Austral\SecurityBundle\Provider\UserProviderInterface for non-Doctrine users (e.g., LDAP).
  2. Event Subscribers

    • Extend functionality via events:
      #[AsEventListener(UserEvents::USER_UPDATED)]
      public function onUserUpdated(UserUpdatedEvent $event) {
          // Log changes, notify admins, etc.
      }
      
  3. Voters

    • Create custom voters for group-based permissions:
      use Symfony\Component\Security\Core\Authorization\Voter\Voter;
      
      class GroupVoter extends Voter {
          protected function supports(string $attribute, $subject): bool {
              return $attribute === 'GROUP_EDIT';
          }
      
          protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool {
              $user = $token->getUser();
              return $user->hasGroup('Editors');
          }
      }
      
  4. API Filters

    • Filter API responses by role/group:
      # config/api/platform.yaml
      filters:
          role_filter:
              property: 'user.roles'
              operator: 'in'
              value: ['ROLE_ADMIN']
      

Configuration Quirks

  1. Default Password Hasher

    • The bundle uses Symfony’s UserPasswordHasher. To customize:
      # config/services.yaml
      Austral\SecurityBundle\Manager\UserManager:
          arguments:
              $passwordHasher: '@security.user_password_hasher' # Override if needed
      
  2. Group Namespace

    • Groups are prefixed with GROUP_ by default. Change in config:
      # config/packages/austral_security.yaml
      austral_security:
          group:
              prefix: 'ROLE_GROUP_'
      
  3. Audit Logging

    • Enable audit logs for user changes:
      austral_security:
          audit:
              enabled: true
              log_channel: 'security'
      
    • Note: Requires monolog bundle.

Performance Tips

  1. Eager-Loading

    • Avoid the N+1 problem when fetching users with groups/roles:
      $users = $userManager->findAll(['with' => ['groups', 'roles']]);
      
  2. Caching Roles

    • Cache role checks in production:
      framework:
          cache:
              pools:
                  security.role_cache:
                      adapter: cache.app
      
  3. Bulk Operations

    • Use batch processing for large user imports:
      $userManager->setBatchMode(true);
      
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator