> ## 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 guide to user authentication and management with Cocobase

# Authentication

Cocobase provides a complete authentication system with user registration, login, session management, and profile handling. No complex setup required - just use the built-in auth methods.

## Quick Start

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    import { Cocobase } from "cocobase";

    const db = new Cocobase({ 
      apiKey: "YOUR_API_KEY",
      projectId: "YOUR_PROJECT_ID" // Optional
       });

    // Register a new user
    const user = await db.auth.register({
    email: "user@example.com",
    password: "securePassword123",
    data: { full_name: "Alice Johnson" }
    });

    // Login
    const result = await db.auth.login({
    email: "alice@example.com",
    password: "SecurePass123!"
    });
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    final db = Cocobase(CocobaseConfig(apiKey: "YOUR_API_KEY"));

    // Register a new user
    final user = await db.register(
      email: 'user@example.com',
      password: 'securePassword123',
      data: {
        'full_name': 'Alice Johnson',
        'role': 'developer',
      },
    );

    // Login
    final session = await db.login(
      email: 'user@example.com',
      password: 'securePassword123',
    );
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    client := cocobase.NewClient(cocobase.Config{
        APIKey: "YOUR_API_KEY",
    })

    // Register a new user
    user, err := client.Register(ctx, "user@example.com", "securePassword123", map[string]any{
        "full_name": "Alice Johnson",
        "role":      "developer",
    })

    // Login
    err = client.Login(ctx, "user@example.com", "securePassword123")
    if err != nil {
        log.Fatal(err)
    }
    // Get user separately
    user, err = client.GetCurrentUser(ctx)
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from cocobase_client.client import CocoBaseClient
    db = CocoBaseClient(api_key="YOUR_API_KEY")

    # Register a new user
    user = db.auth.register(
        "user@example.com",
        "securePassword123",
        {
            "full_name": "Alice Johnson",
            "role": "developer"
        }
    )

    # Login
    session = db.auth.login("user@example.com", "securePassword123")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    # Register
    curl -X POST https://api.cocobase.cc/auth-collections/signup \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "user@example.com",
        "password": "securePassword123",
        "data": {
          "full_name": "Alice Johnson",
          "role": "developer"
        }
      }'

    # Login
    curl -X POST https://api.cocobase.cc/auth-collections/login \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "user@example.com",
        "password": "securePassword123"
      }'
    ```
  </Tab>
</Tabs>

## User Registration

Create new user accounts with email and password:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}

    // Basic registration
    const result = await db.auth.register({
    email: "alice@example.com",
    password: "SecurePass123!"
    });

    if (!result.requires_2fa) {
    console.log("Registered user:", result.user);
    }

    // With additional user data
    const userWithData = await db.auth.register({
    email: "bob@example.com",
    password: "SecurePass123!",
    data: {
    full_name: "Bob Smith",
    age: 25,
    role: "admin",
    preferences: {
      theme: "dark",
      notifications: true
    }
    }
    });
    ```

    **Response:**

    ```json theme={null}
    {
      "id": "user_123abc",
      "email": "alice@example.com",
      "data": {
        "full_name": "Bob Smith",
        "age": 25,
        "role": "admin",
        "preferences": {
          "theme": "dark",
          "notifications": true
        }
      },
      "createdAt": "2024-01-15T10:30:00Z",
      "token": "eyJhbGc..."
    }
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Basic registration
    final user = await db.register(
      email: 'alice@example.com',
      password: 'SecurePass123!',
    );

    // With additional user data
    final userWithData = await db.register(
      email: 'bob@example.com',
      password: 'SecurePass123!',
      data: {
        'full_name': 'Bob Smith',
        'age': 25,
        'role': 'admin',
        'preferences': {
          'theme': 'dark',
          'notifications': true,
        },
      },
    );
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // Basic registration
    user, err := client.Register(ctx, "alice@example.com", "SecurePass123!", nil)
    if err != nil {
        log.Fatal(err)
    }

    // With additional user data
    userWithData, err := client.Register(ctx, "bob@example.com", "SecurePass123!", map[string]any{
        "full_name": "Bob Smith",
        "age":       25,
        "role":      "admin",
        "preferences": map[string]any{
            "theme":         "dark",
            "notifications": true,
        },
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Basic registration
    user = db.auth.register("alice@example.com", "SecurePass123!")

    # With additional user data
    user_with_data = db.auth.register(
        "bob@example.com",
        "SecurePass123!",
        {
            "full_name": "Bob Smith",
            "age": 25,
            "role": "admin",
            "preferences": {
                "theme": "dark",
                "notifications": True
            }
        }
    )
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}

    curl -X POST https://api.cocobase.cc/auth-collections/signup \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "email": "bob@example.com",
    "password": "SecurePass123!",
    "data": {
      "full_name": "Bob Smith",
      "age": 25,
      "role": "admin",
      "preferences": {
        "theme": "dark",
        "notifications": true
      }
    }
    }'
    ```
  </Tab>
