# Multi-User Login Feature

## Overview

Your email client now supports **multi-user login** where each user can authenticate with their own email account and see only their own emails.

## ✨ Features

✅ **Individual User Authentication**
- Each user logs in with their own email and password
- Credentials validated against the mail server (IMAP)
- No password storage - only validated on login

✅ **Secure Session Management**
- 7-day persistent login sessions
- HTTP-only secure cookies (encrypted)
- Automatic logout after 7 days
- Manual logout button available

✅ **Per-User Email Access**
- Each logged-in user sees only their own emails
- Fetches from their own mail account via IMAP
- Sends from their own account via SMTP

✅ **Flexible Mail Server Support**
- Use default mail server from .env (EMAIL_HOST)
- Or specify custom mail server during login for each user
- Supports IMAP port 993 (TLS) or 143 (STARTTLS)
- Supports SMTP port 465 (TLS) or 587 (STARTTLS)

---

## 🔑 How It Works

### Login Flow

```
User opens app → No session found
           ↓
    Login page appears
           ↓
User enters email + password
           ↓
System tests IMAP connection
           ↓
✓ Connection works → Session created (7 days)
✗ Connection fails → Error message shown
           ↓
Redirected to email client
```

### Session Storage

- Credentials stored in **HTTP-only secure cookie**
- Cookie encrypted with JWT (JSON Web Token)
- Only lasts 7 days (configurable)
- Cleared when user clicks "Logout"

### Email Fetching

1. User logged in with `user@domain.com` and password
2. When fetching emails:
   - Uses stored credentials from session
   - Connects to IMAP server
   - Fetches from their INBOX
   - Returns only their emails

---

## 👥 User Scenarios

### Scenario 1: Shared Mail Server
```
Mail Server: mail.yourdomain.com

User 1: alice@yourdomain.com (password: alice123)
User 2: bob@yourdomain.com (password: bob456)
User 3: carol@yourdomain.com (password: carol789)

All use same mail server, but each sees only their own emails
```

### Scenario 2: Custom Mail Servers per User
```
User 1: alice@company1.com
  - Mail Server: mail.company1.com

User 2: bob@company2.com
  - Mail Server: mail.company2.com

Each user specifies their own mail server during login
```

### Scenario 3: Team Collaboration
```
SharedTeamEmail: team@yourdomain.com
Team members login with same email/password
Everyone sees the same shared inbox
```

---

## 🚀 Getting Started

### Installation

```bash
# Install dependencies (includes jose for JWT)
npm ci

# Build application
npm run build

# Start application
npm start
```

### Environment Setup

Create `.env` file from `.env.example`:

```bash
cp .env.example .env
nano .env
```

Configure:

```env
# Default mail server (optional, users can override)
EMAIL_HOST=mail.yourdomain.com
EMAIL_IMAP_PORT=993
EMAIL_SMTP_PORT=465
EMAIL_FROM_NAME=TagneticAI

# Session encryption (generate a random string)
JWT_SECRET=your-random-secret-key-change-this-in-production

# App configuration
NODE_ENV=production
PORT=3000
NEXT_PUBLIC_API_URL=https://email.yourdomain.com
```

### Generate JWT Secret

```bash
# On Linux/Mac
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

# On Windows PowerShell
node -e "[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))")'))"

# Or use any random string (minimum recommended: 32 characters)
JWT_SECRET=abcdefghijklmnopqrstuvwxyz123456
```

---

## 📱 User Interface

### Login Page

When no session exists, users see:

```
┌─────────────────────────────────┐
│       🌐 TagneticAI             │
│      Email Client               │
├─────────────────────────────────┤
│  Email Address                  │
│  ┌──────────────────────────┐  │
│  │ you@example.com          │  │
│  └──────────────────────────┘  │
│                                 │
│  Password                       │
│  ┌──────────────────────────┐  │
│  │ ••••••••••               │  │
│  └──────────────────────────┘  │
│                                 │
│  ▶ Advanced: Custom Mail Server │
│    [Mail server host...]        │
│                                 │
│   [Sign In Button]              │
│                                 │
│ 💡 Credentials validated against │
│    mail server. Password not     │
│    stored.                       │
└─────────────────────────────────┘
```

### Logout Button

In the Sidebar footer:

```
[🔄 Refresh] [☀️ Light] [🚪 Logout]
```

Click "Logout" to clear session and return to login page.

---

## 🔒 Security

