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

Api Platform User Security Bundle Laravel Package

dotsafe/api-platform-user-security-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require dotsafe/api-platform-user-security-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Dotsafe\ApiPlatformUserSecurityBundle\DotsafeApiPlatformUserSecurityBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Password Reset Configure the bundle in config/packages/dotsafe_api_platform_user_security.yaml:

    dotsafe_api_platform_user_security:
        reset:
            enabled: true
            token_ttl: 3600  # 1 hour
            email_template: 'emails/reset_password.html.twig'
    

    Ensure you have a User entity with resetToken and resetTokenExpiresAt fields (or extend the provided User trait).

  3. Trigger a Reset Use the ResetPasswordAction in your API Platform controller:

    use Dotsafe\ApiPlatformUserSecurityBundle\Action\ResetPasswordAction;
    
    #[ApiResource(
        operations: [
            new ResetPasswordAction(),
        ]
    )]
    class User {}
    

Implementation Patterns

Workflows

  1. Password Reset Flow

    • Request: POST /api/reset-password-request with email.
    • Response: Returns a success message (no token in payload for security).
    • Email: Send a link with a token (e.g., /api/reset-password?token=...).
    • Reset: POST /api/reset-password with token and newPassword.
  2. Integration with API Platform Extend existing User resource operations:

    #[ApiResource(
        operations: [
            new GetCollection(),
            new Get(),
            new ResetPasswordAction(), // Add to existing operations
        ]
    )]
    class User {}
    
  3. Customizing Tokens Override token generation in a custom ResetTokenGenerator service:

    # config/services.yaml
    services:
        App\Service\CustomResetTokenGenerator:
            decorates: 'dotsafe_api_platform_user_security.reset_token_generator'
    
  4. Email Templates Extend the default Twig template (emails/reset_password.html.twig) or override the path in config:

    dotsafe_api_platform_user_security:
        reset:
            email_template: 'custom/path/reset.html.twig'
    
  5. Validation Use Symfony’s validator constraints in your User entity:

    use Symfony\Component\Validator\Constraints as Assert;
    
    #[Assert\Length(min: 8)]
    private ?string $plainPassword = null;
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Tokens expire after token_ttl (default: 3600s). Ensure clients handle 404/403 for expired tokens gracefully.
    • Debugging: Check resetTokenExpiresAt in the User entity to verify expiry logic.
  2. Email Delivery

    • The bundle does not send emails automatically. Integrate with Symfony Mailer or a custom service:
      $this->mailer->send(
          new ResetPasswordEmail($user, $token)
      );
      
    • Test locally with a mail catcher (e.g., Mailtrap).
  3. Missing Documentation

    • "Password change" and "Magic Link" features are TODOs. Implement these manually by extending the bundle’s SecurityController.
    • Example for password change:
      // src/Controller/SecurityController.php
      public function changePassword(User $user, string $currentPassword, string $newPassword): Response
      {
          // Validate current password, update user, etc.
      }
      
  4. Impersonation

    • The "Impersonate" feature is undocumented. Use Symfony’s HWIOAuthBundle or SensioFrameworkExtraBundle for inspiration.
  5. Database Schema

    • Ensure your User entity has these fields (or extend Dotsafe\ApiPlatformUserSecurityBundle\Entity\User):
      #[ORM\Column(nullable: true)]
      private ?string $resetToken;
      
      #[ORM\Column(nullable: true)]
      private ?\DateTimeInterface $resetTokenExpiresAt;
      

Debugging Tips

  1. Token Generation

    • Log tokens for debugging (temporarily):
      $token = $this->resetTokenGenerator->generate($user);
      $this->logger->debug('Reset token:', ['token' => $token]);
      
  2. Configuration Overrides

    • Use dump(config('dotsafe_api_platform_user_security')) to verify loaded settings.
  3. Event Listeners

    • Extend the bundle’s events (e.g., ResetPasswordRequestedEvent) for custom logic:
      # config/services.yaml
      services:
          App\EventListener\ResetPasswordListener:
              tags:
                  - { name: kernel.event_listener, event: dotsafe_api_platform_user_security.reset_password_requested, method: onResetRequested }
      

Extension Points

  1. Custom Actions Create a new action class (e.g., MagicLinkAction) by copying ResetPasswordAction and overriding methods like process().

  2. Token Storage Replace the default token storage (e.g., switch to Redis):

    services:
        dotsafe_api_platform_user_security.reset_token_storage:
            class: App\Service\RedisResetTokenStorage
            arguments: ['@redis']
    
  3. Security Layers Add rate-limiting to /reset-password-request:

    # config/packages/security.yaml
    firewalls:
        main:
            pattern: ^/api/reset-password-request
            rate_limiter: reset_password_limiter
    
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.
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
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle