Login and logout

Update time: 2024/03/07 11:13:40

NIM SDK for Flutter provides manual login and automatic login interfaces, as well as mechanisms and strategies such as automatic reconnection and multi-device login. Before calling the login interface, you must register a CommsEase IM account (account or accid) for each app user and obtain the corresponding token at the same time.

You can register an account using the following methods:

  • Method 1: sign up by calling the server API. In the production environment, users must sign up for an IM account in this way.
  • Mehtod 2: Register IM accounts in the CommsEase console . This method is suitable for account registration in the debugging phase.

How it works

The process of account registration and initial login:

uml diagram

Description:

  1. Register CommsEase IM accounts using the app accounts.
  2. CommsEase IM server return Token to the app server.
  3. A client logs on to the app server.
  4. App server returns Token to the client.
  5. An app client uses the token to log in to the CommsEase IM server.

API call sequence diagram

The following diagram shows the sequence of API call for the first login and logout. NIM in the diagram represents the NIM SDK for Flutter.

uml diagram

Listener to login

Before login for the first time, register listeners for login status changes, multi-device login events, and data sync status changes after successful login.

Listener to changes of the login status

You can listen to the login status using the event stream of login status(authStatus).

NIM SDK for Flutter cannot actively query whether the current account is online. You can listen to the login status changes and cache the status.

  • Parameters

    Two types of status events are available:

    • NIMAuthStatusEvent: Generic login status event, including NIMAuthStatus enumeration for login states.
    • NIMKickOutByOtherClientEvent: Removal event, including status fields and extra properties; The event must be parsed based on the specific types of events.
NIMAuthStatus Description
unknown Undefined
unLogin not logged in or failed login
netBroken disconnected
connecting Connecting to the CommsEase server
logging Logging in
loggedIn Logged in
kickOut If you are kicked out by the login session on another device, the page must be redirected to the manual login interface at this time. You can't log in automatically after being kicked
kickOutByOtherClient Removed due to the login session on another device (calling the kickOutOtherOnlineClient method). The page will be redirected to the login page. You can't log in automatically after being removed.
forbidden Banned by the CommsEase serverIM account banned. You can't log in automatically after being banned
versionError SDK version error. If this login exception occurs, you cannot log in automatically
pwdError CommsEase IM account (account) or token error. If this login exception occurs, you cannot log in automatically

