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

# Authentication API

> User authentication, registration, and session management

## Overview

The Authentication API handles user registration, login, session management, email verification, and password reset flows. All authentication uses secure HTTP-only cookies for session management with JWT tokens.

## Authentication Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Client
    participant API
    participant Email

    User->>Client: Enter credentials
    Client->>API: POST /auth/register
    API->>Email: Send verification email
    API-->>Client: Success (unverified account)
    User->>Email: Click verification link
    Email->>API: POST /auth/verify-email
    API-->>Client: Email verified
    User->>Client: Login
    Client->>API: POST /auth/login
    API-->>Client: Set HTTP-only cookie
    Client->>API: Authenticated requests
```

## Endpoints

### Register New User

<ParamField path="POST" type="endpoint">
  /auth/register
</ParamField>

Create a new user account. An email verification link will be sent to the provided email address.

**Request Body:**

```json theme={null}
{
  "email": "user@example.com",
  "name": "John Doe",
  "password": "SecurePassword123!"
}
```

<ParamField body="email" type="string" required>
  Valid email address
</ParamField>

<ParamField body="name" type="string" required>
  Full name (minimum 2 characters)
</ParamField>

<ParamField body="password" type="string" required>
  Strong password (minimum 8 characters)
</ParamField>

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Registration successful. Please check your email to verify your account.",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "name": "John Doe",
    "emailVerified": false,
    "createdAt": "2024-01-17T10:30:00Z"
  }
}
```

<Warning>
  Users must verify their email before they can fully access the platform.
</Warning>

***

### Login

<ParamField path="POST" type="endpoint">
  /auth/login
</ParamField>

Authenticate a user and establish a session.

**Request Body:**

```json theme={null}
{
  "email": "user@example.com",
  "password": "SecurePassword123!"
}
```

<ParamField body="email" type="string" required>
  User's email address
</ParamField>

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

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Login successful",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "name": "John Doe",
    "role": "USER",
    "emailVerified": true
  }
}
```

**Cookies Set:**

* `accessToken` - HTTP-only, Secure, SameSite=Strict (15 minutes)
* `refreshToken` - HTTP-only, Secure, SameSite=Strict (7 days)

***

### Get Current User

<ParamField path="GET" type="endpoint">
  /auth/me
</ParamField>

Retrieve the currently authenticated user's information.

**Headers:**

```
Cookie: accessToken=...
```

**Response:**

```json theme={null}
{
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "name": "John Doe",
    "role": "USER",
    "emailVerified": true,
    "createdAt": "2024-01-17T10:30:00Z"
  }
}
```

***

### Refresh Access Token

<ParamField path="POST" type="endpoint">
  /auth/refresh
</ParamField>

Obtain a new access token using the refresh token.

**Headers:**

```
Cookie: refreshToken=...
```

**Response:**

```json theme={null}
{
  "ok": true,
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "user@example.com",
    "name": "John Doe",
    "role": "USER"
  }
}
```

**Cookies Updated:**

* New `accessToken` issued
* `refreshToken` rotated for security

***

### Logout

<ParamField path="POST" type="endpoint">
  /auth/logout
</ParamField>

Terminate the user's session and invalidate tokens.

**Headers:**

```
Cookie: accessToken=...
```

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Logged out successfully"
}
```

**Cookies Cleared:**

* `accessToken` removed
* `refreshToken` removed

***

### Verify Email

<ParamField path="POST" type="endpoint">
  /auth/verify-email
</ParamField>

Verify a user's email address using the verification token sent via email.

**Request Body:**

```json theme={null}
{
  "token": "verification_token_from_email"
}
```

<ParamField body="token" type="string" required>
  Email verification token
</ParamField>

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Email verified successfully. You can now log in."
}
```

***

### Resend Verification Email

<ParamField path="POST" type="endpoint">
  /auth/send-email-verification
</ParamField>

Request a new verification email if the previous one expired or was lost.

**Request Body:**

```json theme={null}
{
  "email": "user@example.com"
}
```

<ParamField body="email" type="string" required>
  User's email address
</ParamField>

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Verification email sent. Please check your inbox."
}
```

**Rate Limit:**

This endpoint is rate-limited to prevent abuse:

* **5 requests per hour** per email address

***

### Forgot Password

<ParamField path="POST" type="endpoint">
  /auth/forgot-password
</ParamField>

Request a password reset link via email.

**Request Body:**

```json theme={null}
{
  "email": "user@example.com"
}
```

<ParamField body="email" type="string" required>
  User's email address
</ParamField>

**Response:**

```json theme={null}
{
  "success": true,
  "message": "If an account exists with this email, a password reset link has been sent."
}
```

<Info>
  For security, the API always returns a success message regardless of whether the email exists.
</Info>

***

### Reset Password

<ParamField path="POST" type="endpoint">
  /auth/reset-password
</ParamField>

Reset password using the token received via email.

**Request Body:**

```json theme={null}
{
  "token": "reset_token_from_email",
  "password": "NewSecurePassword123!"
}
```

