> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vchata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication Controller

> Complete authentication and user management API endpoints

# Authentication Controller

The Authentication Controller provides secure user registration, login, profile management, and session handling for the VChata platform.

## Base Path

```
/auth
```

## Endpoints

### Sign Up

<RequestExample>
  ```http theme={null}
  POST /auth/signup
  Content-Type: application/json

  {
    "email": "john.doe@example.com",
    "password": "SecurePassword123!",
    "firstName": "John",
    "lastName": "Doe",
    "organizationName": "Acme Corp",
    "timezone": "America/New_York",
    "paymentMethodId": "pm_1234567890"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "user": {
      "id": "usr_abc123",
      "email": "john.doe@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "authProvider": "LOCAL",
      "createdAt": "2024-01-15T10:00:00Z"
    },
    "organization": {
      "id": "org_xyz789",
      "name": "Acme Corp",
      "createdAt": "2024-01-15T10:00:00Z"
    },
    "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "message": "User and organization created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates a new user account along with an organization. This endpoint:

* Validates email uniqueness across the platform
* Creates user with encrypted password
* Automatically creates an organization
* Creates Stripe customer and attaches payment method
* Assigns the user as organization admin
* Sets long-lived auth token (7 days) as secure httpOnly cookie

<Note>
  **Payment Required**: A valid payment method ID from PaymentElement is required for account activation.
</Note>

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="email" type="string" required>
      User's email address (must be unique)
    </ParamField>

    <ParamField path="password" type="string" required>
      Password (minimum 8 characters)
    </ParamField>

    <ParamField path="firstName" type="string" required>
      User's first name
    </ParamField>

    <ParamField path="lastName" type="string" required>
      User's last name
    </ParamField>

    <ParamField path="organizationName" type="string" required>
      Name for the new organization
    </ParamField>

    <ParamField path="timezone" type="string" required>
      User's timezone (e.g., "America/New\_York")
    </ParamField>

    <ParamField path="paymentMethodId" type="string" required>
      Stripe payment method ID for billing
    </ParamField>
  </Expandable>
</ParamField>

### Login

<RequestExample>
  ```http theme={null}
  POST /auth/login
  Content-Type: application/json

  {
    "email": "john.doe@example.com",
    "password": "SecurePassword123!"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "user": {
      "id": "usr_abc123",
      "email": "john.doe@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "authProvider": "LOCAL",
      "avatar": "https://api.dicebear.com/7.x/avataaars/svg?seed=john.doe"
    },
    "organizations": [
      {
        "id": "org_xyz789",
        "name": "Acme Corp",
        "role": "ADMIN",
        "joinedAt": "2024-01-15T10:00:00Z"
      }
    ],
    "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "message": "Login successful"
  }
  ```
</ResponseExample>

**Description**: Authenticates a user with email and password using secure cookie-based authentication.

**Cookie-Based Authentication**:

* Auth Token: Valid for 7 days, stored in secure httpOnly cookie
* Cookie is automatically sent with all requests
* No Authorization headers needed - cookies handle authentication
* No refresh needed - long-lived token eliminates complexity

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="email" type="string" required>
      User's email address
    </ParamField>

    <ParamField path="password" type="string" required>
      User's password
    </ParamField>
  </Expandable>
</ParamField>

### Get Current User

<RequestExample>
  ```http theme={null}
  GET /auth/me
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "user": {
      "id": "usr_abc123",
      "email": "john.doe@example.com",
      "authProvider": "LOCAL",
      "firstName": "John",
      "lastName": "Doe",
      "avatar": "https://api.dicebear.com/7.x/avataaars/svg?seed=john.doe",
      "createdAt": "2024-01-15T10:00:00Z",
      "organizations": [
        {
          "id": "org_xyz789",
          "name": "Acme Corp",
          "role": "ADMIN",
          "joinedAt": "2024-01-15T10:00:00Z"
        },
        {
          "id": "org_def456",
          "name": "Beta Inc",
          "role": "MEMBER",
          "joinedAt": "2024-02-01T14:30:00Z"
        }
      ],
      "currentOrganization": {
        "id": "org_xyz789",
        "name": "Acme Corp",
        "role": "ADMIN"
      }
    },
    "message": "User retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves the currently authenticated user's profile along with their organization memberships.

**Response includes**:

* User profile information
* All organization memberships with roles
* Current active organization context
* Platform permissions and settings

### Update User Profile

<RequestExample>
  ```http theme={null}
  PATCH /auth/me
  Authorization: Bearer <token>
  Content-Type: application/json

  {
    "firstName": "Jane",
    "lastName": "Smith",
    "nickname": "JSmith"
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "user": {
      "id": "usr_abc123",
      "email": "jane.smith@example.com",
      "firstName": "Jane",
      "lastName": "Smith",
      "nickname": "JSmith",
      "updatedAt": "2024-01-20T15:30:00Z"
    },
    "message": "Profile updated successfully"
  }
  ```
</ResponseExample>

