> ## 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

> Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat Flutter SDK.

> [accordion] AI Integration Quick Reference
>
> ```dart theme={null}
> // Check existing session
> User? user = await CometChat.getLoggedInUser();
>
> // Login with Auth Key (development only)
> CometChat.login("cometchat-uid-1", "AUTH_KEY",
>   onSuccess: (User user) { debugPrint("Logged in: $user"); },
>   onError: (CometChatException e) { debugPrint("Error: ${e.message}"); }
> );
>
> // Login with Auth Token (production)
> CometChat.loginWithAuthToken("AUTH_TOKEN",
>   onSuccess: (User user) { debugPrint("Logged in: $user"); },
>   onError: (CometChatException e) { debugPrint("Error: ${e.message}"); }
> );
>
> // Logout
> CometChat.logout(
>   onSuccess: (String msg) { debugPrint("Logged out"); },
>   onError: (CometChatException e) { debugPrint("Error: ${e.message}"); }
> );
> ```
>
> **Create users via:** [Dashboard](https://app.cometchat.com) (testing) | [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production)
> **Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5`

After [initializing](https://www.cometchat.com/docs/sdk/flutter/setup.md) the SDK, the next step is to authenticate your user. CometChat provides two login methods — Auth Key for quick development, and Auth Token for production — both accessed through the `login()` method.

### How It Works

```mermaid theme={null}
sequenceDiagram
    participant User
    participant YourApp as Your App
    participant YourServer as Your Server
    participant CometChat as CometChat

    User->>YourApp: Signs up / Logs in
    YourApp->>YourServer: Authenticate user
    YourServer->>CometChat: Create user (REST API, first time only)
    CometChat-->>YourServer: User created
    YourServer->>CometChat: Create Auth Token (REST API)
    CometChat-->>YourServer: Auth Token
    YourServer-->>YourApp: Return Auth Token
    YourApp->>CometChat: CometChat.loginWithAuthToken(authToken)
    CometChat-->>YourApp: User object (logged in)
```

## Before You Log In

### Create a User

A user must exist in CometChat before they can log in.

* **During development:** Create users from the [CometChat Dashboard](https://app.cometchat.com). Five test users are already available with UIDs `cometchat-uid-1` through `cometchat-uid-5`.
* **In production:** Call the [Create User REST API](https://api-explorer.cometchat.com/reference/creates-user) when a user signs up in your app.

> [!NOTE]
>
> We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`.

### Check for an Existing Session

The SDK persists the logged-in user's session locally. Before calling `login()`, always check whether a session already exists — this avoids unnecessary login calls and keeps your app responsive.

```dart theme={null}
User? user = await CometChat.getLoggedInUser();
if (user != null) {
  // User is already logged in — proceed to your app
}
```

If `getLoggedInUser()` returns `null`, no active session exists and you need to call `login()`.

| Method | Returns | Description |
| - | - | - |
| `CometChat.getLoggedInUser()` | `Future<User?>` | Returns the currently logged-in user, or `null` if no session exists |

## Login with Auth Key

This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [Auth Token](#login-with-auth-token) instead of an Auth Key to ensure enhanced security.

> [!WARNING]
>
> Auth Keys are meant for development and testing only. For production, use [Auth Token login](#login-with-auth-token) instead. Never ship Auth Keys in client-side code.

> [tab] Dart
>
> ```dart theme={null}
> String UID = "user_id"; // Replace with the UID of the user to login
> String authKey = "AUTH_KEY"; // Replace with your App Auth Key
>
> final user = await CometChat.getLoggedInUser();
> if (user == null) {
> await CometChat.login(UID, authKey,
> 		onSuccess: (User user) {
> 			debugPrint("Login Successful : $user" );
> 		}, onError: (CometChatException e) {
> 			debugPrint("Login failed with exception:  ${e.message}");
> 		});
> }
> ```

| Parameter | Type | Description |
| - | - | - |
| `UID` | `String` | The UID of the user to log in |
| `authKey` | `String` | Your CometChat Auth Key |

On success, the `onSuccess` callback receives a [`User`](https://www.cometchat.com/docs/sdk/reference/entities#user) object containing the logged-in user's details.

> [accordion] Response
>
> **On Success** — A `User` object representing the logged-in user:
>
> **User Object:**
>
> | Parameter | Type | Description | Sample Value |
> | - | - | - | - |
> | `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` |
> | `name` | string | Display name of the user | `"Andrew Joseph"` |
> | `link` | string | Profile link | `null` |
> | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` |
> | `metadata` | object | Custom metadata | `{}` |
> | `status` | string | Online status | `"online"` |
> | `role` | string | User role | `"default"` |
> | `statusMessage` | string | Status message | `null` |
> | `tags` | array | User tags | `[]` |
> | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
> | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
> | `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` |

> [accordion] Error
>
> **CometChatException:**
>
> | Parameter | Type | Description | Sample Value |
> | - | - | - | - |
> | `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` |
> | `message` | string | Human-readable error message | `"The specified UID does not exist."` |
> | `details` | string | Additional technical details | `"Please verify the UID and try again."` |

## Login with Auth Token

Auth Token login keeps your Auth Key off the client entirely. Your server generates a token via the REST API and passes it to the client.

1. [Create the user](https://api-explorer.cometchat.com/reference/creates-user) via the REST API when they sign up (first time only).
2. [Generate an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) on your server and return it to the client.
3. Pass the token to `loginWithAuthToken()`.

> [tab] Dart
>
> ```dart theme={null}
> String authToken = "AUTH_TOKEN";
> var user = await CometChat.getLoggedInUser(onSuccess: (_){}, onError: (_){});
> if (user == null) {
>  if(authToken!=null){
>    await  CometChat.loginWithAuthToken(authToken,
>                                        onSuccess: (User loggedInUser){
>                                          debugPrint("Login Successful : $user" );
>                                        }, onError: ( CometChatException e){
>                                          debugPrint("Login failed with exception:  ${e.message}");
>                                        });
>  }
> }
> ```

| Parameter | Type | Description |
| - | - | - |
| `authToken` | `String` | Auth Token generated on your server for the user |

On success, the `onSuccess` callback receives a [`User`](https://www.cometchat.com/docs/sdk/reference/entities#user) object containing the logged-in user's details.

> [accordion] Response
>
> **On Success** — A `User` object representing the logged-in user:
>
> **User Object:**
>
> | Parameter | Type | Description | Sample Value |
> | - | - | - | - |
> | `uid` | string | Unique identifier of the user | `"cometchat-uid-1"` |
> | `name` | string | Display name of the user | `"Andrew Joseph"` |
> | `link` | string | Profile link | `null` |
> | `avatar` | string | Avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` |
> | `metadata` | object | Custom metadata | `{}` |
> | `status` | string | Online status | `"online"` |
> | `role` | string | User role | `"default"` |
> | `statusMessage` | string | Status message | `null` |
> | `tags` | array | User tags | `[]` |
> | `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` |
> | `blockedByMe` | boolean | Whether the current user has blocked this user | `false` |
> | `lastActiveAt` | number | Epoch timestamp of last activity | `1745554700` |

> [accordion] Error
>
> **CometChatException:**
>
> | Parameter | Type | Description | Sample Value |
> | - | - | - | - |
> | `code` | string | Error code identifier | `"ERR_UID_NOT_FOUND"` |
> | `message` | string | Human-readable error message | `"The specified UID does not exist."` |
> | `details` | string | Additional technical details | `"Please verify the UID and try again."` |

## Logout

Call `logout()` when your user logs out of your app. This clears the local session.

> [tab] Dart
>
> ```dart theme={null}
> CometChat.logout( onSuccess: ( successMessage) {
>     debugPrint("Logout successful with message $successMessage");
>   }, onError: (CometChatException e ){
>     debugPrint("Logout failed with exception:  ${e.message}");
>       }
>   );
> ```

> [accordion] Response
>
> **On Success** — A `String` message confirming the logout:
>
> | Parameter | Type | Description | Sample Value |
> | - | - | - | - |
> | `message` | string | Success confirmation message | `"Logout successful"` |

> [accordion] Error
>
> **CometChatException:**
>
> | Parameter | Type | Description | Sample Value |
> | - | - | - | - |
> | `code` | string | Error code identifier | `"ERR_NOT_LOGGED_IN"` |
> | `message` | string | Human-readable error message | `"No active user session."` |
> | `details` | string | Additional technical details | `"Please log in before attempting to log out."` |

***

## Login Listener

You can listen for login and logout events in real time using `LoginListener`. This is useful for updating UI state or triggering side effects when the auth state changes.

| Callback | Description |
| - | - |
| `loginSuccess(User user)` | User logged in successfully. Provides the `User` object. |
| `loginFailure(CometChatException e)` | Login failed. Provides a `CometChatException`. |
| `logoutSuccess()` | User logged out successfully. |
| `logoutFailure(CometChatException e)` | Logout failed. Provides a `CometChatException`. |

### Add a Listener

> [tab] Dart
>
> ```dart theme={null}
> class Class_Name with LoginListener {
>
>   // CometChat.addLoginListener("UNIQUE_LISTENER_ID", this); // call this in initState
>
>   @override
>   void loginSuccess(User user) {
>     debugPrint("LoginListener loginSuccess: $user");
>   }
>
>   @override
>   void loginFailure(CometChatException e) {
>     debugPrint("LoginListener loginFailure: ${e.message}");
>   }
>
>   @override
>   void logoutSuccess() {
>     debugPrint("LoginListener logoutSuccess");
>   }
>
>   @override
>   void logoutFailure(CometChatException e) {
>     debugPrint("LoginListener logoutFailure: ${e.message}");
>   }
> }
> ```

### Remove a Listener

```dart theme={null}
CometChat.removeLoginListener("UNIQUE_LISTENER_ID");
```

> [!WARNING]
>
> Always remove login listeners when they're no longer needed (e.g., on widget disposal or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling.

***

## Next Steps

> [card] [Send Messages](https://www.cometchat.com/docs/sdk/flutter/send-message.md)
>
> Send your first text, media, or custom message

> [card] [User Management](https://www.cometchat.com/docs/sdk/flutter/user-management.md)
>
> Create, update, and manage users in your app

> [card] [Connection Status](https://www.cometchat.com/docs/sdk/flutter/connection-status.md)
>
> Monitor the SDK connection state in real time

> [card] [All Real-Time Listeners](https://www.cometchat.com/docs/sdk/flutter/real-time-listeners.md)
>
> Complete reference for all SDK event listeners


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.