<ParamField body="token" type="string" required>
  Password reset token from email
</ParamField>

<ParamField body="password" type="string" required>
  New password (minimum 8 characters)
</ParamField>

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Password reset successful. You can now log in with your new password."
}
```

***

## Security Features

### HTTP-Only Cookies

All session tokens are stored in HTTP-only cookies to prevent XSS attacks. JavaScript cannot access these cookies.

### Secure Flag

Cookies are marked as `Secure`, ensuring they're only transmitted over HTTPS in production.

### SameSite Policy

Cookies use `SameSite=Strict` to prevent CSRF attacks.

### Token Rotation

Refresh tokens are rotated on each use to minimize security risks if a token is compromised.

### Password Requirements

* Minimum 8 characters
* Recommended: Mix of uppercase, lowercase, numbers, and special characters

### Token Expiration

* **Access Token:** 15 minutes
* **Refresh Token:** 7 days
* **Verification Token:** 24 hours
* **Reset Token:** 1 hour

## Error Codes

| Code                   | Status | Description                        |
| ---------------------- | ------ | ---------------------------------- |
| `INVALID_CREDENTIALS`  | 401    | Incorrect email or password        |
| `EMAIL_ALREADY_EXISTS` | 409    | Email is already registered        |
| `EMAIL_NOT_VERIFIED`   | 403    | Email verification required        |
| `INVALID_TOKEN`        | 400    | Token is invalid or expired        |
| `TOKEN_EXPIRED`        | 401    | Token has expired                  |
| `WEAK_PASSWORD`        | 400    | Password doesn't meet requirements |
| `RATE_LIMIT_EXCEEDED`  | 429    | Too many requests                  |

## Use Cases

### Example 1: Complete Registration Flow

```bash theme={null}
# Step 1: Register
curl -X POST "https://api.steerai.autos/v1/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "dealer@example.com",
    "name": "Auto Dealer",
    "password": "SecurePass123!"
  }'

# Step 2: User receives email and verifies
curl -X POST "https://api.steerai.autos/v1/auth/verify-email" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "verification_token_from_email"
  }'

# Step 3: Login
curl -X POST "https://api.steerai.autos/v1/auth/login" \
  -H "Content-Type: application/json" \
  -c cookies.txt \
  -d '{
    "email": "dealer@example.com",
    "password": "SecurePass123!"
  }'
```

### Example 2: Password Reset Flow

```bash theme={null}
# Step 1: Request reset
curl -X POST "https://api.steerai.autos/v1/auth/forgot-password" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "dealer@example.com"
  }'

# Step 2: Reset with token from email
curl -X POST "https://api.steerai.autos/v1/auth/reset-password" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "reset_token_from_email",
    "password": "NewSecurePass123!"
  }'
```

### Example 3: Token Refresh

```bash theme={null}
# Refresh access token before it expires
curl -X POST "https://api.steerai.autos/v1/auth/refresh" \
  -b cookies.txt \
  -c cookies.txt
```

## Client Implementation

### JavaScript/Node.js

```javascript theme={null}
class AuthClient {
  constructor(baseURL) {
    this.baseURL = baseURL;
  }

  async register(email, name, password) {
    const response = await fetch(`${this.baseURL}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, name, password })
    });
    return response.json();
  }

  async login(email, password) {
    const response = await fetch(`${this.baseURL}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include', // Important for cookies
      body: JSON.stringify({ email, password })
    });
    return response.json();
  }

  async getCurrentUser() {
    const response = await fetch(`${this.baseURL}/auth/me`, {
      credentials: 'include'
    });
    return response.json();
  }

  async logout() {
    const response = await fetch(`${this.baseURL}/auth/logout`, {
      method: 'POST',
      credentials: 'include'
    });
    return response.json();
  }
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Always use HTTPS in production">
    Never transmit credentials over unsecured HTTP connections.
  </Accordion>

  <Accordion title="Implement client-side token refresh">
    Automatically refresh tokens before they expire to maintain session continuity.
  </Accordion>

  <Accordion title="Store refresh tokens securely">
    Use HTTP-only cookies (handled automatically by our API) rather than localStorage.
  </Accordion>

  <Accordion title="Enforce strong password policies">
    Require passwords with adequate complexity and length.
  </Accordion>

  <Accordion title="Implement rate limiting">
    Protect authentication endpoints from brute-force attacks.
  </Accordion>

  <Accordion title="Log authentication events">
    Track login attempts, password resets, and suspicious activity.
  </Accordion>
</AccordionGroup>

## Related Resources

<CardGroup cols={2}>
  <Card title="Getting Started" icon="rocket" href="/getting-started/authentication">
    Quick start guide for authentication
  </Card>

  <Card title="Security Guide" icon="shield" href="/guides/security">
    Comprehensive security best practices
  </Card>

  <Card title="Users API" icon="user" href="/api-reference/users/management">
    User management and profile endpoints
  </Card>

  <Card title="Teams API" icon="users" href="/api-reference/teams/overview">
    Team collaboration and permissions
  </Card>
</CardGroup>
