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

# Authentication

# Authentication

The Revelation 14 API uses **JWT (JSON Web Tokens)** for authentication. All API requests must include a valid access token in the Authorization header.

## Authentication Flow

```mermaid theme={null}
sequenceDiagram
    participant App as Mobile App
    participant Edge as Edge Functions
    participant DB as Supabase Database

    App->>Edge: Login Request
    Edge->>DB: Validate User
    DB-->>Edge: User Data
    Edge->>Edge: Sign JWT Token
    Edge-->>App: Access Token
    
    Note over App: Store token securely
    
    App->>Edge: API Request + Token
    Edge->>Edge: Decode JWT
    Edge->>DB: Validated Query
```

## Getting an Access Token

### Login Endpoint

<Card title="POST /auth/login" icon="key">
  Authenticate a user and receive an access token
</Card>

**Endpoint**: `https://rzqklwfhwqmviintncqh.supabase.co/functions/v1/auth/login`

**Headers**:

* `Content-Type: application/json`
* `apikey: your_supabase_anon_key`

**Request Body**:

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

**Response**:

```json theme={null}
{
  "success": true,
  "statusCode": 200,
  "message": "Welcome back",
  "data": {
    "payload": {
      "id": "f9cc094c-ba9c-4a0a-82b9-e40d589e97db",
      "name": "John Doe",
      "email": "user@example.com",
      "role": "STANDARD_USER",
      "status": "ACTIVE",
      "isVerified": true,
      "createdAt": "2025-08-15T13:53:15.974Z"
    },
    "accessToken": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
```

## Using Access Tokens

Include the access token in the `Authorization` header for all authenticated requests:

```bash theme={null}
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

## JWT Token Structure

The JWT token contains the following payload:

```json theme={null}
{
  "id": "user_unique_id",
  "role": "STANDARD_USER",
  "iat": 1760426328,
  "exp": 1760433528
}
```

**Fields**:

* `id`: Unique user identifier
* `role`: User role (STANDARD\_USER, ADMIN, etc.)
* `iat`: Issued at timestamp
* `exp`: Expiration timestamp

## Token Expiration

* **Default Expiration**: 2 hours
* **Refresh**: Tokens must be refreshed by re-authenticating
* **Validation**: Tokens are validated on each request

<Warning>
  Tokens expire after 2 hours. Your application should handle token expiration gracefully and prompt users to re-authenticate when needed.
</Warning>

## User Roles

| Role            | Description   | Permissions                         |
| --------------- | ------------- | ----------------------------------- |
| `STANDARD_USER` | Regular user  | Create/read/update/delete own notes |
| `ADMIN`         | Administrator | Full access to all resources        |

## Security Best Practices

<CardGroup cols={2}>
  <Card title="Secure Storage" icon="lock">
    Store tokens securely on the client (encrypted storage, keychain)
  </Card>

  <Card title="HTTPS Only" icon="shield-check">
    Always use HTTPS for API communications
  </Card>

  <Card title="Token Validation" icon="check-circle">
    Validate token expiration before making requests
  </Card>

  <Card title="Logout Handling" icon="right-from-bracket">
    Clear tokens on logout or app uninstall
  </Card>
</CardGroup>

## Error Responses

### 401 Unauthorized

```json theme={null}
{
  "error": "Authorization header required",
  "success": false
}
```

### 401 Invalid Token

```json theme={null}
{
  "error": "Invalid token format",
  "success": false
}
```

### 400 Invalid Credentials

```json theme={null}
{
  "statusCode": 400,
  "message": "Invalid credentials"
}
```

## Code Examples

<CodeGroup>
  ```dart Flutter - Secure Storage theme={null}
  import 'package:flutter_secure_storage/flutter_secure_storage.dart';

  class AuthService {
    static const _storage = FlutterSecureStorage();
    static const _tokenKey = 'access_token';

    // Store token securely
    static Future<void> storeToken(String token) async {
      await _storage.write(key: _tokenKey, value: token);
    }

    // Retrieve token
    static Future<String?> getToken() async {
      return await _storage.read(key: _tokenKey);
    }

    // Clear token on logout
    static Future<void> clearToken() async {
      await _storage.delete(key: _tokenKey);
    }
  }
  ```

  ```javascript JavaScript - Token Management theme={null}
  class AuthManager {
    static setToken(token) {
      localStorage.setItem('access_token', token);
    }

    static getToken() {
      return localStorage.getItem('access_token');
    }

    static clearToken() {
      localStorage.removeItem('access_token');
    }

    static isTokenExpired(token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]));
        return Date.now() >= payload.exp * 1000;
      } catch {
        return true;
      }
    }
  }
  ```
</CodeGroup>