</Tabs>

<Note>
  Password requirements: - Minimum 8 characters - At least one uppercase letter

  * At least one lowercase letter - At least one number
</Note>

## User Login

Authenticate users and get access tokens:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}

    const result = await db.auth.login({
    email: "alice@example.com",
    password: "SecurePass123!"
    });

    if (result.requires_2fa) {
    console.log("2FA required:", result.message);
    } else {
    console.log("Logged in user:", result.user);
    }

    // Token is automatically stored internally
    ```

    **With automatic token persistence:**

    ```typescript theme={null}
    // Token is automatically saved to localStorage

    await db.auth.initAuth();

    if (db.auth.isAuthenticated()) {
    const currentUser = await db.auth.getCurrentUser();
    console.log("User is logged in:", currentUser);
    }
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Login
    final session = await db.login(
      email: 'alice@example.com',
      password: 'SecurePass123!',
    );

    print('Token: ${session.token}');
    print('User: ${session.user}');

    // Check current user
    final currentUser = await db.getCurrentUser();
    if (currentUser != null) {
      print('User is logged in: $currentUser');
    }
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // Login
    err = client.Login(ctx, "alice@example.com", "SecurePass123!")
    if err != nil {
        log.Fatal(err)
    }
    user, err := client.GetCurrentUser(ctx)
    fmt.Printf("Email: %s\n", user.Email)

    // Token is automatically stored and used for future requests
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Login
    session = db.auth.login("alice@example.com", "SecurePass123!")

    print(f"Token: {session['token']}")
    print(f"User: {session['user']}")

    # Check current user
    current_user = db.auth.get_current_user()
    if current_user:
        print(f"User is logged in: {current_user}")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}

    curl -X POST https://api.cocobase.cc/auth-collections/login \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "email": "alice@example.com",
    "password": "SecurePass123!"
    }'
    ```

    ````

     **Use the token in subsequent requests:**
     ```bash
     curl -X GET https://api.cocobase.cc/collections/posts \
       -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
    ````
  </Tab>
</Tabs>

## Get Current User

Retrieve the currently authenticated user:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}

    await db.auth.initAuth();

    if (db.auth.isAuthenticated()) {
    const user = await db.auth.getCurrentUser();
    console.log("Logged in as:", user.email);
    console.log("User data:", user.data);
    } else {
    console.log("No user logged in");
    }
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Get current user
    final user = await db.getCurrentUser();

    if (user != null) {
      print('Logged in as: ${user.email}');
      print('User data: ${user.data}');
    } else {
      print('No user logged in');
    }
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // Get current user
    user, err := client.GetCurrentUser(ctx)
    if err != nil {
        log.Printf("No user logged in: %v", err)
        return
    }

    fmt.Printf("Logged in as: %s\n", user.Email)
    fmt.Printf("User data: %+v\n", user.Data)
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Get current user
    user = db.auth.get_current_user()

    if user:
        print(f"Logged in as: {user['email']}")
        print(f"User data: {user['data']}")
    else:
        print("No user logged in")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    curl -X GET https://api.cocobase.cc/auth-collections/me \
      -H "Authorization: Bearer YOUR_USER_TOKEN"
    ```
  </Tab>
</Tabs>

## Update User Profile

Update user data after authentication:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}

    const updatedUser = await db.auth.updateUser({
    data: {
    full_name: "Alice Johnson Smith",
    bio: "Full-stack developer",
    avatar: "https://example.com/avatar.jpg",
    preferences: {
      theme: "dark",
      language: "en"
    }
    }
    });

    console.log("Updated user:", updatedUser);
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Update user profile
    final updatedUser = await db.updateUser(data: {
      'full_name': 'Alice Johnson Smith',
      'bio': 'Full-stack developer',
      'avatar': 'https://example.com/avatar.jpg',
      'preferences': {
        'theme': 'dark',
        'language': 'en',
      },
    });

    print('Updated user: $updatedUser');
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // Update user profile
    updatedUser, err := client.UpdateUser(ctx, map[string]interface{}{
        "full_name": "Alice Johnson Smith",
        "bio": "Full-stack developer",
    }, nil, nil)
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Update user profile
    updated_user = db.auth.update_profile({
        "full_name": "Alice Johnson Smith",
        "bio": "Full-stack developer",
        "avatar": "https://example.com/avatar.jpg",
        "preferences": {
            "theme": "dark",
            "language": "en"
        }
    })
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}

    curl -X PATCH https://api.cocobase.cc/auth-collections/user \
    -H "Authorization: Bearer YOUR_USER_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
    "data": {
      "full_name": "Alice Johnson Smith",
      "bio": "Full-stack developer",
      "avatar": "https://example.com/avatar.jpg"
    }
    }'
    ```
  </Tab>