**Description**: Updates the current user's profile information including first name, last name, nickname, and email.

<Note>
  **Important**: Email updates will require re-verification (not implemented in this endpoint). All fields are optional - only provided fields will be updated.
</Note>

<ParamField path="body" type="object">
  <Expandable title="Request Body">
    <ParamField path="firstName" type="string">
      User's first name
    </ParamField>

    <ParamField path="lastName" type="string">
      User's last name
    </ParamField>

    <ParamField path="nickname" type="string">
      User's nickname
    </ParamField>

    <ParamField path="email" type="string">
      User's email address
    </ParamField>
  </Expandable>
</ParamField>

### Logout

<RequestExample>
  ```http theme={null}
  POST /auth/logout
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "message": "Logout successful"
  }
  ```
</ResponseExample>

**Description**: Logs out the current user by clearing the authentication cookie and invalidating the session.

### Create Setup Intent

<RequestExample>
  ```http theme={null}
  POST /auth/setup-intent
  Authorization: Bearer <token>
  Content-Type: application/json

  {}
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "clientSecret": "seti_1234567890_secret_abcdef...",
    "message": "Setup intent created successfully"
  }
  ```
</ResponseExample>

**Description**: Creates a Stripe setup intent for adding or updating payment methods. This is used to securely collect payment method information without processing a charge.

### Get User Consents

<RequestExample>
  ```http theme={null}
  GET /auth/me/consents
  Authorization: Bearer <token>
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "success": true,
    "consents": [
      {
        "id": "consent_123",
        "type": "TERMS_OF_SERVICE",
        "version": "1.0",
        "acceptedAt": "2024-01-15T10:00:00Z",
        "ipAddress": "192.168.1.1",
        "userAgent": "Mozilla/5.0..."
      }
    ],
    "message": "Consents retrieved successfully"
  }
  ```
</ResponseExample>

**Description**: Retrieves all active consent records for the authenticated user.

### Iframe Debug

<RequestExample>
  ```http theme={null}
  GET /auth/iframe-debug
  ```
</RequestExample>

<ResponseExample>
  ```json theme={null}
  {
    "isIframe": true,
    "requestInfo": {
      "referer": "https://fcupwvbjh0do6t4stcdo.apps.whop.com/login",
      "userAgent": "Mozilla/5.0...",
      "origin": "https://fcupwvbjh0do6t4stcdo.apps.whop.com",
      "frameContext": null,
      "host": "api.vchata.com",
      "allHeaders": ["authorization", "content-type", "user-agent", ...]
    },
    "cookieConfig": {
      "httpOnly": true,
      "secure": true,
      "sameSite": "none",
      "domain": undefined,
      "path": "/",
      "maxAge": 604800000
    },
    "recommendations": [
      "✅ Cookie will work in iframe context",
      "✅ SameSite=None allows cross-origin usage",
      "✅ Secure flag is properly set"
    ],
    "timestamp": "2024-01-15T10:00:00Z",
    "environment": "production"
  }
  ```
</ResponseExample>

**Description**: Debug endpoint to test iframe authentication behavior and cookie settings. Returns information about the request context and cookie configuration.

**Use this endpoint to**:

* Test iframe detection logic
* Verify cookie settings for different contexts
* Debug authentication issues in iframe environments
* Check CORS and header handling

## Error Responses

### Common Errors

<ResponseExample status="400">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 400,
    "message": [
      "password must be at least 8 characters",
      "email must be an email",
      "paymentMethodId must be a string"
    ],
    "error": "Bad Request"
  }
  ```
</ResponseExample>

<ResponseExample status="401">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 401,
    "message": "Invalid email or password",
    "error": "Unauthorized"
  }
  ```
</ResponseExample>

<ResponseExample status="409">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 409,
    "message": "User with this email already exists",
    "error": "Conflict"
  }
  ```
</ResponseExample>

<ResponseExample status="502">
  ```json theme={null}
  {
    "success": false,
    "statusCode": 502,
    "message": "Payment service temporarily unavailable",
    "error": "Bad Gateway"
  }
  ```
</ResponseExample>

## Security Features

* **Secure Cookies**: Authentication tokens are stored in httpOnly, secure cookies
* **CSRF Protection**: Cookie-based authentication provides built-in CSRF protection
* **Password Encryption**: All passwords are hashed using bcrypt
* **Rate Limiting**: Login attempts are rate limited to prevent brute force attacks
* **JWT Tokens**: Secure JWT tokens with 7-day expiration
* **Iframe Support**: Special handling for iframe contexts with fallback mechanisms

## Authentication Flow

<Steps>
  <Step title="User Registration">
    User provides email, password, and payment method
  </Step>

  <Step title="Account Creation">
    System creates user account, organization, and Stripe customer
  </Step>

  <Step title="Token Generation">
    JWT token is generated and set as secure cookie
  </Step>

  <Step title="Login">
    User can login with email/password to receive auth token
  </Step>

  <Step title="API Access">
    All subsequent requests use the auth token for authentication
  </Step>
</Steps>
