loginUser method

Future<String?> loginUser(
  1. LoginData data,
  2. bool rememberMe
)

Logs in the user by verifying the provided credentials.

This function checks the user's credentials by hashing the password, sending the login request, and saving the credentials locally if rememberMe is true.

  • data: A LoginData object containing the username and password.
  • rememberMe: A flag indicating if the user's credentials should be saved for future logins.

Returns null on successful login, or an error message otherwise.

Implementation

Future<String?> loginUser(LoginData data, bool rememberMe) async {
  LoadingDialog loadingDialog = LoadingDialog(buildContext: context);
  loadingDialog.showLoadingDialog();

  try {
    // Hash the password before sending to API
    EncryptionUtils encryptionUtils = EncryptionUtils();
    String hashedPassword = encryptionUtils.hashUserPassword(
        passwordToHash: data.password,
        userName: data.name
    );

    // Call the login API
    ApiReturn loginReturn = await Provider.of<DataProvider>(context, listen: false)
        .dataHandler
        .getUserRepo()
        .login(
      hashedPassword: hashedPassword,
      userName: data.name,
    );

    // If login is successful
    if (loginReturn.success) {
      await Provider.of<DataProvider>(context, listen: false)
          .userHasLoggedIn(loginReturn.data);

      // Save user credentials if `rememberMe` is enabled
      if (rememberMe) {
        await SharedPrefUtils().set("lastLoggedInUserName", data.name);
        await SharedPrefUtils().set("lastLoggedInUserPassword", data.password);
      }

      loadingDialog.closeLoadingDialog();
      return null;
    } else {
      loadingDialog.closeLoadingDialog();
      return '${loginReturn.returnCode}\n${loginReturn.explanation}';
    }
  } catch (e) {
    loadingDialog.closeLoadingDialog();
    return e.toString();
  }
}