# Authentication Guide

## Overview

This backend supports two authentication methods:

1. **JWT Auth** (Recommended) - Fast, local token verification
2. **Clerk Auth** - Direct Clerk session verification

## Authentication Flow

### Frontend (React + Clerk)

```javascript
// 1. User signs in with Clerk
const { user } = useUser();

// 2. Send user data to backend login endpoint
const userData = {
  user_type: "direct_client",
  clerk_user_id: user.id,
  email: user.primaryEmailAddress?.emailAddress,
  first_name: user.firstName,
  last_name: user.lastName,
  full_name: user.fullName,
  image_url: user.imageUrl,
};

const response = await axios.post(
  "http://localhost:5000/api/auth/login",
  userData
);

// 3. Store JWT token
const { token } = response.data.data;
localStorage.setItem("token", token);

// 4. Use token for subsequent API calls
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
```

### Backend Auth Options

#### Option 1: JWT Auth (Recommended)

**Pros:**
- Fast (no external API calls)
- Works offline
- Lower latency
- No rate limits

**Usage:**
```javascript
import { auth } from "../middleware/index.js";

router.post("/locations", auth, locationController.createLocation);
```

**How it works:**
1. Frontend sends JWT token in `Authorization: Bearer <token>` header
2. Backend verifies JWT locally using `JWT_SECRET`
3. Attaches user info to `req.user`

#### Option 2: Clerk Auth

**Pros:**
- Real-time session validation
- Automatic revocation support
- Clerk manages token lifecycle

**Cons:**
- Slower (external API call)
- Requires internet connection
- Subject to Clerk rate limits

**Usage:**
```javascript
import { clerkAuth } from "../middleware/index.js";

router.post("/locations", clerkAuth, locationController.createLocation);
```

**How it works:**
1. Frontend sends Clerk session token in `Authorization: Bearer <token>` header
2. Backend verifies token with Clerk API
3. Fetches user from database using `clerk_user_id`
4. Attaches user info to `req.user`

## Request Object

Both auth methods attach the same structure to `req.user`:

```javascript
req.user = {
  user_id: 123,           // Your database user ID
  account_id: 456,        // Your database account ID
  email: "user@example.com",
  clerk_user_id: "user_xxx" // Only with clerkAuth
};
```

## Environment Variables

```env
# JWT
JWT_SECRET="your-secret-key"

# Clerk
CLERK_API_KEY=sk_test_xxx
CLERK_PUBLISHABLE_KEY=pk_test_xxx
```

## Recommendation

**Use JWT Auth** for most routes. It's faster, more reliable, and follows industry best practices.

Only use Clerk Auth if you need:
- Real-time session revocation
- Clerk-specific user metadata
- Direct Clerk integration features