### What We Do ✅
- Validate credentials against real mail server (IMAP)
- Never store passwords in database
- Use secure HTTP-only cookies
- Encrypt session with JWT
- HTTPS in production (SSL/TLS)
- 7-day session expiration

### What We Don't Do ❌
- Never save passwords
- Never transmit credentials in URL
- Never store unencrypted sessions
- Never log sensitive information

### Best Practices

1. **Change JWT_SECRET in production**
   ```bash
   # Generate strong random secret
   node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
   ```

2. **Use HTTPS always**
   - Configure SSL/TLS certificate
   - Force HTTPS redirect (port 80 → 443)

3. **Protect your mail server**
   - Use strong passwords
   - Enable 2FA on mail server if available
   - Limit IMAP/SMTP access by IP if needed

4. **Monitor for abuse**
   - Check mail server logs
   - Monitor failed login attempts
   - Set up rate limiting if needed

---

## 🔧 Configuration

### Session Duration

To change from 7 days to different duration:

**File**: `lib/auth.ts`

```typescript
// Change this line:
const expiresAt = Date.now() + 7 * 24 * 60 * 60 * 1000; // 7 days

// To (example: 24 hours):
const expiresAt = Date.now() + 24 * 60 * 60 * 1000; // 1 day

// Or (example: 30 days):
const expiresAt = Date.now() + 30 * 24 * 60 * 60 * 1000; // 30 days
```

### Default Mail Server

Users must have `EMAIL_HOST` configured in `.env` to use default:

```env
EMAIL_HOST=mail.yourdomain.com
EMAIL_IMAP_PORT=993
EMAIL_SMTP_PORT=465
```

Users can override by entering custom mail server in login form.

### Disable Custom Mail Server

If you want to prevent users from specifying custom mail servers:

**File**: `components/LoginPage.tsx`

Remove or hide this section:

```tsx
{/* Mail Server Host (Optional) */}
<div className="pt-2">
  <details className="text-sm">
    {/* ... remove this entire section ... */}
  </details>
</div>
```

---

## 🧪 Testing

### Test Login

```bash
# 1. Start application
npm run dev

# 2. Open browser
http://localhost:3000

# 3. Enter test credentials
Email: your-email@example.com
Password: your-password
Mail Server: (leave blank to use EMAIL_HOST)

# 4. Should redirect to email client
```

### Test Logout

```bash
# 1. Click "Logout" button in sidebar
# 2. Should return to login page
# 3. Session cookie cleared
# 4. Must login again
```

### Test Session Persistence

```bash
# 1. Login successfully
# 2. Close browser / tab
# 3. Reopen application
# 4. Should still be logged in (within 7 days)
# 5. Click refresh or navigate - still logged in
```

### Test Invalid Credentials

```bash
# 1. Enter wrong password
# 2. Should show error: "Invalid email or password"
# 3. Login page still shown
```

---

## 🚀 Deployment

### cPanel Deployment

See **CPANEL-DEPLOYMENT.md** for detailed instructions.

### VPS Deployment

See **WHMCS-DEPLOYMENT.md** for detailed instructions.

### Important: Set JWT_SECRET

Before deploying, generate and set JWT_SECRET:

```bash
# Generate strong secret
NODE_SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")

# Add to .env on server
echo "JWT_SECRET=$NODE_SECRET" >> /opt/tagneticai-email/.env
```

---

## 📊 API Endpoints

### Authentication

#### `POST /api/auth/login`

**Request**:
```json
{
  "email": "user@example.com",
  "password": "their-password",
  "mailHost": "mail.custom.com" // optional
}
```

**Response (Success)**:
```json
{
  "success": true,
  "message": "Login successful"
}
```

**Response (Error)**:
```json
{
  "error": "Invalid email or password"
}
```

#### `POST /api/auth/logout`

**Request**: (no body)

**Response**:
```json
{
  "success": true,
  "message": "Logged out successfully"
}
```

### Email APIs (Require Authentication)

#### `GET /api/emails`

**Requires**: Valid session

**Response**:
```json
[
  {
    "id": "123",
    "subject": "Hello",
    "from": "sender@example.com",
    "date": "2024-01-15T10:30:00Z",
    "snippet": "Hi, how are you?...",
    "unread": true,
    "body": "...",
    "html": "<p>...</p>"
  }
]
```

#### `POST /api/send`

**Requires**: Valid session

