login method

Future<AuthenticationResponse?> login(
  1. LogbotCredentials credentials, {
  2. String? otp,
})

Log in with a user, saves the credentials and tokens on the client to refresh the access later

Implementation

Future<AuthenticationResponse?> login(LogbotCredentials credentials,
    {String? otp}) {
  LogbotLogger().simple("login(): User Credentials: ${credentials.toJson()}");

  /// If the user is trying to login with a different user, will completely logout first
  String? currentUser = LogbotSecureStorageManager().credentials?.username;
  if (currentUser != null && currentUser != credentials.username) {
    LogbotLogger().simple("login(): User has changed. Will logout first");
    logout();
  }
  if (_isAuthenticated()) {
    LogbotLogger().simple(
        "login(): User is already authenticated, will not login again.");

    /// Ritorno un Future che non fa nulla perchè non posso ritornare null
    return Future(() => null);
  }
  LogbotLogger().simple(
      "login(): User is not authenticated. Will login with credentials.");

  /// if there is already a pending request for refresh/re authentication, it doesn't make any sense to request
  /// it again. Will just return the Future and everyone will wait for that
  if (_authenticationFuture != null) {
    LogbotLogger().simple(
        "login(): There is an authentication request pending already. Will wait for that");
    return _authenticationFuture!;
  }
  _authenticationFuture = AuthApi(
    credentials.basePath == null
        ? null
        : ApiClient(
            basePath: credentials.basePath!,
          ),
  )
      .loginOrRefresh(
    "password",
    credentials.clientId,
    credentials.clientSecret,
    username: credentials.username,
    password: credentials.password,
    totp: otp,
  )
      .then((AuthenticationResponse? response) {
    // Updates the value of the access token and refresh token
    _storeAuthenticationValues(credentials: credentials, response: response);
    LogbotLogger().simple(
        "login(): User ${credentials.username} successfully logged in");
    _authenticationFuture = null;
    return response;
  }).onError((ApiException error, stackTrace) {
    LogbotLogger().error("login()", error.toString(), stackTrace);
    _authenticationFuture = null;
    throw error;
  });
  return _authenticationFuture!;
}