PHP code example of joe-nassar-tech / laravel-exponential-lockout

1. Go to this page and download the library: Download joe-nassar-tech/laravel-exponential-lockout library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joe-nassar-tech / laravel-exponential-lockout example snippets


return [
    // Cache configuration
    'cache' => [
        'store' => null, // Uses default cache store
        'prefix' => 'exponential_lockout',
    ],

    // Default delay sequence (in seconds) - 1min → 5min → 15min → 30min → 2hr → 6hr → 12hr → 24hr
    'default_delays' => [60, 300, 900, 1800, 7200, 21600, 43200, 86400],

    // Response handling
    'default_response_mode' => 'auto', // 'auto', 'json', 'redirect', 'callback'
    'default_redirect_route' => 'login',

    // Context templates for inheritance
    'context_templates' => [
        'strict' => [
            'enabled' => true,
            'min_attempts' => 1, // Lock immediately after 1st failure
            'delays' => [300, 900, 1800, 7200, 21600], // 5min → 15min → 30min → 2hr → 6hr
            'reset_after_hours' => 48, // Keep attempts longer
        ],
        'api' => [
            'enabled' => true,
            'response_mode' => 'json',
            'min_attempts' => 3,
            'delays' => [60, 300, 900, 1800, 7200],
            'reset_after_hours' => 24,
        ],
        'mfa' => [
            'enabled' => true,
            'min_attempts' => 2, // Stricter for MFA
            'delays' => [30, 60, 120, 300, 600], // Quick cycles for time-sensitive MFA
            'reset_after_hours' => 12, // Reset faster for MFA
        ],
    ],

    // Context-specific configurations
    'contexts' => [
        'login' => [
            'extends' => 'api', // Inherit API template
            'key' => 'email',
            'redirect_route' => 'login',
        ],
        'otp' => [
            'extends' => 'mfa', // Inherit MFA template
            'key' => 'phone',
            'response_mode' => 'json',
        ],
        'admin' => [
            'extends' => 'strict', // Inherit strict template
            'key' => 'email',
            'redirect_route' => 'admin.login',
        ],
        // ... more contexts
    ],
];

use Illuminate\Support\Facades\Route;

// Login route protection
Route::post('/login', [LoginController::class, 'login'])
    ->middleware('exponential.lockout:login');

// OTP verification protection  
Route::post('/verify-otp', [OtpController::class, 'verify'])
    ->middleware('exponential.lockout:otp');

// PIN validation protection
Route::post('/validate-pin', [PinController::class, 'validate'])
    ->middleware('exponential.lockout:pin');

use ExponentialLockout\Facades\Lockout;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        // Check if locked out (optional - middleware handles this automatically)
        if (Lockout::isLockedOut('login', $request->email)) {
            $remaining = Lockout::getRemainingTime('login', $request->email);
            return response()->json(['error' => 'Locked', 'retry_after' => $remaining], 429);
        }
        
        $credentials = $request->only('email', 'password');
        
        if (Auth::attempt($credentials)) {
            // Clear lockout on successful login (optional - middleware does this automatically)
            Lockout::clear('login', $request->email);
            return response()->json(['success' => true], 200);
        }
        
        // Record failed attempt (optional - middleware does this automatically)
        Lockout::recordFailure('login', $request->email);
        return response()->json(['error' => 'Invalid credentials'], 401);
    }
}

class OtpController extends Controller
{
    public function verify(Request $request)
    {
        $phone = $request->input('phone');
        $otp = $request->input('otp');
        
        if ($this->isValidOtp($phone, $otp)) {
            // Clear lockout on successful verification
            Lockout::clear('otp', $phone);
            
            return response()->json(['message' => 'OTP verified successfully']);
        }
        
        // Record failed attempt
        Lockout::recordFailure('otp', $phone);
        
        return response()->json([
            'error' => 'Invalid OTP',
            'attempts' => Lockout::getAttemptCount('otp', $phone)
        ], 401);
    }
}

'key_extractors' => [
    'user_session' => function ($request) {
        return $request->session()->getId();
    },
    'device_fingerprint' => function ($request) {
        return hash('sha256', $request->userAgent() . $request->ip());
    },
],

'contexts' => [
    'admin_login' => [
        'key' => 'device_fingerprint',
        'delays' => [300, 900, 1800, 7200],
    ],
],

'custom_response_callback' => function ($context, $key, $remainingTime) {
    return response()->json([
        'error' => 'Account temporarily locked',
        'context' => $context,
        'retry_after' => $remainingTime,
        'retry_after_human' => gmdate('H:i:s', $remainingTime),
    ], 429);
},

if (Lockout::isLockedOut('login', $email)) {
    $remainingTime = Lockout::getRemainingTime('login', $email);
    
    return response()->json([
        'error' => 'Account locked',
        'retry_after' => $remainingTime
    ], 429);
}

$info = Lockout::getLockoutInfo('login', $email);
/*
Returns:
[
    'context' => 'login',
    'key' => '[email protected]',
    'attempts' => 3,
    'is_locked_out' => true,
    'remaining_time' => 840,
    'locked_until' => Carbon instance,
    'last_attempt' => Carbon instance,
]
*/

// Record a failed attempt
Lockout::recordFailure(string $context, string $key): int

// Check if locked out
Lockout::isLockedOut(string $context, string $key): bool

// Get remaining lockout time in seconds
Lockout::getRemainingTime(string $context, string $key): int

// Clear lockout
Lockout::clear(string $context, string $key): bool

// Clear all lockouts for context
Lockout::clearContext(string $context): bool

// Get attempt count
Lockout::getAttemptCount(string $context, string $key): int

// Extract key from request
Lockout::extractKeyFromRequest(string $context, Request $request): string

// Get detailed lockout information
Lockout::getLockoutInfo(string $context, string $key): array

'context_templates' => [
    'strict' => [
        'enabled' => true,
        'min_attempts' => 1, // Lock immediately after 1st failure
        'delays' => [300, 900, 1800, 7200, 21600], // 5min → 15min → 30min → 2hr → 6hr
        'reset_after_hours' => 48, // Keep attempts longer
    ],
    'api' => [
        'enabled' => true,
        'response_mode' => 'json',
        'min_attempts' => 3,
        'delays' => [60, 300, 900, 1800, 7200],
        'reset_after_hours' => 24,
    ],
],

'contexts' => [
    'login' => [
        'extends' => 'api', // Inherit API template
        'key' => 'email',
        'redirect_route' => 'login', // Override specific setting
    ],
    'admin' => [
        'extends' => 'strict', // Inherit strict template
        'key' => 'email',
        'redirect_route' => 'admin.login',
    ],
],

'contexts' => [
    'login' => [
        'enabled' => true,                    // Enable/disable this context
        'key' => 'email',                     // Key extraction method
        'delays' => [60, 300, 900],          // Custom delay sequence
        'response_mode' => 'auto',            // Response handling mode
        'redirect_route' => 'login',          // Redirect route for web requests
        'max_attempts' => null,               // Max attempts (null = use delay sequence length)
        'min_attempts' => 3,                  // Attempts before first lockout
        'reset_after_hours' => 24,            // Reset attempts after inactivity
    ],
],

[60, 300, 900, 1800, 7200, 21600, 43200, 86400]
// 1min, 5min, 15min, 30min, 2hr, 6hr, 12hr, 24hr

'contexts' => [
    'otp' => [
        'delays' => [30, 60, 180, 300, 600], // Shorter for OTP
    ],
    'admin' => [
        'delays' => [600, 1800, 7200, 21600], // Longer for admin
    ],
],

try {
    Lockout::recordFailure('invalid_context', $key);
} catch (InvalidArgumentException $e) {
    // Context not configured or disabled
    Log::error('Lockout error: ' . $e->getMessage());
}

'cache' => [
    'store' => 'redis', // Use specific store
    'prefix' => 'app_lockout',
],

// config/cache.php
'stores' => [
    'lockout_redis' => [
        'driver' => 'redis',
        'connection' => 'lockout',
    ],
],

// config/database.php
'redis' => [
    'lockout' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'database' => 2, // Dedicated database
    ],
],

class LoginTest extends TestCase
{
    public function test_user_gets_locked_out_after_failures()
    {
        // Simulate multiple failed attempts
        for ($i = 0; $i < 3; $i++) {
            $this->post('/login', ['email' => '[email protected]', 'password' => 'wrong']);
        }
        
        // Verify lockout is active
        $this->assertTrue(Lockout::isLockedOut('login', '[email protected]'));
        
        // Test lockout response
        $response = $this->post('/login', ['email' => '[email protected]', 'password' => 'correct']);
        $response->assertStatus(429);
    }
}

// In your controller
Log::info('Lockout status', [
    'context' => 'login',
    'key' => $email,
    'info' => Lockout::getLockoutInfo('login', $email)
]);
bash
php artisan vendor:publish --tag=exponential-lockout-config
bash
# Clear lockout for specific context and key
php artisan lockout:clear login [email protected]

# Clear with force (no confirmation)
php artisan lockout:clear login [email protected] --force