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

Secure Code Laravel Package

veeqtoh/secure-code

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require veeqtoh/secure-code
    

    Publish the config (optional but recommended for customization):

    php artisan vendor:publish --provider="Veeqtoh\SecureCode\SecureCodeServiceProvider" --tag="config"
    
  2. First Use Case: Generate a 6-digit alphanumeric code:

    use Veeqtoh\SecureCode\Facades\SecureCode;
    
    $code = SecureCode::generate(6); // Returns e.g., "A1b2C3"
    
  3. Where to Look First:

    • Config File: config/secure-code.php (for customization like allowed characters, length ranges, etc.).
    • Facade: SecureCode (for quick generation/validation).
    • Manager: SecureCodeManager (for tracking codes in the database).

Implementation Patterns

Usage Patterns

  1. Code Generation:

    • Basic Generation:
      $code = SecureCode::generate(6); // Random 6-digit code
      
    • Custom Character Set:
      $code = SecureCode::generate(8, ['characters' => '0123456789ABCDEF']);
      
    • Length Range:
      $code = SecureCode::generateBetween(4, 8); // Random length between 4-8
      
  2. Validation:

    • Default Validation:
      if (SecureCode::validate('A1b2C3', 6)) {
          // Valid code
      }
      
    • Custom Validation Class: Extend Veeqtoh\SecureCode\Validation\SecureCodeValidator and bind it in the config:
      'validator' => \App\Services\CustomSecureCodeValidator::class,
      
  3. Tracking Codes (Database):

    • Allocate a Code:
      $code = SecureCode::allocate(6, 'user_id_123', ['metadata' => 'purpose']);
      
    • Reset/Reuse a Code:
      SecureCode::reset('A1b2C3'); // Marks as reusable
      
    • Destroy a Code:
      SecureCode::destroy('A1b2C3'); // Permanently removes from tracking
      
  4. Facade vs. Manager:

    • Use the Facade (SecureCode) for one-off generation/validation.
    • Use the Manager (SecureCodeManager) for persistent tracking (e.g., OTPs, coupons).

Workflows

  1. OTP System:

    // Generate and store OTP
    $otp = SecureCode::allocate(6, $user->id, ['expires_at' => now()->addMinutes(5)]);
    
    // Validate OTP later
    if (SecureCode::validate($request->otp, 6) && $otp->user_id === $user->id) {
        // Proceed
    }
    
  2. Coupon System:

    // Generate unique coupon
    $couponCode = SecureCode::generate(10, ['prefix' => 'COUPON_']);
    
    // Track usage
    $coupon = SecureCode::allocate(10, null, ['used' => false]);
    $coupon->update(['used' => true]);
    
  3. Bulk Generation:

    $codes = collect(range(1, 100))->map(fn($i) => SecureCode::generate(8));
    

Integration Tips

  • Laravel Events: Trigger events when codes are allocated/reset (e.g., SecureCodeAllocated).
  • Queue Jobs: Offload code generation/validation to queues for high-traffic apps.
  • Testing: Use SecureCode::fake() to mock codes in tests:
    SecureCode::fake(['A1b2C3', 'D4e5F6']);
    

Gotchas and Tips

Pitfalls

  1. Character Collisions:

    • Avoid ambiguous characters (e.g., 0O, 1I, 5S) if codes are user-facing.
    • Customize characters in config to exclude problematic ones.
  2. Database Tracking Overhead:

    • Allocating codes to the database adds latency. Use the facade (SecureCode) for stateless codes (e.g., one-time tokens).
  3. Validation Strictness:

    • The default validator checks length and character set. Override if you need flexible validation (e.g., allow partial matches).
  4. Reused Codes:

    • By default, codes are not reusable after allocation. Set 'reusable' => true in config or use SecureCode::reset() to allow reuse.
  5. Thread Safety:

    • Code generation is thread-safe, but database operations (allocate/reset) are not. Use transactions for critical workflows:
      DB::transaction(function () {
          $code = SecureCode::allocate(6, $user->id);
          // Additional logic...
      });
      

Debugging

  1. Code Not Validating:

    • Check if the code matches the exact length and character set used during generation.
    • Verify no whitespace is included (trim inputs):
      $code = trim($request->input('code'));
      
  2. Database Issues:

    • Ensure the secure_codes table exists and migrations are run:
      php artisan migrate
      
    • Check for duplicate entries if codes fail to allocate.
  3. Custom Validator Errors:

    • Extend SecureCodeValidator and ensure your class is autoloaded or manually bound in the config.

Config Quirks

  1. Default Values:

    'length' => 6,               // Default code length
    'characters' => '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', // Alphanumeric
    'reusable' => false,         // Codes are non-reusable by default
    'validator' => \Veeqtoh\SecureCode\Validation\SecureCodeValidator::class,
    
    • Override these in config/secure-code.php or dynamically in code:
      SecureCode::setConfig(['characters' => '0123456789']);
      
  2. Dynamic Length:

    • Use generateBetween() for variable-length codes, but ensure your validator supports the range.

Extension Points

  1. Custom Storage:

    • Extend the manager to support alternative storage (e.g., Redis):
      SecureCode::setManager(new \App\Services\RedisSecureCodeManager());
      
  2. Code Generation Strategies:

    • Replace the default SecureCodeGenerator with a custom class (e.g., for sequential codes):
      'generator' => \App\Services\SequentialCodeGenerator::class,
      
  3. Events:

    • Listen for SecureCodeAllocated, SecureCodeReset, or SecureCodeDestroyed events to trigger side effects (e.g., notifications):
      SecureCode::allocated(function ($code) {
          // Send email with the code
      });
      
  4. Rate Limiting:

    • Combine with Laravel’s rate limiter to prevent brute-force attacks:
      RateLimiter::for('secure-code')->by($request->ip())->allow(5)->every(1)->response(function () {
          return response('Too many attempts.', 429);
      });
      
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php