# Security Features Setup Guide

## Overview
This guide explains how to enable and configure the new security features for the EPOLaw signup page to prevent spam and bot registrations.

## Features Implemented

### 1. Rate Limiting
- **Signup limit**: 3 attempts per hour per IP address
- **Login limit**: 10 attempts per hour per IP address
- **Global limit**: 200 requests per day per IP
- Automatically blocks IPs after 5 failed attempts for 1 hour

### 2. reCAPTCHA Integration
- Google reCAPTCHA v2 for human verification
- Prevents automated bot signups
- Gracefully degrades if not configured

### 3. Email Verification
- New users must verify their email before accessing the system
- Verification links expire after 24 hours
- Accounts remain inactive until verified

### 4. CSRF Protection
- All forms protected with CSRF tokens
- Prevents cross-site request forgery attacks

### 5. Honeypot Field
- Hidden field that only bots would fill
- Silently rejects submissions from bots

### 6. Enhanced Password Requirements
- Minimum 8 characters
- Must contain uppercase letters
- Must contain lowercase letters
- Must contain numbers
- Pattern enforced both client-side and server-side

### 7. IP Blocking
- Tracks failed login/signup attempts
- Blocks IPs after 5 failed attempts
- Automatic cleanup of old records after 24 hours

## Setup Instructions

### Step 1: Run Database Migration
```bash
cd /var/www/lawbot
python3 migrate_security.py
```

### Step 2: Configure reCAPTCHA (Optional but Recommended)

1. Go to [Google reCAPTCHA Admin](https://www.google.com/recaptcha/admin)
2. Register your site:
   - Label: EPOLaw
   - reCAPTCHA type: v2 - "I'm not a robot" Checkbox
   - Domains: Add your domain (e.g., epolaw.com)
3. Copy the Site Key and Secret Key
4. Add to `/var/www/lawbot/config/.env`:
```env
RECAPTCHA_SITE_KEY=your_site_key_here
RECAPTCHA_SECRET_KEY=your_secret_key_here
```

### Step 3: Configure Email Settings
Ensure your email configuration in `/var/www/lawbot/config/.env` is correct:
```env
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USE_TLS=True
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password
```

### Step 4: Optional Configuration
Edit `/var/www/lawbot/config/security_config.py` to adjust:
- Rate limits
- Password requirements
- Block duration
- Verification expiry time

### Step 5: Restart the Application
```bash
sudo systemctl restart apache2
```

## Testing the Security Features

### Test Rate Limiting
1. Try to sign up more than 3 times in an hour from the same IP
2. You should see "Too many attempts. Please try again later."

### Test reCAPTCHA
1. Try to submit the signup form without completing reCAPTCHA
2. You should see "Please complete the reCAPTCHA verification"

### Test Email Verification
1. Sign up with a valid email
2. Check email for verification link
3. Try to login before verifying - should be blocked
4. Click verification link and try again - should work

### Test Honeypot
1. Use browser developer tools to make the hidden "website" field visible
2. Fill it with any value and submit
3. Form should be rejected with "Invalid submission"

### Test Password Validation
1. Try passwords that don't meet requirements:
   - Less than 8 characters
   - No uppercase letters
   - No numbers
2. Each should show appropriate error message

## Monitoring

### View Failed Login Attempts
```sql
SELECT * FROM failed_login_attempts ORDER BY attempt_time DESC LIMIT 20;
```

### View Unverified Users
```sql
SELECT email, created_at, email_verification_sent_at 
FROM users 
WHERE email_verified = FALSE 
ORDER BY created_at DESC;
```

### Clean Up Old Failed Attempts (runs automatically)
```sql
DELETE FROM failed_login_attempts 
WHERE attempt_time < DATE_SUB(NOW(), INTERVAL 24 HOUR);
```

## Troubleshooting

### reCAPTCHA Not Showing
- Check that RECAPTCHA_SITE_KEY is set in .env
- Verify the domain is registered in Google reCAPTCHA admin
- Check browser console for JavaScript errors

### Emails Not Sending
- Verify SMTP settings in .env
- Check that email_config.py is properly configured
- Look for errors in Apache error logs: `sudo tail -f /var/log/apache2/error.log`

### Rate Limiting Too Strict
- Adjust limits in `/var/www/lawbot/config/security_config.py`
- Consider using Redis for distributed rate limiting in production

### Database Migration Fails
- Check MySQL user has ALTER and CREATE permissions
- Run migration with elevated privileges if needed
- Check for syntax errors in existing database schema

## Security Best Practices

1. **Keep reCAPTCHA Keys Secret**: Never commit them to version control
2. **Monitor Failed Attempts**: Regularly review failed_login_attempts table
3. **Update Dependencies**: Keep Flask-Limiter and Flask-WTF updated
4. **Use HTTPS**: Ensure all forms are submitted over HTTPS
5. **Regular Audits**: Review security logs monthly
6. **Backup Before Migration**: Always backup database before running migrations

## Support
For issues or questions about the security features, contact the development team or check the application logs at `/var/log/apache2/error.log`.