</Tabs>

## Logout

End the user session:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Logout current user
    await db.auth.logout();

    console.log("User logged out");

    // Verify logout
    const user = db.auth.getCurrentUser(); // Returns null
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Logout current user
    await db.logout();

    print('User logged out');

    // Verify logout
    final user = await db.getCurrentUser(); // Returns null
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // Logout current user
    err := client.Logout(ctx)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("User logged out")
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Logout current user
    db.auth.logout()

    print("User logged out")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}

    curl -X POST https://api.cocobase.cc/auth-collections/logout \
    -H "Authorization: Bearer YOUR_USER_TOKEN"
    ```
  </Tab>
</Tabs>

## Password Management

### Change Password

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Change password (user must be logged in)
    await db.auth.changePassword("oldPassword123", "newPassword456");
    ```
  </Tab>

  <Tab title="Go">
    <Note>This feature is not yet available in the Go SDK.</Note>
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    db.auth.change_password("oldPassword123", "newPassword456")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    curl -X POST https://api.cocobase.cc/auth/change-password \
      -H "Authorization: Bearer YOUR_USER_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "oldPassword": "oldPassword123",
        "newPassword": "newPassword456"
      }'
    ```
  </Tab>
</Tabs>

### Request Password Reset

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Send password reset email
    await db.auth.requestPasswordReset("user@example.com");
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    await db.requestPasswordReset(email: 'user@example.com');
    ```
  </Tab>

  <Tab title="Go">
    <Note>This feature is not yet available in the Go SDK.</Note>
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    db.auth.request_password_reset("user@example.com")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    curl -X POST https://api.cocobase.cc/auth/request-password-reset \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "user@example.com"
      }'
    ```
  </Tab>
</Tabs>

### Reset Password with Token

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Reset password using token from email
    await db.auth.resetPassword("reset_token_from_email", "newPassword123");
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    await db.resetPassword(
      token: 'reset_token_from_email',
      newPassword: 'newPassword123',
    );
    ```
  </Tab>

  <Tab title="Go">
    <Note>This feature is not yet available in the Go SDK.</Note>
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    db.auth.reset_password("reset_token_from_email", "newPassword123")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    curl -X POST https://api.cocobase.cc/auth/reset-password \
      -H "Content-Type: application/json" \
      -d '{
        "token": "reset_token_from_email",
        "newPassword": "newPassword123"
      }'
    ```
  </Tab>
</Tabs>

## OAuth Authentication

Authenticate users with Google, GitHub, and other OAuth providers:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Cocobase does NOT handle the Google popup.
    // You handle OAuth yourself, then send the token to Cocobase.

    // Option 1: Using Google Identity Services
    google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: async (response) => {
        // Send the ID token to Cocobase
        const user = await db.auth.loginWithGoogle({
          idToken: response.credential,
          platform: "web"
        });
        console.log("Logged in:", user.email);
      }
    });

    google.accounts.id.renderButton(
      document.getElementById("google-btn"),
      { theme: "outline", size: "large" }
    );

    // Option 2: Using react-google-login
    // import { useGoogleLogin } from '@react-oauth/google';
    // const login = useGoogleLogin({
    //   onSuccess: async (tokenResponse) => {
    //     const user = await db.auth.loginWithGoogle({
    //       idToken: tokenResponse.credential,
    //       platform: "web"
    //     });
    //   }
    // });

    // For mobile (iOS/Android)
    // const user = await db.auth.loginWithGoogle({
    //   idToken: "token-from-native-google-sdk",
    //   platform: "ios" // or "android"
    // });
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Initiate Google OAuth flow
    final authUrl = await db.getOAuthUrl(
      provider: 'google',
      redirectUrl: 'yourapp://auth/callback',
      scopes: ['email', 'profile'],
    );

    // Open authUrl in browser/webview

    // Handle callback
    final session = await db.handleOAuthCallback(
      provider: 'google',
      code: authorizationCode,
    );
    ```
  </Tab>

  <Tab title="Go">
    <Note>This feature is not yet available in the Go SDK.</Note>
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Initiate Google OAuth flow
    auth_url = db.auth.get_oauth_url(
        "google",
        redirect_url="https://yourapp.com/auth/callback",
        scopes=["email", "profile"]
    )

    # Handle callback
    session = db.auth.handle_oauth_callback("google", authorization_code)
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    # Get OAuth URL
    curl -X POST https://api.cocobase.cc/auth/oauth/google/url \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "redirectUrl": "https://yourapp.com/auth/callback",
        "scopes": ["email", "profile"]
      }'

    # Handle callback
    curl -X POST https://api.cocobase.cc/auth/oauth/google/callback \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "code": "AUTHORIZATION_CODE_FROM_GOOGLE"
      }'
    ```
  </Tab>
</Tabs>

**Supported OAuth Providers:**

* Google
* GitHub
* Facebook
* Twitter
* Microsoft
* Apple

## Two-Factor Authentication (2FA)

### Enable 2FA

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Enable 2FA for current user
    await db.auth.enable2FA();
    console.log("2FA enabled successfully");

    // Verify 2FA setup with code from authenticator app
    await db.auth.verify2FA("123456");

    // Disable 2FA
    await db.auth.disable2FA();
    console.log("2FA disabled");
    ```
  </Tab>

  <Tab title="Go">
    <Note>This feature is not yet available in the Go SDK.</Note>
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Enable 2FA
    db.auth.enable_2fa()
    print("2FA enabled")

    # Verify 2FA
    db.auth.verify_2fa("123456")

    # Disable 2FA
    db.auth.disable_2fa()
    print("2FA disabled")
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    # Enable 2FA
    curl -X POST https://api.cocobase.cc/auth/2fa/enable \
      -H "Authorization: Bearer YOUR_USER_TOKEN"

    # Verify 2FA
    curl -X POST https://api.cocobase.cc/auth/2fa/verify \
      -H "Authorization: Bearer YOUR_USER_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{
        "code": "123456"
      }'
    ```
  </Tab>
</Tabs>

### Login with 2FA

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}

    // First attempt login
    const result = await db.auth.login({
    email: "user@example.com",
    password: "password123"
    });

    if (result.requires_2fa) {
    const code = prompt("Enter 2FA code:");

    await db.auth.verify2FALogin({
    email: "user@example.com",
    code
    });

    console.log("2FA login successful");
    }
    ```
  </Tab>

  <Tab title="Go">
    <Note>This feature is not yet available in the Go SDK.</Note>
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    try:
        db.auth.login("user@example.com", "password123")
    except TwoFactorRequiredError:
        # Prompt user for 2FA code
        code = input("Enter 2FA code: ")

        # Complete login with 2FA
        db.auth.verify_2fa_login(code)
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}

    # Login
    curl -X POST https://api.cocobase.cc/auth-collections/login \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "email": "user@example.com",
    "password": "password123"
    }'

    # Complete 2FA login
    curl -X POST https://api.cocobase.cc/auth-collections/verify-2fa-login \
    -H "x-api-key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "email": "user@example.com",
    "code": "123456"
    }'
    ```
  </Tab>
</Tabs>

## Email Verification

Verify user email addresses to ensure account authenticity and improve security.

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    // Request verification email for current user
    await db.auth.requestEmailVerification();

    // Verify email with token from link
    const token = new URLSearchParams(window.location.search).get('token');
    if (token) {
      await db.auth.verifyEmail(token);
      console.log("Email verified successfully");
    }

    // Resend if needed
    await db.auth.resendVerificationEmail();
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Request verification
    db.auth.request_email_verification()

    # Verify email
    db.auth.verify_email("verification_token_from_email")

    # Resend
    db.auth.resend_verification_email()
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    # Request verification
    curl -X POST https://api.cocobase.cc/auth/request-verification \
      -H "Authorization: Bearer YOUR_USER_TOKEN"

    # Verify email
    curl -X POST https://api.cocobase.cc/auth/verify-email \
      -H "Content-Type: application/json" \
      -d '{
        "token": "verification_token_from_email"
      }'
    ```
  </Tab>
