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

My Auth Bundle Laravel Package

alexseif/my-auth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alexseif/my-auth-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Alexseif\MyAuthBundle\MyAuthBundle::class => ['all' => true],
    ];
    
  2. Publish Configuration

    php bin/console my-auth:install
    

    This generates:

    • config/packages/my_auth.yaml (default config)
    • Migration for User entity (if using Doctrine)
    • Login/registration templates in templates/my_auth/
  3. First Use Case: User Registration Add a route in config/routes.yaml:

    my_auth_registration:
        path: /register
        controller: MyAuthBundle\Controller\RegistrationController::register
    

    Access /register to trigger the registration workflow (form + email verification via symfonycasts/verify-email-bundle).


Implementation Patterns

Core Workflows

  1. Authentication Flow

    • Login: Uses Symfony’s security.yaml firewall with form login.
      # config/packages/security.yaml
      firewalls:
          main:
              form_login:
                  authentication_path: my_auth_login
                  check_path: my_auth_login
      
    • Logout: Extend MyAuthBundle\Event\LogoutEvent to add custom logic (e.g., analytics):
      // src/EventListener/CustomLogoutListener.php
      public function onLogout(LogoutEvent $event) {
          $event->setPostLogoutRedirectUri('/custom-logout-page');
      }
      
      Register in services.yaml:
      services:
          App\EventListener\CustomLogoutListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'my_auth.logout', method: 'onLogout' }
      
  2. Password Reset Leverage symfonycasts/reset-password-bundle via the bundle’s wrapper:

    php bin/console my-auth:password-reset:send-email {user-email}
    

    Customize the reset template by overriding: templates/my_auth/reset_password/email.txt.twig.

  3. Role-Based Access Extend the User entity (auto-generated in src/Entity/User.php):

    #[ORM\Column]
    private array $roles = ['ROLE_USER'];
    
    public function addRole(string $role): self {
        if (!in_array($role, $this->roles)) {
            $this->roles[] = $role;
        }
        return $this;
    }
    

    Use in controllers:

    #[IsGranted('ROLE_ADMIN')]
    public function adminDashboard(): Response { ... }
    

Integration Tips

  • Custom User Provider: Override the default UserProvider by binding your own service:
    # config/services.yaml
    services:
        App\Security\UserProvider:
            decorates: 'my_auth.user_provider'
            arguments: ['@my_auth.user_provider.inner']
    
  • Email Templates: Override Twig templates in templates/my_auth/ to match your theme.
  • API Auth: Combine with lexik/jwt-authentication-bundle by extending the User entity to implement UserInterface for JWT.

Gotchas and Tips

Pitfalls

  1. Missing Migrations After publishing config, run:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

    The bundle assumes a User entity with email, password, and isVerified fields.

  2. CSRF Token Mismatch If registration/login forms fail silently, ensure your templates include:

    {{ form_start(form, { attr: { 'novalidate': 'novalidate' } }) }}
    {{ form_row(form._token) }}  {# Critical for CSRF protection #}
    
  3. Email Verification Stuck Check the verify_email bundle’s queue worker. If using Symfony’s mailer, verify the transport (e.g., MAILER_DSN in .env):

    MAILER_DSN=smtp://user:pass@smtp.example.com:port
    

Debugging

  • Event Debugging: Dump events in config/packages/dev/my_auth.yaml:

    my_auth:
        debug:
            enabled: true
            log_events: true
    

    Events are logged to var/log/dev.log.

  • Password Hashing: If hashing fails, ensure security.yaml uses the correct encoder:

    security:
        encoders:
            App\Entity\User:
                algorithm: auto
    

Extension Points

  1. Custom Fields Extend the User entity and update the registration form type:

    // src/Form/RegistrationFormType.php
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('customField', TextType::class);
    }
    

    Override the bundle’s form type in services.yaml:

    services:
        MyAuthBundle\Form\RegistrationType:
            class: App\Form\RegistrationFormType
    
  2. Pre/Post Auth Logic Subscribe to events:

    // src/EventListener/AuthListener.php
    public function onAuthenticationSuccess(AuthenticationSuccessEvent $event) {
        $user = $event->getUser();
        // Custom logic (e.g., log activity)
    }
    

    Register the listener:

    tags:
        - { name: 'kernel.event_listener', event: 'security.authentication.success', method: 'onAuthenticationSuccess' }
    
  3. Testing Use the bundle’s test utilities:

    // tests/Functional/AuthTest.php
    use Alexseif\MyAuthBundle\Test\AuthTestTrait;
    
    class AuthTest extends WebTestCase {
        use AuthTestTrait;
    
        public function testRegistration() {
            $this->registerUser(['email' => 'test@example.com']);
            $this->assertResponseRedirects('/verify-email');
        }
    }
    

Config Quirks

  • Email Verification URL: Customize the verification URL in config/packages/my_auth.yaml:
    my_auth:
        verify_email:
            route: my_custom_verification_route  # Default: my_auth_verify_email
    
  • Password Reset Token TTL: Adjust in config/packages/reset_password.yaml (inherited from symfonycasts/reset-password-bundle):
    reset_password:
        token_ttl: 86400  # 1 day in seconds
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon