# Laravel Multi-Provider CAPTCHA Package

[![Latest Version](https://img.shields.io/packagist/v/dariusmure/laravel-captcha.svg)](https://packagist.org/packages/dariusmure/laravel-captcha)
[![License](https://img.shields.io/packagist/l/dariusmure/laravel-captcha.svg)](https://packagist.org/packages/dariusmure/laravel-captcha)

A comprehensive CAPTCHA package for Laravel with support for multiple providers:
- **hCaptcha** - Privacy-focused CAPTCHA
- **reCAPTCHA v2** - Classic checkbox CAPTCHA
- **reCAPTCHA v2 Invisible** - Invisible CAPTCHA
- **reCAPTCHA v3** - Score-based CAPTCHA (0.0-1.0)
- **Cloudflare Turnstile** - Modern, fast CAPTCHA
- **TrustIP** - IP-based verification

## Features

✨ **Multi-Provider Support** - Switch between providers easily
🔄 **Automatic Fallback** - Fallback to secondary provider if primary fails
🛡️ **Rate Limiting** - Built-in protection against abuse
📊 **Statistics Tracking** - Monitor verification success rates and response times
🎯 **Location-Based** - Enable CAPTCHA for specific forms (login, register, etc.)
🧪 **Testing Mode** - Bypass CAPTCHA in development
🔐 **IP Whitelist** - Exclude trusted IPs from verification
⚡ **Performance** - Cached configuration and optimized queries

## Installation

Install the package via Composer:

```bash
composer require dariusmure/laravel-captcha
```

Publish the configuration file:

```bash
php artisan vendor:publish --provider="DariusMure\Captcha\CaptchaServiceProvider" --tag="config"
```

Publish the migrations:

```bash
php artisan vendor:publish --provider="DariusMure\Captcha\CaptchaServiceProvider" --tag="migrations"
```

Run migrations:

```bash
php artisan migrate
```

Publish views (optional):

```bash
php artisan vendor:publish --provider="DariusMure\Captcha\CaptchaServiceProvider" --tag="views"
```

## Configuration

### Environment Variables

Add to your `.env` file:

```env
# Enable CAPTCHA
CAPTCHA_ENABLED=true
CAPTCHA_PROVIDER=hcaptcha

# Testing Mode
CAPTCHA_TESTING_MODE=false

# hCaptcha
HCAPTCHA_SITE_KEY=your-site-key
HCAPTCHA_SECRET_KEY=your-secret-key

# reCAPTCHA v2
RECAPTCHA_V2_SITE_KEY=your-site-key
RECAPTCHA_V2_SECRET_KEY=your-secret-key

# reCAPTCHA v2 Invisible
RECAPTCHA_V2_INVISIBLE_SITE_KEY=your-site-key
RECAPTCHA_V2_INVISIBLE_SECRET_KEY=your-secret-key

# reCAPTCHA v3
RECAPTCHA_V3_SITE_KEY=your-site-key
RECAPTCHA_V3_SECRET_KEY=your-secret-key
RECAPTCHA_V3_THRESHOLD=0.5

# Cloudflare Turnstile
TURNSTILE_SITE_KEY=your-site-key
TURNSTILE_SECRET_KEY=your-secret-key

# TrustIP
TRUSTIP_API_KEY=your-api-key
```

### Provider Keys

Get your keys from:
- **hCaptcha**: https://dashboard.hcaptcha.com/
- **reCAPTCHA**: https://www.google.com/recaptcha/admin
- **Turnstile**: https://dash.cloudflare.com/
- **TrustIP**: https://trustip.io/

## Usage

### Blade Component

Add CAPTCHA to any form:

```blade
<form method="POST" action="/login">
    @csrf
    
    <!-- Your form fields -->
    
    <x-captcha location="login" />
    
    <button type="submit">Login</button>
</form>
```

### Middleware

Protect routes with the CAPTCHA middleware:

```php
// In routes/web.php
Route::post('/login', [LoginController::class, 'login'])
    ->middleware('captcha:login');

Route::post('/register', [RegisterController::class, 'register'])
    ->middleware('captcha:register');

Route::post('/contact', [ContactController::class, 'send'])
    ->middleware('captcha:contact');
```

### Manual Verification

Verify CAPTCHA manually in your controller:

```php
use DariusMure\Captcha\Facades\Captcha;

public function login(Request $request)
{
    $result = Captcha::verify(
        $request->input('g-recaptcha-response'),
        'login',
        $request->ip()
    );
    
    if (!$result['success']) {
        return back()->withErrors([
            'captcha' => $result['error'] ?? 'CAPTCHA verification failed'
        ]);
    }
    
    // Continue with login logic
}
```

### Available Locations

- `login` - Login form
- `register` - Registration form
- `forgot_password` - Password reset form
- `contact` - Contact form
- `api` - API requests

## Admin Panel Integration

The package includes a complete admin interface for configuration:

```php
// In routes/web.php
Route::middleware(['auth', 'admin'])->group(function () {
    Route::get('/admin/captcha', [\DariusMure\Captcha\Http\Controllers\CaptchaController::class, 'index'])
        ->name('admin.captcha.index');
    Route::post('/admin/captcha', [\DariusMure\Captcha\Http\Controllers\CaptchaController::class, 'update'])
        ->name('admin.captcha.update');
});
```

## Statistics

Get verification statistics:

```php
use DariusMure\Captcha\Facades\Captcha;

// Get statistics for last 7 days
$stats = Captcha::getStatistics(7);

// Get success rate for a provider
$successRate = \DariusMure\Captcha\Models\CaptchaStatistic::getSuccessRate('hcaptcha', 7);

// Get average response time
$avgTime = \DariusMure\Captcha\Models\CaptchaStatistic::getAverageResponseTime('hcaptcha', 7);
```

## Testing

Enable testing mode in `.env`:

```env
CAPTCHA_TESTING_MODE=true
```

This will bypass all CAPTCHA verifications in development.

## API Reference

### Captcha Facade

```php
// Check if CAPTCHA is enabled
Captcha::isEnabled('login'); // bool

// Check if IP is whitelisted
Captcha::isWhitelisted('127.0.0.1'); // bool

// Verify CAPTCHA response
Captcha::verify($response, $location, $ip); // array

// Get provider name
Captcha::getProviderName(); // string

// Get site key
Captcha::getSiteKey(); // string

// Render CAPTCHA HTML
Captcha::render(['class' => 'my-captcha']); // string

// Clear cached settings
Captcha::clearCache(); // void
```

## Database Structure

### captcha_settings
- Provider configuration
- Location settings
- Whitelist IPs
- Fallback configuration

### captcha_statistics
- Verification attempts
- Success/failure rates
- Response times
- Score tracking (for reCAPTCHA v3)

### captcha_rate_limits
- IP-based rate limiting
- Failed attempt tracking
- Automatic blocking

## Security

- Rate limiting prevents brute force attacks
- IP whitelist for trusted sources
- Automatic fallback prevents service disruption
- Statistics help identify attack patterns

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

## Credits

- **Darius Mure** - [GitHub](https://github.com/dariusmure)

## Support

For issues and feature requests, please use the [GitHub issue tracker](https://github.com/dariusmure/laravel-captcha/issues).
