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

# Authentication

> CometChat Calling SDK v5 - Authentication for iOS

Before users can make or receive calls, they must be authenticated with the CometChat Calls SDK. This guide covers the login and logout methods.

<Note>
  **Sample Users**

  CometChat provides 5 test users: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4`, and `cometchat-uid-5`.
</Note>

## Check Login Status

Before calling `login()`, check if a user is already logged in using `getLoggedInUser()`. The SDK maintains the session internally, so you only need to login once per user session.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    if let loggedInUser = CometChatCalls.getLoggedInUser() {
        // User is already logged in
        print("User already logged in: \(loggedInUser.uid ?? "")")
    } else {
        // No user logged in, proceed with login
    }
    ```
  </Tab>

  <Tab title="Objective-C">
    ```objectivec theme={null}
    CallsUser *loggedInUser = [CometChatCalls getLoggedInUser];

    if (loggedInUser != nil) {
        // User is already logged in
        NSLog(@"User already logged in: %@", loggedInUser.uid);
    } else {
        // No user logged in, proceed with login
    }
    ```
  </Tab>
</Tabs>

The `getLoggedInUser()` method returns a `CallsUser` object if a user is logged in, or `nil` if no session exists.

## Login with UID and API Key

This method is suitable for development and testing. For production apps, use [Auth Token login](#login-with-auth-token) instead.

<Warning>
  **Security Notice**

  Using the API Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security.
</Warning>

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let uid = "cometchat-uid-1" // Replace with your user's UID
    let apiKey = "API_KEY" // Replace with your API Key

    if CometChatCalls.getLoggedInUser() == nil {
        CometChatCalls.login(UID: uid, apiKey: apiKey, onSuccess: { user in
            print("Login successful: \(user.uid ?? "")")
        }, onError: { error in
            print("Login failed: \(error.errorDescription)")
        })
    } else {
        // User already logged in
    }
    ```
  </Tab>

  <Tab title="Objective-C">
    ```objectivec theme={null}
    NSString *uid = @"cometchat-uid-1"; // Replace with your user's UID
    NSString *apiKey = @"API_KEY"; // Replace with your API Key

    if ([CometChatCalls getLoggedInUser] == nil) {
        [CometChatCalls loginWithUID:uid 
                              apiKey:apiKey 
                           onSuccess:^(CallsUser * user) {
            NSLog(@"Login successful: %@", user.uid);
        } onError:^(CometChatCallException error) {
            NSLog(@"Login failed: %@", error.errorDescription);
        }];
    } else {
        // User already logged in
    }
    ```
  </Tab>
</Tabs>

| Parameter   | Type    | Description                                |
| ----------- | ------- | ------------------------------------------ |
| `UID`       | String  | The unique identifier of the user to login |
| `apiKey`    | String  | Your CometChat API Key                     |
| `onSuccess` | Closure | Closure called with `CallsUser` on success |
| `onError`   | Closure | Closure called with error on failure       |

## Login with Auth Token

This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your API Key secure.

### Auth Token Flow

1. User authenticates with your backend
2. Your backend calls the [CometChat Create Auth Token API](https://api-explorer.cometchat.com/reference/create-authtoken)
3. Your backend returns the Auth Token to the client
4. Client uses the Auth Token to login

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let authToken = "AUTH_TOKEN" // Token received from your backend

    CometChatCalls.login(authToken: authToken, onSuccess: { user in
        print("Login successful: \(user.uid ?? "")")
    }, onError: { error in
        print("Login failed: \(error.errorDescription)")
    })
    ```
  </Tab>

  <Tab title="Objective-C">
    ```objectivec theme={null}
    NSString *authToken = @"AUTH_TOKEN"; // Token received from your backend

    [CometChatCalls loginWithAuthToken:authToken 
                             onSuccess:^(CallsUser * user) {
        NSLog(@"Login successful: %@", user.uid);
    } onError:^(CometChatCallException error) {
        NSLog(@"Login failed: %@", error.errorDescription);
    }];
    ```
  </Tab>
</Tabs>

| Parameter   | Type    | Description                                |
| ----------- | ------- | ------------------------------------------ |
| `authToken` | String  | Auth Token generated via CometChat API     |
| `onSuccess` | Closure | Closure called with `CallsUser` on success |
| `onError`   | Closure | Closure called with error on failure       |

## CallsUser Object

On successful login, the callback returns a `CallsUser` object containing user information:

| Property | Type       | Description                    |
| -------- | ---------- | ------------------------------ |
| `uid`    | String?    | Unique identifier of the user  |
| `name`   | String?    | Display name of the user       |
| `avatar` | String?    | URL of the user's avatar image |
| `status` | UserStatus | User's online status           |

## Logout

Call `logout()` when the user signs out of your application. This clears the local session and disconnects from CometChat services.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChatCalls.logout(onSuccess: { message in
        print("Logout successful")
    }, onError: { error in
        print("Logout failed: \(error.errorDescription)")
    })
    ```
  </Tab>

  <Tab title="Objective-C">
    ```objectivec theme={null}
    [CometChatCalls logoutOnSuccess:^(NSString * message) {
        NSLog(@"Logout successful");
    } onError:^(CometChatCallException error) {
        NSLog(@"Logout failed: %@", error.errorDescription);
    }];
    ```
  </Tab>
</Tabs>

## Error Handling

Common authentication errors:

| Error Code                   | Description                           |
| ---------------------------- | ------------------------------------- |
| `ERROR_INVALID_UID`          | The provided UID is empty or invalid  |
| `ERROR_UID_WITH_SPACE`       | The UID contains spaces (not allowed) |
| `ERROR_API_KEY_NOT_FOUND`    | The API Key is missing or invalid     |
| `ERROR_BLANK_AUTHTOKEN`      | The Auth Token is empty               |
| `ERROR_AUTHTOKEN_WITH_SPACE` | The Auth Token contains spaces        |
