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

# Authentication

> Complete reference for Cocobase authentication API endpoints and patterns

# Authentication

Cocobase provides a robust authentication system supporting both administrative API keys and per-user JWT tokens.

## Authentication Methods

### API Key Authentication

API keys are used for server-side operations and administrative tasks.

* **Header**: `X-API-Key: your_api_key` or `Authorization: Bearer your_api_key`
* **Use Case**: Cloud functions, backend integrations, administrative scripts.

### JWT Token Authentication

User tokens are obtained after login and are used for client-side user operations.

* **Header**: `Authorization: Bearer <jwt_token>`
* **Use Case**: Frontend applications, mobile apps, user-specific data access.

***

## Sign Up

Create a new user account.

### Endpoint

`POST /auth-collections/signup`

### Request Body

```json theme={null}
{
  "email": "user@example.com",
  "password": "securePassword123",
  "data": {
    "username": "johndoe",
    "name": "John Doe"
  }
}
```

### Response

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "user": {
    "id": "user_abc123",
    "email": "user@example.com",
    "data": { "username": "johndoe" }
  }
}
```

***

## Login

Authenticate an existing user.

### Endpoint

`POST /auth-collections/login`

### Request Body

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

### Response

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "user": {
    "id": "user_abc123",
    "email": "user@example.com"
  }
}
```

***

## Get Current User

Retrieve the profile of the currently authenticated user.

### Endpoint

`GET /auth-collections/user`

### Headers

`Authorization: Bearer <jwt_token>`

***

## Update User

Update the current user's data. Supports atomic array operations.

### Endpoint

`PATCH /auth-collections/user`

### Atomic Array Operations

Use `$append` and `$remove` to modify array fields (like followers/following) without fetching-and-saving.

#### Follow a User (\$append)

```json theme={null}
{
  "data": {
    "$append": { "following_ids": "user_target_456" }
  }
}
```

#### Unfollow a User (\$remove)

```json theme={null}
{
  "data": {
    "$remove": { "following_ids": "user_target_456" }
  }
}
```

### Update with File Upload

To update a user with files (e.g., avatar), use `multipart/form-data`.

```bash theme={null}
curl -X PATCH https://api.cocobase.cc/auth-collections/user \
  -H "Authorization: Bearer <token>" \
  -F "data={\"bio\": \"New bio\"}" \
  -F "avatar=@/path/to/image.jpg"
```

***

## Change Password

Update the user's password.

### Endpoint

`POST /auth-collections/change-password`

### Request Body

```json theme={null}
{
  "old_password": "currentPassword123",
  "new_password": "newSecurePassword456"
}
```

***

## List Users

List all users in the project. Requires API Key.

### Endpoint

`GET /auth-collections/users`

### Query Parameters

* `limit`: Number of users to return
* `offset`: Skip results for pagination
* `role`: Filter by role
* `email_contains`: Search by email content

***

## Get User by ID

Retrieve a specific user's public profile.

### Endpoint

`GET /auth-collections/users/{id}`

***

## OAuth Authentication

Cocobase supports Google and Apple OAuth.

### 1. Get OAuth Google URL

`GET /auth-collections/oauth/google?redirect_uri=https://yourapp.com/callback`

### 2. Verify Google Login

`POST /auth-collections/verify-google-login`

```json theme={null}
{
  "code": "auth_code_from_google",
  "redirect_uri": "https://yourapp.com/callback"
}
```

***

## User Relationships

Users can have relationships like `followers` and `following`. These are typically stored as arrays of IDs in the user `data` object.

| Relationship | ID Pattern      |
| ------------ | --------------- |
| Following    | `following_ids` |
| Followers    | `followers_ids` |
| Meta         | `referral_code` |

***

## Examples

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    // Register
    const signup = await fetch('https://api.cocobase.cc/auth-collections/signup', {
      method: 'POST',
      body: JSON.stringify({ email, password, data })
    });

    // Update (Follow)
    await fetch('https://api.cocobase.cc/auth-collections/user', {
      method: 'PATCH',
      headers: { 'Authorization': `Bearer ${token}` },
      body: JSON.stringify({
        data: { "$append": { "following_ids": targetId } }
      })
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    # Login
    res = requests.post('https://api.cocobase.cc/auth-collections/login', 
                       json={'email': email, 'password': password})
    token = res.json()['access_token']

    # Get User
    user = requests.get('https://api.cocobase.cc/auth-collections/user',
                       headers={'Authorization': f'Bearer {token}'}).json()
    ```
  </Tab>
</Tabs>

***

## Best Practices

1. **Security**: Never expose Live API keys (`sk_live_...`) in client-side code.
2. **Tokens**: Refresh JWT tokens before they expire to maintain session persistence.
3. **Atomic Operations**: Always use `$append` and `$remove` for array updates to avoid race conditions.
4. **Validation**: Validate email formats and password strength on the frontend before submitting to the API.

***

## Rate Limits

| Tier       | Limit                  |
| ---------- | ---------------------- |
| Free       | 60 requests / minute   |
| Pro        | 1000 requests / minute |
| Enterprise | Custom                 |
