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

Laravel Temporary Tokens Laravel Package

mydaniel/laravel-temporary-tokens

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require mydaniel/laravel-temporary-tokens
    php artisan vendor:publish --provider="MyDaniel\TemporaryTokens\TemporaryTokensServiceProvider" --tag="config"
    php artisan vendor:publish --provider="MyDaniel\TemporaryTokens\TemporaryTokensServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. First Use Case: Generate a token for a user (e.g., password reset):

    use MyDaniel\TemporaryTokens\Facades\TemporaryToken;
    
    $token = TemporaryToken::generate(
        user: $user,
        length: 6,
        expiresAt: now()->addMinutes(15),
        maxUses: 1,
        metadata: ['purpose' => 'password_reset']
    );
    
  3. Validate a Token:

    $isValid = TemporaryToken::validate($tokenValue, $user);
    
  4. Consume the Token:

    $consumed = TemporaryToken::consume($tokenValue, $user);
    

Where to Look First

  • Configuration: config/temporary-tokens.php (adjust token length, expiration defaults, etc.).
  • Artisan Command: php artisan temporary-tokens:prune (run via cron or manually to clean up expired tokens).
  • Facade: MyDaniel\TemporaryTokens\Facades\TemporaryToken (primary entry point for most operations).

Implementation Patterns

Core Workflows

  1. Token Generation:

    • Dynamic Tokens: Generate tokens for one-time actions (e.g., OTPs, password resets).
      $token = TemporaryToken::generate(
          user: $user,
          length: 8,
          expiresAt: now()->addMinutes(30),
          metadata: ['device' => 'mobile']
      );
      
    • Bulk Generation: Create multiple tokens for batch operations (e.g., bulk email verifications).
      $tokens = TemporaryToken::generateMany(
          userIds: [1, 2, 3],
          length: 6,
          expiresAt: now()->addHours(1)
      );
      
  2. Token Validation and Consumption:

    • Validation with Metadata Check:
      $isValid = TemporaryToken::validate(
          $tokenValue,
          $user,
          fn ($metadata) => $metadata['purpose'] === 'password_reset'
      );
      
    • Consumption with Callback:
      $consumed = TemporaryToken::consume($tokenValue, $user, function ($token) {
          // Perform action after token is consumed (e.g., update user password).
          $user->forceFill(['password' => bcrypt('new_password')])->save();
      });
      
  3. Token Management:

    • Find Tokens by User:
      $tokens = TemporaryToken::forUser($user)->get();
      
    • Find Tokens by Metadata:
      $tokens = TemporaryToken::whereMetadata('purpose', 'email_verification')->get();
      
    • Regenerate Expired Tokens:
      $newToken = TemporaryToken::regenerate($user, $oldTokenValue);
      
  4. Integration with Eloquent:

    • Attach Tokens to Models:
      // In User model:
      public function tokens()
      {
          return $this->hasMany(TemporaryToken::class);
      }
      
    • Query Tokens via Relationship:
      $user->tokens()->where('purpose', 'login')->first();
      

Advanced Patterns

  1. Custom Token Storage: Override the default storage by binding a custom repository:

    // In a service provider:
    $this->app->bind(
        MyDaniel\TemporaryTokens\Contracts\TokenRepository::class,
        App\Repositories\CustomTokenRepository::class
    );
    
  2. Event-Based Workflows: Listen for token events (e.g., TokenGenerated, TokenConsumed) to trigger side effects:

    // In EventServiceProvider:
    protected $listen = [
        \MyDaniel\TemporaryTokens\Events\TokenGenerated::class => [
            \App\Listeners\SendTokenViaEmail::class,
        ],
    ];
    
  3. Rate Limiting: Combine with Laravel's rate limiting to restrict token generation/consumption:

    use Illuminate\Cache\RateLimiting\Limit;
    
    RateLimiter::for('generate_tokens', function (Request $request) {
        return Limit::perMinute(5)->by($request->user()->id);
    });
    

Gotchas and Tips

Pitfalls

  1. Token Expiration Handling:

    • Issue: Tokens may not be pruned immediately, leading to stale data in queries.
    • Fix: Run php artisan temporary-tokens:prune manually or schedule it via cron (e.g., daily):
      * * * * * cd /path-to-project && php artisan temporary-tokens:prune >> /dev/null 2>&1
      
    • Tip: Use TemporaryToken::prune() in a scheduled job for finer control.
  2. Metadata Serialization:

    • Issue: Complex metadata (e.g., objects, resources) may not serialize correctly.
    • Fix: Ensure metadata is JSON-serializable or use json_encode() explicitly:
      $metadata = ['data' => json_encode(['key' => 'value'])];
      
  3. Token Consumption Race Conditions:

    • Issue: Concurrent requests to consume the same token may cause inconsistencies.
    • Fix: Use database transactions or optimistic locking:
      DB::transaction(function () use ($tokenValue, $user) {
          $consumed = TemporaryToken::consume($tokenValue, $user);
      });
      
  4. Token Length and Security:

    • Issue: Default token length (e.g., 6 digits) may be insufficient for high-security use cases.
    • Fix: Adjust config/temporary-tokens.php or override dynamically:
      $token = TemporaryToken::generate(..., length: 12);
      
    • Tip: For OTPs, consider using TemporaryToken::generateAlphanumeric() for mixed-case tokens.
  5. Model Association:

    • Issue: Forgetting to associate tokens with a model (e.g., user_id) can lead to orphaned tokens.
    • Fix: Always pass a model when generating tokens:
      TemporaryToken::generate(user: $user, ...);
      

Debugging Tips

  1. Query Logs: Enable Laravel's query logging to inspect token-related queries:

    DB::enableQueryLog();
    $token = TemporaryToken::generate(...);
    dd(DB::getQueryLog());
    
  2. Token Inspection: Dump token details for debugging:

    $token = TemporaryToken::find($tokenValue);
    dd($token->toArray());
    
  3. Event Listeners: Temporarily log token events to trace workflows:

    // In a listener:
    \Log::info('Token generated', ['token' => $token->value, 'metadata' => $token->metadata]);
    

Extension Points

  1. Custom Token Generators: Extend the default generator to support custom logic (e.g., time-based tokens):

    use MyDaniel\TemporaryTokens\Contracts\TokenGenerator;
    
    class CustomTokenGenerator implements TokenGenerator
    {
        public function generate(int $length): string
        {
            return Str::random($length); // Or custom logic.
        }
    }
    

    Bind it in a service provider:

    $this->app->bind(TokenGenerator::class, CustomTokenGenerator::class);
    
  2. Token Validation Rules: Create reusable validation rules for tokens:

    use Illuminate\Validation\Rule;
    
    $rules = [
        'token' => [
            'required',
            Rule::exists('temporary_tokens', 'value')
                ->where('user_id', $user->id)
                ->where('expires_at', '>', now())
                ->where('max_uses', '>', \DB::raw('(SELECT COUNT(*) FROM token_consumptions WHERE token_id = temporary_tokens.id)')),
        ],
    ];
    
  3. Token Notifications: Extend the package to send notifications (e.g., emails/SMS) when tokens are generated:

    // In a listener for TokenGenerated:
    $user->notify(new TokenGeneratedNotification($token));
    
  4. Testing: Use the package's testing helpers to mock tokens:

    use MyDaniel\TemporaryTokens\Testing\Fakes\FakeToken;
    
    $fakeToken = FakeToken::create($user, '123456');
    $this->assertTrue(TemporaryToken::validate('123456', $user));
    
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