> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-v6-beta2-flutter-uikit.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Learn how to create users, log in with Auth Key or Auth Token, and manage user sessions in CometChat React Native SDK.

<Info>
  **Quick Reference** - Login with Auth Key (dev) or Auth Token (production):

  ```javascript theme={null}
  // Auth Key login (development only)
  const user = await CometChat.login("USER_UID", "AUTH_KEY");

  // Auth Token login (recommended for production)
  const user = await CometChat.login("AUTH_TOKEN");

  // Check existing session
  const loggedInUser = await CometChat.getLoggedinUser();
  ```
</Info>

## Create User

Before you log in a user, you must add the user to CometChat.

1. **For proof of concept/MVPs**: Create the user using the [CometChat Dashboard](https://app.cometchat.com).
2. **For production apps**: Use the CometChat [Create User API](https://api-explorer.cometchat.com/reference/creates-user) to create the user when your user signs up in your app.

<Note>
  **Sample Users:** We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`.
</Note>

Once initialization is successful, you will need to log the user into CometChat using the `login()` method.

We recommend you call the CometChat login method once your user logs into your app. The `login()` method needs to be called only once.

<Warning>
  The CometChat SDK maintains the session of the logged-in user within the SDK. Thus you do not need to call the login method for every session. You can use the `CometChat.getLoggedinUser()` method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns `null`, it implies there is no session present within the SDK and you need to log the user into CometChat.
</Warning>

## Login using Auth Key

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

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    var UID = "UID";
    var authKey = "AUTH_KEY";

    // Check if user is already logged in before calling login
    CometChat.getLoggedinUser().then(
      (user) => {
        if (!user) {
          CometChat.login(UID, authKey).then(
            (user) => {
              console.log("Login Successful:", user);
            },
            (error) => {
              console.log("Login failed with exception:", error);
            }
          );
        }
      },
      (error) => {
        console.log("Something went wrong", error);
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    var UID: string = "cometchat-uid-1",
      authKey: string = "AUTH_KEY";

    // Check if user is already logged in before calling login
    CometChat.getLoggedinUser().then(
      (user: CometChat.User) => {
        if (!user) {
          CometChat.login(UID, authKey).then(
            (user: CometChat.User) => {
              console.log("Login Successful:", user);
            },
            (error: CometChat.CometChatException) => {
              console.log("Login failed with exception:", error);
            }
          );
        }
      },
      (error: CometChat.CometChatException) => {
        console.log("Some Error Occured", error);
      }
    );
    ```
  </Tab>
</Tabs>

| Parameter | Description                                      |
| --------- | ------------------------------------------------ |
| UID       | The UID of the user that you would like to login |
| authKey   | CometChat Auth Key                               |

After the user logs in, their information is returned in the `User` object on `Promise` resolved.

<Accordion title="Response">
  **On Success** — Returns a User object:

  <span id="login-authkey-user-object" style={{scrollMarginTop: '100px'}} />

  **User Object:**

  | Parameter       | Type    | Description                                         | Sample Value                                                            |
  | --------------- | ------- | --------------------------------------------------- | ----------------------------------------------------------------------- |
  | `uid`           | string  | Unique identifier of the user                       | `"cometchat-uid-2"`                                                     |
  | `name`          | string  | Display name of the user                            | `"George Alan"`                                                         |
  | `authToken`     | string  | Authentication token for the session                | `"cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0"`            |
  | `avatar`        | string  | URL to user's avatar image                          | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` |
  | `status`        | string  | Current online status                               | `"online"`                                                              |
  | `role`          | string  | User's role                                         | `"default"`                                                             |
  | `lastActiveAt`  | number  | Unix timestamp of last activity                     | `1771311515`                                                            |
  | `hasBlockedMe`  | boolean | Whether this user has blocked the logged-in user    | `false`                                                                 |
  | `blockedByMe`   | boolean | Whether logged-in user has blocked this user        | `false`                                                                 |
  | `deactivatedAt` | number  | Unix timestamp if user is deactivated (0 if active) | `0`                                                                     |
  | `tags`          | array   | Tags associated with the user                       | `[]`                                                                    |
</Accordion>

## Login using Auth Token

This advanced authentication procedure does not use the Auth Key directly in your client code, thus ensuring safety.

<Steps>
  <Step title="Create a User">
    [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app.
  </Step>

  <Step title="Create an Auth Token">
    [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database.
  </Step>

  <Step title="Login with the token">
    Load the Auth Token in your client and pass it to the `login()` method.
  </Step>
</Steps>

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    var authToken = "AUTH_TOKEN";

    // Check if user is already logged in before calling login
    CometChat.getLoggedinUser().then(
      (user) => {
        if (!user) {
          CometChat.login(authToken).then(
            (user) => {
              console.log("Login Successful:", user);
            },
            (error) => {
              console.log("Login failed with exception:", error);
            }
          );
        }
      },
      (error) => {
        console.log("Something went wrong", error);
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    var authToken: string = "AUTH_TOKEN";

    // Check if user is already logged in before calling login
    CometChat.getLoggedinUser().then(
      (user: CometChat.User) => {
        if (!user) {
          CometChat.login(authToken).then(
            (user: CometChat.User) => {
              console.log("Login Successful:", user);
            },
            (error: CometChat.CometChatException) => {
              console.log("Login failed with exception:", error);
            }
          );
        }
      },
      (error: CometChat.CometChatException) => {
        console.log("Some Error Occured", error);
      }
    );
    ```
  </Tab>
</Tabs>

| Parameter | Description                                    |
| --------- | ---------------------------------------------- |
| authToken | Auth Token of the user you would like to login |

After the user logs in, their information is returned in the `User` object on the `Promise` resolved.

<Accordion title="Response">
  **On Success** — Returns a User object:

  <span id="login-authtoken-user-object" style={{scrollMarginTop: '100px'}} />

  **User Object:**

  | Parameter       | Type    | Description                                         | Sample Value                                                            |
  | --------------- | ------- | --------------------------------------------------- | ----------------------------------------------------------------------- |
  | `uid`           | string  | Unique identifier of the user                       | `"cometchat-uid-2"`                                                     |
  | `name`          | string  | Display name of the user                            | `"George Alan"`                                                         |
  | `authToken`     | string  | Authentication token for the session                | `"cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0"`            |
  | `avatar`        | string  | URL to user's avatar image                          | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` |
  | `status`        | string  | Current online status                               | `"online"`                                                              |
  | `role`          | string  | User's role                                         | `"default"`                                                             |
  | `lastActiveAt`  | number  | Unix timestamp of last activity                     | `1771311515`                                                            |
  | `hasBlockedMe`  | boolean | Whether this user has blocked the logged-in user    | `false`                                                                 |
  | `blockedByMe`   | boolean | Whether logged-in user has blocked this user        | `false`                                                                 |
  | `deactivatedAt` | number  | Unix timestamp if user is deactivated (0 if active) | `0`                                                                     |
  | `tags`          | array   | Tags associated with the user                       | `[]`                                                                    |
</Accordion>

## Logout

You can use the `logout()` method to log out the user from CometChat. We suggest you call this method once your user has been successfully logged out from your app.

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    CometChat.logout().then(
      () => {
        console.log("Logout completed successfully");
      },
      (error) => {
        console.log("Logout failed with exception:", error);
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    CometChat.logout().then(
      (loggedOut: Object) => {
        console.log("Logout completed successfully");
      },
      (error: CometChat.CometChatException) => {
        console.log("Logout failed with exception:", error);
      }
    );
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  **On Success** — Returns a success message:

  | Parameter | Type   | Description         | Sample Value                      |
  | --------- | ------ | ------------------- | --------------------------------- |
  | `message` | string | Logout confirmation | `"Logout completed successfully"` |
</Accordion>

<AccordionGroup>
  <Accordion title="Best Practices">
    * Always check for an existing session with `getLoggedinUser()` before calling `login()`
    * Use Auth Token (not Auth Key) in production environments
    * Generate Auth Tokens server-side and never expose your REST API Key in client code
    * Call `logout()` when the user logs out of your app to clean up the CometChat session
    * Handle login errors gracefully and provide user-friendly error messages
  </Accordion>

  <Accordion title="Troubleshooting">
    * **Login fails with "UID not found":** Ensure the user has been created in CometChat before attempting login
    * **Auth Token expired:** Generate a new Auth Token from your server and retry login
    * **Session persists after logout:** Ensure `logout()` completes successfully before redirecting
    * **Multiple login calls:** Use `getLoggedinUser()` to prevent redundant login attempts
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Login Listener" icon="bell" href="/sdk/react-native/login-listener">
    Listen for real-time login and logout events
  </Card>

  <Card title="Send Messages" icon="paper-plane" href="/sdk/react-native/messaging">
    Start sending text, media, and custom messages
  </Card>

  <Card title="User Presence" icon="circle-dot" href="/sdk/react-native/user-presence">
    Track real-time online/offline status of users
  </Card>

  <Card title="UI Kit Integration" icon="palette" href="/ui-kit/react-native/overview">
    Add pre-built UI components to your app
  </Card>
</CardGroup>
