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

User Password Bundle Laravel Package

beelab/user-password-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require beelab/user-password-bundle
    

    Register the bundle in config/bundles.php:

    BeeLab\UserPasswordBundle\BeeLabUserPasswordBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --tag=beelab_user_password_config
    

    Update config/beelab_user_password.php with your email settings (e.g., mailer transport, from address).

  3. First Use Case: Password Reset Flow

    • Trigger the reset via a form (e.g., LostPasswordController):
      use BeeLab\UserPasswordBundle\Controller\LostPasswordController;
      
    • The bundle provides a default Twig template (@BeeLabUserPassword/reset_password.html.twig) for the reset form.
    • Test the flow by submitting an email, then check the inbox for the reset link.

Implementation Patterns

Core Workflows

  1. Requesting a Password Reset

    • Use the LostPasswordController or extend it to customize logic:
      public function requestReset(Request $request)
      {
          $email = $request->request->get('email');
          $this->get('beelab_user_password.password_resetter')->sendResetLink($email);
          return $this->render('your_template.html.twig');
      }
      
    • The PasswordResetter service handles token generation, email dispatch, and user validation.
  2. Resetting a Password

    • The ResetPasswordController validates tokens and updates passwords:
      public function reset(Request $request, $token)
      {
          $this->get('beelab_user_password.password_resetter')->resetPassword($token, $request->request->get('password'));
          return $this->redirectToRoute('home');
      }
      
    • Tokens expire after token_ttl (default: 1 hour) in config.
  3. Customizing Emails

    • Override the default email template by publishing assets:
      php artisan vendor:publish --tag=beelab_user_password_translation
      
    • Extend BeeLab\UserPasswordBundle\Event\PasswordResetEvent to modify email content dynamically.
  4. Integration with BeelabUserBundle

    • The bundle assumes BeeLab\UserBundle is installed. Ensure your User entity extends BeeLab\UserBundle\Entity\User and includes:
      /**
       * @ORM\Column(type="string", length=255, nullable=true)
       */
      private $resetToken;
      
    • Add getter/setter methods for resetToken and resetTokenExpiresAt.

Advanced Patterns

  1. Token Management

    • Manually generate/validate tokens via the PasswordResetter service:
      $token = $this->get('beelab_user_password.password_resetter')->generateToken($user);
      $isValid = $this->get('beelab_user_password.password_resetter')->isTokenValid($token, $user);
      
    • Customize token generation (e.g., UUID instead of hash) by extending BeeLab\UserPasswordBundle\Service\TokenGenerator.
  2. Event-Driven Extensions

    • Listen for PasswordResetEvent to log/resend emails:
      // src/EventListener/PasswordResetListener.php
      public function onPasswordReset(PasswordResetEvent $event)
      {
          // Custom logic (e.g., analytics, notifications)
      }
      
    • Register the listener in services.yaml:
      services:
          App\EventListener\PasswordResetListener:
              tags:
                  - { name: kernel.event_listener, event: beelab_user_password.reset, method: onPasswordReset }
      
  3. Testing

    • Mock the PasswordResetter in tests:
      $resetter = $this->createMock(PasswordResetter::class);
      $resetter->method('sendResetLink')->willReturn(true);
      $this->container->set('beelab_user_password.password_resetter', $resetter);
      
    • Use BeeLab\UserPasswordBundle\Tests as a reference for test cases.

Gotchas and Tips

Common Pitfalls

  1. Missing BeelabUserBundle

    • Error: Class 'BeeLab\UserBundle\Entity\User' not found.
    • Fix: Ensure beelab/user-bundle is installed and your User entity extends the correct base class.
  2. Token Expiry

    • Issue: Tokens expire too quickly or not at all.
    • Debug: Check token_ttl in config and ensure resetTokenExpiresAt is updated during token generation.
    • Tip: Use TTL (e.g., 24 hours) for better UX:
      # config/beelab_user_password.php
      token_ttl: 86400 # 24 hours in seconds
      
  3. Email Delivery Failures

    • Symptom: Reset emails are not sent.
    • Debug:
      • Verify mailer transport in config (e.g., smtp, sendmail).
      • Check from address is valid and not blacklisted.
      • Test with a local mail server (e.g., MailHog) during development.
  4. CSRF Protection

    • Issue: Reset form submissions fail with CSRF errors.
    • Fix: Ensure the form includes the CSRF token:
      {{ csrf_token('reset_password') }}
      
  5. Database Schema Mismatch

    • Error: Column 'resetToken' not found.
    • Fix: Run migrations after installing the bundle or manually add the column:
      // Migration file
      $table->string('reset_token')->nullable();
      $table->datetime('reset_token_expires_at')->nullable();
      

Pro Tips

  1. Custom Token Storage

    • Store tokens in Redis for scalability:
      # config/beelab_user_password.php
      token_storage: redis
      
    • Requires predis/predis and Redis server.
  2. Rate Limiting

    • Prevent brute-force attacks by limiting reset requests:
      // Extend PasswordResetter
      public function sendResetLink($email)
      {
          if ($this->isRateLimited($email)) {
              throw new \RuntimeException('Too many requests. Try again later.');
          }
          // ... existing logic
      }
      
  3. Localization

    • Override translation files for multi-language support:
      php artisan vendor:publish --tag=beelab_user_password_translation --force
      
    • Update resources/translations/beelab_user_password.xx.yaml.
  4. Logging

    • Log reset attempts for security audits:
      // In a listener
      $this->logger->info('Password reset requested', [
          'email' => $event->getEmail(),
          'ip' => $request->getClientIp(),
      ]);
      
  5. Testing Tokens

    • Use the PasswordResetter directly in tests to avoid email delivery:
      $resetter = $this->get('beelab_user_password.password_resetter');
      $resetter->setMailerMock(true); // Disables email sending
      
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