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

Password Hash Bundle Laravel Package

christian-riesen/password-hash-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require christian-riesen/password-hash-bundle:1.*
    

    Ensure AppKernel.php includes the bundle:

    new ChristianRiesen\PasswordHashBundle\PasswordHashBundle(),
    
  2. Configure security.yml Replace the default encoder with the custom one:

    security:
        encoders:
            Symfony\Component\Security\Core\User\User:  # Default Symfony user
                id: security.encoder.passwordhash
    

    For custom user entities (e.g., Acme\UserBundle\Entity\User):

    security:
        encoders:
            Acme\UserBundle\Entity\User:
                id: security.encoder.passwordhash
    
  3. First Use Case Use the encoder in a registration or password update form. The bundle automatically handles PHP 5.3–5.5 compatibility via password_compat.


Implementation Patterns

Workflows

  1. Registration Workflow

    • Use the encoder to hash passwords during user creation:
      $user = new User();
      $user->setPassword($password); // Encoder auto-hashes via Symfony's UserInterface
      $em->persist($user);
      $em->flush();
      
    • The encoder is triggered automatically when setting passwords on entities implementing UserInterface.
  2. Password Updates

    • Re-hash passwords when updated (e.g., in a setPassword() method):
      public function setPassword($plainPassword) {
          $this->password = $this->encoder->encodePassword($this, $plainPassword);
      }
      
    • Inject the encoder via dependency injection:
      use Symfony\Component\DependencyInjection\ContainerInterface;
      
      public function setPassword($plainPassword, ContainerInterface $container) {
          $encoder = $container->get('security.encoder.passwordhash');
          $this->password = $encoder->encodePassword($this, $plainPassword);
      }
      
  3. Authentication

    • The bundle integrates seamlessly with Symfony’s security system. No additional configuration is needed for password verification.

Integration Tips

  • Custom User Providers Ensure your user entity implements Symfony\Component\Security\Core\User\UserInterface or extends Symfony\Component\Security\Core\User\AdvancedUserInterface for full compatibility.

  • Legacy Systems For PHP < 5.5, the bundle falls back to password_compat. Test thoroughly to ensure compatibility with your environment.

  • Testing Mock the encoder in unit tests to avoid dependency on PHP’s native functions:

    $encoder = $this->createMock('Symfony\Component\Security\Core\Encoder\EncoderInterface');
    $encoder->expects($this->any())
            ->method('encodePassword')
            ->willReturn('hashed_password');
    $this->container->set('security.encoder.passwordhash', $encoder);
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch

    • If PHP < 5.3, the bundle will fail silently or throw errors. Ensure your server meets the minimum requirement (PHP 5.3+).
    • Fix: Upgrade PHP or use a different encoder (e.g., bcrypt).
  2. Missing UserInterface

    • The encoder only works with entities implementing UserInterface. Forgetting this causes silent failures.
    • Fix: Add use Symfony\Component\Security\Core\User\UserInterface; and implement required methods.
  3. Overriding Encoder Configuration

    • Incorrect security.yml syntax (e.g., missing id: security.encoder.passwordhash) breaks authentication.
    • Fix: Validate YAML syntax and ensure the encoder ID matches the bundle’s service name.
  4. Password Compat Conflicts

    • If password_compat is already loaded (e.g., via another package), conflicts may arise.
    • Fix: Exclude ircmaxell/password_compat from other dependencies or use a custom alias.

Debugging

  • Check Encoder Service Verify the encoder is registered:

    php bin/console debug:container security.encoder.passwordhash
    

    Should return:

    Service "security.encoder.passwordhash" is defined as "ChristianRiesen\PasswordHashBundle\Encoder\PasswordHashEncoder".
    
  • Log Hashing Errors Wrap password operations in try-catch blocks to log failures:

    try {
        $hashed = $encoder->encodePassword($user, $plainPassword);
    } catch (\Exception $e) {
        \Log::error("Password hash failed: " . $e->getMessage());
    }
    

Extension Points

  1. Custom Hash Algorithms The bundle uses PHP’s native password_hash() (or password_compat). To override:

    • Extend ChristianRiesen\PasswordHashBundle\Encoder\PasswordHashEncoder and inject a custom hashing strategy.
  2. Fallback Behavior Disable the fallback for PHP ≥ 5.5 by overriding the encoder service:

    # app/config/services.yml
    services:
        security.encoder.passwordhash:
            class: ChristianRiesen\PasswordHashBundle\Encoder\PasswordHashEncoder
            arguments:
                - "@security.password_hashers"  # Use Symfony's default hashers
    
  3. Legacy Password Migration To migrate old passwords (e.g., MD5) to the new format:

    public function migratePassword(User $user) {
        $oldHash = $user->getPassword();
        $newHash = password_hash($oldHash, PASSWORD_DEFAULT); // Re-hash the old hash!
        $user->setPassword($newHash);
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
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