createUser static method

Future<UserInfo?> createUser(
  1. Session session,
  2. String userName,
  3. String email,
  4. String? password, [
  5. String? hash,
])

Creates a new user. Either password or hash needs to be provided.

Implementation

static Future<UserInfo?> createUser(
  Session session,
  String userName,
  String email,
  String? password, [
  String? hash,
]) async {
  assert(password != null || hash != null,
      'Either password or hash needs to be provided');
  var userInfo = await Users.findUserByEmail(session, email);

  if (userInfo == null) {
    userInfo = UserInfo(
      userIdentifier: email,
      email: email,
      userName: userName,
      created: DateTime.now(),
      scopeNames: [],
      blocked: false,
    );

    session.log('creating user', level: LogLevel.debug);
    userInfo = await Users.createUser(session, userInfo, 'email');
    if (userInfo == null) return null;
  }

  // Check if there is email authentication in place already
  var oldAuth = await session.db.findSingleRow<EmailAuth>(
    where: EmailAuth.t.userId.equals(userInfo.id!),
  );
  if (oldAuth != null) {
    return userInfo;
  }

  session.log('creating email auth', level: LogLevel.debug);
  hash = hash ?? generatePasswordHash(password!, email);
  var auth = EmailAuth(
    userId: userInfo.id!,
    email: email,
    hash: hash,
  );
  await session.db.insert(auth);

  await UserImages.setDefaultUserImage(session, userInfo.id!);
  await Users.invalidateCacheForUser(session, userInfo.id!);
  userInfo = await Users.findUserByUserId(session, userInfo.id!);

  session.log('returning created user', level: LogLevel.debug);
  return userInfo;
}