**Request**:
```json
{
  "to": "recipient@example.com",
  "subject": "Reply",
  "text": "Thanks for the email!",
  "html": "<p>Thanks for the email!</p>",
  "cc": "optional@example.com",
  "bcc": "hidden@example.com"
}
```

**Response**:
```json
{
  "success": true,
  "message": "Email sent successfully",
  "messageId": "..."
}
```

---

## 🐛 Troubleshooting

### Problem: "Invalid email or password"

**Causes**:
- Wrong email or password
- Mail server down
- Firewall blocking IMAP connection

**Solutions**:
1. Verify email and password
2. Test connection manually:
   ```bash
   telnet mail.yourdomain.com 993
   ```
3. Check firewall allows IMAP/SMTP ports
4. Ask mail server administrator

### Problem: "Session expired"

**Cause**: Session older than 7 days

**Solution**: Login again

### Problem: "Can't reach mail server"

**Causes**:
- Wrong mail server hostname
- Wrong port number
- Firewall/network issue

**Solutions**:
1. Verify mail server hostname
2. Check port is 993 (IMAP TLS) or 143 (STARTTLS)
3. Verify firewall allows outbound on that port
4. Check network connectivity

### Problem: "Unauthorized" error

**Cause**: Session invalid or expired

**Solution**: Clear cookies and login again

```bash
# Clear cookies in browser developer tools
# Or logout and login again
```

---

## 📚 File Structure

```
app/
├── api/
│   ├── auth/
│   │   ├── login/route.ts       ← Login endpoint
│   │   └── logout/route.ts      ← Logout endpoint
│   ├── emails/route.ts          ← Modified: Uses session
│   └── send/route.ts            ← Modified: Uses session
├── page.tsx                     ← Modified: Added login check
└── layout.tsx

components/
├── LoginPage.tsx                ← New: Login form
├── Sidebar.tsx                  ← Modified: Added logout button
├── EmailList.tsx                ← No changes
├── ReadingPane.tsx              ← No changes
└── ReplyBox.tsx                 ← No changes

lib/
└── auth.ts                      ← New: Session management

.env.example                     ← Added: JWT_SECRET
package.json                     ← Added: jose dependency
```

---

## 🎯 Key Changes from Original

| Component | Change | Purpose |
|-----------|--------|---------|
| `app/page.tsx` | Added login check | Show login before email client |
| `components/LoginPage.tsx` | NEW | User authentication form |
| `components/Sidebar.tsx` | Added logout button | Let users logout |
| `app/api/emails/route.ts` | Use session credentials | Per-user email fetching |
| `app/api/send/route.ts` | Use session credentials | Per-user email sending |
| `lib/auth.ts` | NEW | JWT session management |
| `app/api/auth/login/route.ts` | NEW | Login endpoint |
| `app/api/auth/logout/route.ts` | NEW | Logout endpoint |
| `package.json` | Added `jose` | JWT handling |
| `.env.example` | Added `JWT_SECRET` | Session encryption |

---

## 🚀 Next Steps

1. **Install dependencies**:
   ```bash
   npm ci
   ```

2. **Configure environment**:
   ```bash
   cp .env.example .env
   # Edit .env with your mail server details
   # Generate JWT_SECRET
   ```

3. **Build application**:
   ```bash
   npm run build
   ```

4. **Deploy to your server**:
   - Follow CPANEL-DEPLOYMENT.md or WHMCS-DEPLOYMENT.md

5. **Test login**:
   - Visit `https://email.yourdomain.com`
   - Login with any user's credentials
   - Verify emails appear
   - Test logout and login again

---

## ✅ Verification Checklist

- [ ] `npm ci` installs without errors
- [ ] `npm run build` succeeds
- [ ] `npm start` starts without errors
- [ ] App loads to login page
- [ ] Can login with valid credentials
- [ ] Emails appear after login
- [ ] Can logout successfully
- [ ] After logout, shows login page again
- [ ] Invalid credentials show error
- [ ] Session persists after page refresh
- [ ] 7-day session expires correctly
- [ ] Can reply to emails (uses logged-in user)
- [ ] Can send emails from logged-in user account

---

## 🎉 You're All Set!

Your multi-user email client is ready for deployment.

**Each team member can now**:
1. Login with their own email credentials
2. See only their own emails
3. Compose and reply emails from their account
4. Logout when done

Perfect for team environments where people access different email accounts! 📧✨
