logIn method

Future<LoginResponseStatus> logIn({
  1. required String username,
  2. required String password,
  3. required String url,
  4. Dio? dioTestClient,
})

Implementation

Future<LoginResponseStatus> logIn(
    {required String username,
    required String password,
    required String url,
    Dio? dioTestClient}) async {
  HttpResponse userResponse = await HttpClient.get(
      'me.json?fields=id,name,created,lastUpdated,birthday,gender,displayName,jobTitle,surname,employer,email,firstName,phoneNumber,nationality,userCredentials[code,id,name,lastLogin,displayName,username,userRoles[id,name,code]],organisationUnits[id,code,name,parent],dataViewOrganisationUnits[id,code,name,parent],userGroups[id,name],authorities,programs,dataSets',
      baseUrl: url,
      username: username,
      password: password,
      dioTestClient: dioTestClient);
  if (userResponse.statusCode == 401) {
    return LoginResponseStatus.WRONG_CREDENTIALS;
  }

  if (userResponse.statusCode == 500) {
    return LoginResponseStatus.SERVER_ERROR;
  }

  final uri = Uri.parse(url).host;
  final String databaseName = '${username}_$uri';

  await d2Instance.setDatabase(
      databaseName: databaseName,
      inMemory: d2Instance.inMemory,
      databaseFactory: d2Instance.databaseFactory,
      sharedPreferenceInstance: d2Instance.sharedPreferenceInstance);

  Map<String, dynamic> userData = userResponse.body;

  userData['password'] = password;
  userData['isLoggedIn'] = true;
  userData['username'] = username;
  userData['baseUrl'] = url;
  userData['authTye'] = 'basic';
  userData['dirty'] = true;

  final user = User.fromApi(userData);
  await d2Instance.userModule.user.setData(user).save();

  await d2Instance.userModule.userOrganisationUnit
      .setData(user.organisationUnits)
      .save();

  return LoginResponseStatus.ONLINE_LOGIN_SUCCESS;
}