</Tabs>

<Note>
  Email verification can be enforced globally in your project settings. When enabled, users will have limited access until their email is verified.
</Note>

## Role-Based Access Control

Manage user roles and permissions:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}

    const admin = await db.auth.register({
    email: "admin@example.com",
    password: "password123",
    data: {
    full_name: "Admin User",
    role: "admin"
    }
    });

    await db.auth.initAuth();

    if (db.auth.isAuthenticated()) {
    const currentUser = await db.auth.getCurrentUser();
    if (db.auth.hasRole("admin")) {
    // Show admin features
    }
    }
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    // Register user with role
    final admin = await db.register(
      email: 'admin@example.com',
      password: 'password123',
      data: {
        'full_name': 'Admin User',
        'role': 'admin',
      },
    );

    // Check user role
    final currentUser = await db.getCurrentUser();
    if (currentUser?.data['role'] == 'admin') {
      // Show admin features
    }
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // Register user with role
    admin, err := client.Register(ctx, "admin@example.com", "password123", map[string]any{
        "full_name": "Admin User",
        "role":      "admin",
    })

    // Check user role
    currentUser, _ := client.GetCurrentUser(ctx)
    if currentUser.Data["role"] == "admin" {
        // Show admin features
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Register user with role
    admin = db.auth.register(
        "admin@example.com",
        "password123",
        {
            "full_name": "Admin User",
            "role": "admin"
        }
    )

    # Check user role
    current_user = db.auth.get_current_user()
    if current_user['data']['role'] == 'admin':
        # Show admin features
        pass
    ```
  </Tab>

  <Tab title="HTTP">
    ```bash theme={null}
    # Register with role
    curl -X POST https://api.cocobase.cc/auth/register \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "admin@example.com",
        "password": "password123",
        "data": {
          "role": "admin"
        }
      }'
    ```
  </Tab>
</Tabs>

## Authentication with React

Complete example for React applications:

```typescript theme={null}
// hooks/useAuth.ts
import { useState, useEffect } from "react";
import { db } from "@/lib/cocobase";

export function useAuth() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const currentUser = db.auth.getCurrentUser();
    setUser(currentUser);
    setLoading(false);
  }, []);


const login = async (email: string, password: string) => {
  const result = await db.auth.login({ email, password });

  if (!result.requires_2fa) {
    const user = await db.auth.getCurrentUser();
    setUser(user);
  }

  return result;
};

const register = async (email: string, password: string, data?: any) => {
  const result = await db.auth.register({ email, password, data });

  if (!result.requires_2fa) {
    setUser(result.user);
  }

  return result;
};
  const logout = async () => {
    await db.auth.logout();
    setUser(null);
  };

  return { user, loading, login, register, logout };
}

// components/LoginForm.tsx
function LoginForm() {
  const { login } = useAuth();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await login(email, password);
      // Redirect to dashboard
    } catch (error) {
      console.error("Login failed:", error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <button type="submit">Login</button>
    </form>
  );
}
```

## Authentication with Flutter

Complete example for Flutter applications:

```dart theme={null}
// providers/auth_provider.dart
import 'package:flutter/foundation.dart';
import 'package:coco_base_flutter/coco_base_flutter.dart';

class AuthProvider with ChangeNotifier {
  final Cocobase _db;
  Map<String, dynamic>? _user;

  AuthProvider(this._db) {
    _loadUser();
  }

  Map<String, dynamic>? get user => _user;
  bool get isAuthenticated => _user != null;

  Future<void> _loadUser() async {
    _user = await _db.getCurrentUser();
    notifyListeners();
  }

  Future<void> login(String email, String password) async {
    await _db.login(email, password);
    _user = await _db.getCurrentUser();
    notifyListeners();
  }

  Future<void> register(String email, String password, Map<String, dynamic>? data) async {
    await _db.register(email, password, data: data);
    _user = await _db.getCurrentUser();
    notifyListeners();
  }

  Future<void> logout() async {
    _db.logout();
    _user = null;
    notifyListeners();
  }
}

// screens/login_screen.dart
class LoginScreen extends StatelessWidget {
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: _emailController,
              decoration: InputDecoration(labelText: 'Email'),
            ),
            TextField(
              controller: _passwordController,
              decoration: InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            ElevatedButton(
              onPressed: () async {
                await context.read<AuthProvider>().login(
                  _emailController.text,
                  _passwordController.text,
                );
              },
              child: Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}
```

## Error Handling

Common authentication errors and how to handle them:

<Tabs>
  <Tab title="JavaScript">
    ```typescript theme={null}
    try {
      await db.auth.login({ email, password });
    } catch (error) {
      switch (error.code) {
        case 'INVALID_CREDENTIALS':
          console.error('Invalid email or password');
          break;
        case '2FA_REQUIRED':
          console.log('2FA code required');
          break;
        case 'USER_NOT_FOUND':
          console.error('User not found');
          break;
        case 'EMAIL_ALREADY_EXISTS':
          console.error('Email already registered');
          break;
        default:
          console.error('Authentication error:', error.message);
      }
    }
    ```
  </Tab>

  <Tab title="Dart">
    ```dart theme={null}
    try {
      await db.login(email: email, password: password);
    } catch (e) {
      if (e is CocobaseException) {
        switch (e.code) {
          case 'INVALID_CREDENTIALS':
            print('Invalid email or password');
            break;
          case '2FA_REQUIRED':
            print('2FA code required');
            break;
          case 'USER_NOT_FOUND':
            print('User not found');
            break;
          default:
            print('Authentication error: ${e.message}');
        }
      }
    }
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    err := client.Login(ctx, email, password)
    if err != nil {
        var apiErr *cocobase.APIError
        if errors.As(err, &apiErr) {
            fmt.Println("Status:", apiErr.StatusCode)
            fmt.Println("Error:", apiErr.Body)
        } else {
            fmt.Println("Error:", err)
        }
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    try:
        db.auth.login(email, password)
    except InvalidCredentialsError:
        print("Invalid email or password")
    except TwoFactorRequiredError:
        print("2FA code required")
    except UserNotFoundError:
        print("User not found")
    except CocobaseError as e:
        print(f"Authentication error: {e}")
    ```
  </Tab>

  <Tab title="HTTP">
    HTTP status codes:

    * `400` - Invalid request
    * `401` - Invalid credentials
    * `403` - 2FA required
    * `404` - User not found
    * `409` - Email already exists
    * `500` - Server error
  </Tab>
</Tabs>

## Best Practices

<AccordionGroup>
  <Accordion title="Secure Password Storage">
    Never store passwords in plain text. Use environment variables and secure storage:

    ```typescript theme={null}
    // ✅ Good
    const password = process.env.USER_PASSWORD;

    // ❌ Bad
    const password = "hardcoded_password123";
    ```
  </Accordion>

  {" "}

  <Accordion title="Token Security">
    Tokens are automatically stored securely: - **Browser**: localStorage (with
    HttpOnly flag) - **Mobile**: Secure storage (Keychain/Keystore) - **Server**:
    Memory or secure storage backend
  </Accordion>

  <Accordion title="Session Management">
    Implement automatic token refresh and session validation:

    ```typescript theme={null}
    // Check session on app start
    const user = db.auth.getCurrentUser();
    if (user) {
      try {
        await db.auth.fetchCurrentUser(); // Validates token
      } catch (error) {
        // Token expired, redirect to login
        await db.auth.logout();
      }
    }
    ```
  </Accordion>

  <Accordion title="Password Requirements">
    Enforce strong password requirements:

    * Minimum 8 characters
    * Mix of uppercase, lowercase, numbers
    * Consider special characters
    * Implement password strength meter
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="CRUD Operations" icon="database" href="/features/crud-operations">
    Learn to create, read, update, and delete data
  </Card>

  <Card title="User Profiles" icon="user" href="/examples/user-profiles">
    Build complete user profile management
  </Card>

  <Card title="Protected Routes" icon="shield" href="/examples/protected-routes">
    Secure your application routes
  </Card>

  <Card title="Social Login" icon="users" href="/examples/social-login">
    Implement OAuth authentication
  </Card>
</CardGroup>