For more information about login status changes, see [Login status changes](https://doc.commsease.com/docs/TM5MzM5Njk/zk5NTg0NTg?platformId=120326#login status changes).

  • Example
dart
    /// Start listening to events
    final subscription = NimCore.instance.authService.authStatus.listen((event) {
      if (event is NIMKickOutByOtherClientEvent) {
        /// Listen to the kick event
      } else if (event is NIMAuthStatusEvent) {
        /// Listen to other events
      }
    });

    /// If you do not want to listen to the events, unregister the listener. Otherwise, it will cause a memory leak
    /// subscription.cancel();

Listener to multi-device login event

You can listen to events for multi-device login using the following interfaces to obtain a list of online devices.

dartclass AuthService {
  /// Event of online client list change
  /// [NIMOnlineClient]
  Stream<List<NIMOnlineClient>> get onlineClients;
}
  • Parameters

NIMOnlineClient types:

Parameter Type Description
os String? Client operating system.
clientType NIMClientType Client type
loginTime int Login time
customTag String? Login custom properties
  • Example
dartfinal subscription = NimCore.instance.authService.onlineClients.listen((clients) {
  clients.forEach((client) {
    switch (client.clientType) {
      case NIMClientType.windows:
        // Windows
        break;
      case NIMClientType.macos:
        // macOS
        break;
      case NIMClientType.web:
        // Web
        break;
      case NIMClientType.ios:
        // iOS
        break;
      case NIMClientType.android:
        // Android
        break;
      default:
        // Unknown
        break;
    }
  });
});

/// If you do not want to listen to the events, unregister the listener. Otherwise, it will cause a memory leak
/// subscription.cancel();

Listener to data sync status

After successful login, the SDK will automatically synchronize data, such as group information, offline messages, roaming messages, and system notifications. Status changes of data synchronization are broadcast during data synchronization (NIMDataSyncStatusEvent). Use the following interface to listen to this event.

dartclass AuthService {
    /// Event of login state change
    Stream<NIMAuthStatusEvent> get authStatus;
}

Listening to events for data sync status is unavailable for Windows and macOS.

  • Parameters

The event of data synchronization contains a field of NIMAuthStatus used to identity sync status.:

NIMAuthStatus Description
NIMAuthStatus.dataSyncStart Sync start
NIMAuthStatus.dataSyncFinish Sync complete
  • Example
dart
    /// Start listening to events
    final subscription = NimCore.instance.authService.authStatus.listen((event) {
      if (event is NIMDataSyncStatusEvent) {
        /// Listen to data synchronization events
        if (event.status == NIMAuthStatus.dataSyncStart) {
          /// Data sync starts
        } else if (event.status == NIMAuthStatus.dataSyncFinish) {
          /// Data sync is complete
        }
      }
    });

    /// If you do not want to listen to the events, unregister the listener. Otherwise, it will cause a memory leak
    /// subscription.cancel();

Manual login

You must manually log on to your account in some cases, such as first login for a new device, being kicked out, account switch, or re-login. The method is used in scenario where an account and the corresponding password are required for manual login.

Manually log in by calling login. Store the account and token in the local database after the manual login is successful. The login credentials can be used when the app starts to automatically log in next time. For more information, see [Manual login best practices](https://doc.commsease.com /messaging/docs/zEwMTU1ODc?platform=flutter#Manual login).

javaclass AuthService {
    /// Login interface. The SDK automatically connects to the server and transmit user information. And the response returns the result.
    Future<NIMResult<void>> login(NIMLoginInfo loginInfo);
}
  • NIMLoginInfo description
NIMLoginInfo Required Description
account Yes CommsEase IM Account
token Yes Token used for login
authType No SDK authentication types:
  • NIMAuthType.authTypeDefault: basic loginToken verification (default)
  • NIMAuthType.authTypeDynamic: token calculated using AppSecret for authentication
  • NIMAuthType.authTypeThirdParty: Use token returned by a third party for authentication.
loginExt No Custom field for login
customClientType No Custom client type
  • Example
dartNimCore.instance.authService
    .login(NIMLoginInfo(account: 'account', token: 'token',))
    .then(
      (result) {
        if (result.isSuccess) {
          /// login success
        } else {
          /// Login failure
        }
      },
    );

The error codes for login failures are described as follows:

Code Description
302 appKey, account, and token mismatch
408 Connection to the CommsEase server timed out
415 Disconnected or connection failure
416 The manual login interface is called too frequently
1000 Error caused by failure to open the local database. Open the local database after successful manual login.

Automatic login

To automatically log in, pass the account and token to NIMAndroidSDKOptions or autoLoginInfo in NIMIOSSDKOptions before calling the initialize method to initialize the SDK.

After the manual login is successful, the user account and password stored to the local storage can be used for automatic login. The automatic login is used for scenarios where the login can be completed without entering the user name and password when the application is restarted after the process is killed. In this case, you can access the user's local data stored in the SDK without network and successful login. After automatic login is enabled, you must pay attention to handling the login status. For more information, see [Automatic login best practice] (https://doc.commsease.com/messaging/docs/zEwMTU1ODc?platform=flutter#Automatic login) .

Automatic login is supported on Android and iOS only. Windows and macOS do not support automatic login.

Sample code:

dartNimCore.instance.initialize(
  NIMAndroidSDKOptions(
    appKey: 'appkey',
    autoLoginInfo: NIMLoginInfo(
      account: 'account',
      token: 'token',
    ),
  ),
).then(
  (result) {
    if (result.isSuccess) {
      /// success
    } else {
      /// Initialization failure
    }
  },
);

Logout

You can log out by calling the logout method.

  • API prototype
javaclass AuthService {
  Future<NIMResult<void>> logout();
}
  • Example
dart    NimCore.instance.authService
    .logout()
    .then(
      (result) {
        if (result.isSuccess) {
          /// Success
        } else {
          /// Failure
        }
      }
    );

Mechanisms and strategies for login

Reconnection

The SDK provides an automatic reconnection mechanism. Under this mechanism, after the SDK is disconnected from the CommsEase server, it will automatically re-establish the connection and log in again. If the login state change is tracked, all login state changes caused by reconnection trigger the NIMAuthStatusEvent event.

The SDK will automatically re-establish the connection with the CommsEase server in the following two scenarios: You don't need to implement additional relogin logic on top tier of your application.

  • After successful manual/automatic login, the connection is disconnected due to poor network.
  • After the automatic login is configured during initialization, the connection between the SDK and the CommsEase server is caused by poor network (such as connection timeout), and the account and password is valid (not banned, and the account and password is correct).

Mutually exclusive login on multiple devices

You can configure the following multi-device login policies in the CommsEase console:

  • Only allow one login session
  • Desktop clients (PC and Web) are mutually exclusive for login. Mobile clients (Android and iOS) are mutually exclusive for login. Desktop clients and mobile clients can have simultaneous login sessions.
  • Clients of all platforms can have simultaneous login sessions (up to 10 devices are supported).

For information about how to configure multi-device login policies, see Multi-device login and simultaneous login policy.

To invalidate login sessions on other devices, call the kickOutOtherOnlineClient method. The method must take the NIMOnlineClient object that contain the list of online devices currently logged in to IM. The object is returned by (onlineClients).

If the current client is removed offline, a notification is received for the NIMKickOutByOtherClientEvent event. If the callback for the event is called, you can log out and switch to the login interface.

  • Parameters

NIMKickOutByOtherClientEvent description

Parameter Type Description
status NIMAuthStatus Current login status
clientType int? Get the type of a client that is kicked out
customClientType int? Get the custom type of a client that is kicked out
  • Example
dart
  NimCore.instance.authService
    .kickOutOtherOnlineClient(client)
    .then(
      (result) {
        if (result.isSuccess) {
          /// Success
        } else {
          /// Failure
        }
      }
    );

Login status change process

The login status change process (excluding special statuses, such as being kicked off and being banned by the IM server) is shown in the diagram below. In the diagram, the dark blue element represents the login status, and the light green element represents the automatic login or manual login calling the login method.

unLogin
unLogin
connecting
connecting
No
No
Yes
Yes
Whether the network connection works
Whether the network connection works
netBroken
netBroken
No
No
Yes
Yes
Whether physical network exists
Whether physical network exists
connecting
connecting
No
No
Yes
Yes
Whether the network connection works
Whether the network connection works
logging
logging
No
No
Yes
Yes
Whether the network connection works
Whether the network connection works
loggedIn
loggedIn
No
No
Yes
Yes
Whether the network connection works
Whether the network connection works
Start
Start
Connect/reconnect
Connect/reconnect
Text is not SVG - cannot display

Was this page helpful?
Yes
No
  • How it works
  • API call sequence diagram
  • Listener to login
  • Listener to changes of the login status
  • Listener to multi-device login event
  • Listener to data sync status
  • Manual login
  • Automatic login
  • Logout
  • Mechanisms and strategies for login
  • Reconnection
  • Mutually exclusive login on multiple devices
  • Login status change process