# OTP Verification System Plan

## Overview
Implement One-Time Password (OTP) email verification system after user registration. Users must verify their email with an OTP code before they can log in.

## Email Configuration
- **SMTP Server**: mail.wakelai.com
- **Port**: 465 (SSL)
- **Username**: welcome@wakelai.com
- **Password**: iXnG6D4I#9&{}-E=
- **From**: welcome@wakelai.com

## Architecture

### 1. Database Schema Changes

Add new fields to `User` model in `prisma/schema.prisma`:

```prisma
model User {
  // ... existing fields ...
  otp_code              String?              @db.VarChar(10)
  otp_expires_at        DateTime?
  otp_attempts          Int                  @default(0)
  is_otp_verified       Boolean              @default(false)
}
```

### 2. New Dependencies

Install required packages:
```bash
npm install nodemailer@6.9.7
npm install @types/nodemailer@6.4.14
```

### 3. File Structure

Create new files:
```
src/
├── lib/
│   ├── email-service.ts      # Nodemailer wrapper
│   └── otp-service.ts        # OTP generation/validation
├── app/
│   ├── api/
│   │   ├── auth/
│   │   │   ├── send-otp/
│   │   │   │   └── route.ts
│   │   │   └── verify-otp/
│   │   │       └── route.ts
│   ├── register/
│   │   └── verify-otp/
│   │       └── page.tsx
│   └── login/
│       └── page.tsx          # Update to check verification
└── components/
    ├── auth/
    │   ├── register-form.tsx     # Update registration flow
    │   ├── otp-verification.tsx   # New OTP form component
    │   └── login-form.tsx         # Update to show verification error
```

### 4. Implementation Flow

#### Registration Flow:
1. User fills registration form (username, email, password)
2. User is created with `email_verified: false`, `is_otp_verified: false`
3. Generate 6-digit OTP code
4. Send OTP email to user
5. Redirect to `/register/verify-otp` page
6. User enters OTP
7. If valid: set `is_otp_verified: true`, redirect to dashboard
8. If invalid: show error, allow retry (max 3 attempts)

#### Login Flow:
1. User enters email/password
2. Check if `is_otp_verified: true`
3. If NOT verified: return error "Please verify your email first"
4. If verified: proceed with normal authentication

### 5. API Endpoints

#### POST /api/auth/send-otp
**Request**: `{ "email": string }`
**Response**: `{ "ok": true, "expiresAt": timestamp }`
**Logic**:
- Generate 6-digit random OTP
- Store in DB with 10-minute expiration
- Send email via SMTP
- Rate limit: max 3 OTPs per hour per email

#### POST /api/auth/verify-otp
**Request**: `{ "email": string, "otp": string }`
**Response**: `{ "ok": true }` or `{ "error": string }`
**Logic**:
- Validate OTP matches
- Check not expired
- Check attempts < 3
- On success: set `is_otp_verified: true`, clear OTP
- On failure: increment attempts

### 6. Email Template

```
Subject: Verify Your Wakel AI Account

Hello {username},

Your verification code is: {OTP_CODE}

This code will expire in 10 minutes.

If you didn't request this code, please ignore this email.

---
Wakel AI - Your AI Assistant Platform
https://wakelai.com
```

### 7. Environment Variables

Add to `.env`:
```env
# SMTP Configuration
SMTP_HOST=mail.wakelai.com
SMTP_PORT=465
SMTP_SECURE=true
SMTP_USER=welcome@wakelai.com
SMTP_PASSWORD=iXnG6D4I#9&{}-E=
SMTP_FROM_NAME=Wakel AI
SMTP_FROM_EMAIL=welcome@wakelai.com

# OTP Settings
OTP_LENGTH=6
OTP_EXPIRY_MINUTES=10
OTP_MAX_ATTEMPTS=3
OTP_MAX_PER_HOUR=3
```

### 8. Security Considerations

1. **Rate Limiting**: Max 3 OTP requests per hour per email
2. **Attempts Limit**: Max 3 verification attempts per OTP
3. **Expiration**: OTP codes expire after 10 minutes
4. **Secure Storage**: OTP hashed before storing (bcrypt)
5. **Login Block**: Users cannot login without verification
6. **Resend Option**: Allow requesting new OTP after current expires

### 9. Frontend Components

#### otp-verification.tsx
- 6-digit input field (single box or individual boxes)
- Countdown timer showing expiration
- Resend OTP button (disabled during cooldown)
- Error message display
- Success: auto-redirect to dashboard

#### Updated register-form.tsx
- After successful registration → redirect to OTP page
- Store email in sessionStorage for OTP page

#### Updated login-form.tsx
- Check if user is verified
- Show error if not: "Please verify your email first. Resend code?"

### 10. Testing Checklist

- [ ] New registration sends OTP email
- [ ] OTP code works correctly
- [ ] Invalid OTP shows error
- [ ] Expired OTP shows error
- [ ] After 3 failed attempts, require new OTP
- [ ] Resend OTP works (after expiration)
- [ ] Non-verified users cannot login
- [ ] Verified users can login normally
- [ ] Email template renders correctly
- [ ] Rate limiting works

### 11. Migration Plan

```sql
-- Add OTP fields to existing users table
ALTER TABLE users ADD COLUMN otp_code VARCHAR(10);
ALTER TABLE users ADD COLUMN otp_expires_at TIMESTAMP;
ALTER TABLE users ADD COLUMN otp_attempts INTEGER DEFAULT 0;
ALTER TABLE users ADD COLUMN is_otp_verified BOOLEAN DEFAULT false;

-- For existing users, mark them as verified (they already registered)
UPDATE users SET is_otp_verified = true WHERE email_verified = true;
```

## Implementation Order

1. **Phase 1**: Database schema + migration
2. **Phase 2**: Install dependencies + environment setup
3. **Phase 3**: Email service + OTP service (backend)
4. **Phase 4**: API endpoints (send-otp, verify-otp)
5. **Phase 5**: Frontend OTP verification page
6. **Phase 6**: Update registration flow
7. **Phase 7**: Update login flow
8. **Phase 8**: Testing + deployment
