# Advanced Authentication Features - Quick Reference

## 🎯 What's New

### 1. **Registration** (2-Step with Email OTP)
- **URL:** `http://localhost/interior/auth-system/register.php`
- **Steps:** 
  - Step 1: Fill form (name, email, phone, password)
  - Step 2: Enter 6-digit OTP sent to email
- **Account:** Auto-created with `email_verified = 1`

### 2. **Forgot Password** (3-Step with OTP)
- **URL:** `http://localhost/interior/auth-system/forgot-password.php`
- **Steps:**
  - Step 1: Enter email address
  - Step 2: Enter OTP sent to email
  - Step 3: Enter new password
- **Result:** Password updated, redirect to login

### 3. **Two-Factor Authentication** (Optional 2FA)
- **Enable In:** User Settings page
- **Login Flow:** Password → Email OTP → Enter Code → Login
- **Per User:** Each user can enable/disable 2FA
- **Delivery:** 6-digit code sent via email

### 4. **User Dashboard**
- **URL:** `http://localhost/interior/auth-system/customer-dashboard.php`
- **Access:** Customer role only (after login)
- **Features:**
  - Welcome message
  - Account statistics
  - Recent orders list
  - Quick navigation menu

### 5. **User Profile**
- **URL:** `http://localhost/interior/auth-system/profile.php`
- **Edit Fields:** Name, Phone, City, Address
- **Read-Only:** Email (cannot change)
- **Displays:** Member since date

### 6. **Settings Page**
- **URL:** `http://localhost/interior/auth-system/settings.php`
- **Options:**
  - Change password (requires current password)
  - Enable/disable 2FA toggle
  - View account information

---

## 🔐 Security Features

| Feature | Details |
|---------|---------|
| **OTP Codes** | 6-digit numeric, 10-minute expiration |
| **Password Hash** | Bcrypt with PHP password_hash() |
| **Email Verified** | Required for registration |
| **2FA Optional** | Per-user toggle in settings |
| **Session Security** | Session-based with temporary multi-step vars |
| **Input Validation** | All fields validated server-side |
| **SQL Injection** | Protected with prepared statements |

---

## 📧 Email Service

### Methods Available
```php
EmailService::generateOTP($length = 6)              // Returns 6-digit code
EmailService::generateResetToken()                  // Returns 32-byte token
EmailService::sendEmailVerificationOTP($to, $name, $otp)
EmailService::sendPasswordResetEmail($to, $name, $link)
EmailService::send2FAOTP($to, $name, $otp)
EmailService::sendMail($to, $subject, $message)
```

### Email Templates
- Professional HTML emails
- Faren company branding
- Gold/beige color scheme (#D4A574)
- Mobile-responsive design
- Clear call-to-action buttons

---

## 🗄️ Database Tables

### otp_verification
```
id, email, otp_code, purpose, expires_at, created_at
```
**Purposes:** `email_verification`, `password_reset`, `2fa`

### password_resets
```
id, email, token, expires_at, used, created_at
```

### audit_logs
```
id, user_id, action, details, ip_address, created_at
```

### users (Modified)
Added fields:
- `email_verified` (BOOLEAN)
- `email_verified_at` (DATETIME)
- `two_factor_enabled` (BOOLEAN)
- `two_factor_secret` (VARCHAR)
- `password_changed_at` (DATETIME)

---

## 🧪 Test Scenarios

### Test 1: Register New Customer
```
1. Go to /register.php
2. Enter: name, email, phone, password
3. Watch for OTP email notification
4. Enter 6-digit OTP code
5. Success: Redirected to login
```

### Test 2: Login Without 2FA
```
1. Go to /login.php
2. Select "Customer" role
3. Enter: email, password
4. Click "Sign In"
5. Success: Redirected to dashboard
```

### Test 3: Login With 2FA
```
1. Go to /settings.php (while logged in)
2. Toggle ON: "Enable Two-Factor Authentication"
3. Logout
4. Go to /login.php
5. Enter: email, password
6. Page 2: Enter 6-digit OTP
7. Success: Redirected to dashboard
```

### Test 4: Forgot Password
```
1. Go to /forgot-password.php
2. Enter: registered email
3. Check for OTP email
4. Enter 6-digit OTP
5. Enter: new password twice
6. Success: Redirected to login
7. Login with new password
```

### Test 5: Edit Profile
```
1. Login as customer
2. Go to /profile.php
3. Update: name, phone, city, address
4. Click "Save Changes"
5. Success: Profile updated
```

### Test 6: Change Password
```
1. Login as customer
2. Go to /settings.php
3. Enter: current password, new password (x2)
4. Click "Update Password"
5. Success: Password changed
6. Can login with new password
```

---

## 📋 File Checklist

```
✅ register.php               - 2-step registration with OTP
✅ login.php                  - Login with optional 2FA
✅ forgot-password.php        - 3-step password reset
✅ customer-dashboard.php     - User dashboard
✅ profile.php                - Profile editor
✅ settings.php               - Settings & security
✅ EmailService.php           - Email utility class
✅ setup-advanced-auth.php    - Database setup (RUN ONCE)
✅ ADVANCED_AUTH_GUIDE.md     - Full documentation
✅ QUICK_REFERENCE.md         - This file
```

---

## 🚀 Quick Start

### 1. Verify Setup
```
Visit: http://localhost/interior/auth-system/setup-advanced-auth.php
Should see: "✓ All operations completed successfully"
```

### 2. Test Registration
```
Visit: http://localhost/interior/auth-system/register.php
Complete 2-step registration with OTP verification
```

### 3. Test Login
```
Visit: http://localhost/interior/auth-system/login.php
Login as customer (no 2FA yet)
```

### 4. Enable 2FA
```
While logged in: Go to /settings.php
Toggle 2FA ON and save
Logout and login again to see 2FA in action
```

### 5. Test Forgot Password
```
Visit: /forgot-password.php
Complete 3-step password reset process
```

---

## ⚙️ Configuration

### OTP Settings
- **Length:** 6 digits
- **Expiration:** 10 minutes
- **Location:** `register.php`, `login.php`, `forgot-password.php`
- **Change:** Find `strtotime('+10 minutes')` and adjust

### Email Settings
- **Method:** PHP mail() function
- **Config:** php.ini sendmail_path or SMTP
- **Templates:** All in EmailService.php
- **Test:** Check database `otp_verification` table for codes

### 2FA Settings
- **Type:** Email-based OTP
- **Toggle:** Per-user in settings.php
- **Optional:** Users can enable/disable
- **Enforcement:** Not mandatory

---

## 🔍 Debugging

### Check if tables created
```sql
SELECT TABLE_NAME FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'database_name'
AND TABLE_NAME IN ('otp_verification', 'password_resets', 'audit_logs');
```

### Check OTP codes
```sql
SELECT * FROM otp_verification 
WHERE email = 'test@email.com' 
ORDER BY created_at DESC 
LIMIT 5;
```

### Check user 2FA status
```sql
SELECT id, email, name, two_factor_enabled, email_verified 
FROM users 
WHERE email = 'test@email.com';
```

### Clear expired OTPs
```sql
DELETE FROM otp_verification 
WHERE expires_at < NOW();
```

---

## 📞 Support

### Common Issues

**"OTP not received"**
- Check: PHP mail configuration
- Check: `otp_verification` table has entries
- Check: Email address is correct

**"Cannot login with 2FA"**
- Verify: 2FA enabled in settings
- Check: OTP hasn't expired (10 min limit)
- Check: Email deliverability

**"Forgot password not working"**
- Verify: Email exists in users table
- Check: OTP table entries being created
- Check: Email sending configured

**"Profile won't update"**
- Verify: Logged in as customer
- Check: Session valid and not expired
- Check: Database permissions

---

## 📊 Status Summary

| Component | Status | Notes |
|-----------|--------|-------|
| Registration | ✅ Complete | 2-step with OTP |
| Login | ✅ Complete | Optional 2FA |
| Forgot Password | ✅ Complete | 3-step flow |
| Dashboard | ✅ Complete | Full functionality |
| Profile Editor | ✅ Complete | All fields editable |
| Settings | ✅ Complete | Password + 2FA |
| Email Service | ✅ Complete | All templates ready |
| Database | ✅ Complete | All tables created |
| Documentation | ✅ Complete | Comprehensive guides |

---

## 🎉 Ready for Production

All advanced authentication features are:
- ✅ Fully implemented
- ✅ Tested and validated
- ✅ Security best practices applied
- ✅ Database optimized with indexes
- ✅ Error handling comprehensive
- ✅ Mobile responsive
- ✅ Professionally styled
- ✅ Well documented

**Status:** READY FOR DEPLOYMENT
