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

Reset Password Bundle Laravel Package

symfonycasts/reset-password-bundle

Symfony bundle to implement secure, time-limited password reset flows. Generates reset tokens, validates expiry and one-time use, and provides helpers to send reset emails and update passwords. Integrates with Doctrine and Symfony security.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require symfonycasts/reset-password-bundle
    

    Add to config/bundles.php:

    Symfonycasts\ResetPasswordBundle\ResetPasswordBundle::class => ['all' => true],
    
  2. Configure the Bundle Update .env with:

    RESET_PASSWORD_SECRET=your-strong-secret-key-here
    RESET_PASSWORD_EXPIRATION_MINUTES=60
    
  3. First Use Case: Basic Password Reset Flow

    • Trigger Reset: Add a ForgotPasswordController with a form to submit emails.
      use Symfonycasts\ResetPasswordBundle\Controller\ForgotPasswordController;
      
    • Reset Link: The bundle auto-generates a secure token and sends an email (configure via Twig template in templates/ResetPasswordBundle/email/reset_password.html.twig).
    • Reset Form: Use the provided ResetPasswordController to handle token validation and password updates.
  4. Key Files to Review

    • config/packages/reset_password.yaml (default config)
    • templates/ResetPasswordBundle/ (customize emails/emails)
    • src/Entity/User.php (ensure resetPasswordToken and resetPasswordTokenExpiresAt fields exist).

Implementation Patterns

Workflow: Full Reset Flow

  1. User Requests Reset

    • Submit email via ForgotPasswordController::send().
    • Bundle generates a token, stores it in the user model, and sends an email with a link like: /reset-password?token=XYZ123&email=user@example.com.
  2. Token Validation

    • Use ResetPasswordController::validateToken() to check token expiry/validity.
    • Example middleware to protect routes:
      use Symfonycasts\ResetPasswordBundle\Security\ResetPasswordVoter;
      
      // In security.yaml
      access_control:
          - { path: ^/reset-password, roles: public, requirements: "reset_password.token_valid" }
      
  3. Password Update

    • Submit new password to ResetPasswordController::reset().
    • Bundle handles validation (e.g., strength, confirmation) and updates the password.

Integration Tips

  • Custom User Model Extend the bundle’s UserInterface:

    use Symfonycasts\ResetPasswordBundle\Model\UserInterface as ResetPasswordUserInterface;
    
    class User implements ResetPasswordUserInterface {
        // ...
    }
    
  • Email Customization Override templates in templates/ResetPasswordBundle/email/ or configure the sender in reset_password.yaml:

    reset_password:
        email:
            from: no-reply@yourdomain.com
            subject: 'Reset Your Password'
    
  • Testing Use the bundle’s ResetPasswordTestTrait for unit/integration tests:

    use Symfonycasts\ResetPasswordBundle\Tests\ResetPasswordTestTrait;
    
    class ResetPasswordTest extends TestCase {
        use ResetPasswordTestTrait;
    }
    
  • API Integration For APIs, bypass Twig emails and use a custom mailer service:

    # config/services.yaml
    Symfonycasts\ResetPasswordBundle\Mailer\MailerInterface: '@your.custom.mailer'
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Tokens expire by default after RESET_PASSWORD_EXPIRATION_MINUTES (60 mins).
    • Fix: Extend expiry in config or manually update resetPasswordTokenExpiresAt in the user model.
  2. Token Reuse

    • Tokens are single-use by default. Reuse requires custom logic in ResetPasswordController::validateToken().
  3. Database Schema

    • Ensure your User model has:
      /**
       * @ORM\Column(type="string", length=255, nullable=true)
       */
      private $resetPasswordToken;
      
      /**
       * @ORM\Column(type="datetime", nullable=true)
       */
      private $resetPasswordTokenExpiresAt;
      
    • Mistake: Missing these fields causes ResetPasswordException.
  4. Email Delivery

    • If emails aren’t sent, verify:
      • RESET_PASSWORD_SECRET is set.
      • Your mailer (e.g., Symfony Mailer, Swiftmailer) is configured.
      • The from email in reset_password.yaml is valid.

Debugging Tips

  • Log Tokens Enable debug mode to log token generation/validation:

    reset_password:
        debug: true
    

    Check logs for RESET_PASSWORD_DEBUG entries.

  • Token Validation Errors Common errors:

    • TokenNotFoundException: Token not found in DB or expired.
    • TokenExpiredException: Token older than expiresAt.
    • Solution: Re-generate the token via ForgotPasswordController::send().
  • CSRF Protection The reset form includes CSRF by default. Disable in reset_password.yaml if using API tokens:

    reset_password:
        csrf_protection: false
    

Extension Points

  1. Custom Token Storage Override token storage logic by implementing Symfonycasts\ResetPasswordBundle\TokenStorage\TokenStorageInterface.

  2. Token Generation Extend Symfonycasts\ResetPasswordBundle\TokenGenerator\TokenGeneratorInterface for custom token formats (e.g., UUIDs).

  3. Password Validation Add custom rules in ResetPasswordController::reset():

    $validator = $this->validator;
    $errors = $validator->validate($password, [
        new Assert\Length(['min' => 10]),
        new Custom\PasswordStrength(),
    ]);
    
  4. Event Listeners Listen for token generation/validation events:

    use Symfonycasts\ResetPasswordBundle\Event\ResetPasswordEvents;
    
    // In services.yaml
    Symfony\Component\EventDispatcher\EventSubscriberInterface:
        tags: ['kernel.event_subscriber']
    

    Example subscriber:

    class ResetPasswordSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                ResetPasswordEvents::TOKEN_GENERATED => 'onTokenGenerated',
            ];
        }
    
        public function onTokenGenerated(TokenGeneratedEvent $event) {
            // Log or modify the token
        }
    }
    
  5. Rate Limiting Prevent brute-force attacks by adding rate limiting to ForgotPasswordController:

    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Http\Firewall\RateLimiter;
    
    // In security.yaml
    access_control:
        - { path: ^/forgot-password, roles: public, requires_channel: https }
    
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.
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment