public async Task <int> AddUser(AccountCreatedTransferObject user) { if (string.IsNullOrEmpty(user.ExternalCustomerId)) { throw new ConnectionStringNotFoundException("Cannot identify customer to which user should be created"); } var loginDbConnectionString = await _csProvider.GetLoginDb(); if (string.IsNullOrEmpty(loginDbConnectionString)) { throw new ConnectionStringNotFoundException("Login DB connection string is not found"); } var values = _configuration.UserDefaults; // if we're here then no account is associated with loginId or externalLoginId // only externalCustomerId can be used to lookup DB details var dbDetails = await _csProvider.GetCustomerDbDetails(user.ExternalCustomerId, loginDbConnectionString); var orgId = dbDetails.Item1; var connectionString = dbDetails.Item2; var applicationsToAdd = string.Empty; int defaultUserGroupId = GetDefaultUserGroup(connectionString).Result; if (defaultUserGroupId == 0) { defaultUserGroupId = 1; //set default user group to SC Administrators } if (user.PermissionSets.Any()) { applicationsToAdd = String.Join(",", user.PermissionSets.ToArray()); } var dbUserId = new SqlParameter("@user_id", SqlDbType.Int) { Direction = ParameterDirection.Output }; await Exec(connectionString, "sc_admin_save_preferences", p => { p.Add(dbUserId); p.AddWithValue("@email", user.EmailAddress); p.AddWithValue("@login_name", user.Username); p.AddWithValue("@forename", user.FirstName); p.AddWithValue("@lastname", user.LastName); p.AddWithValue("@ugroup_id", defaultUserGroupId); p.AddWithValue("@language_id", values["language_id"]); p.AddWithValue("@set_default", true); // required to add default group p.AddWithValue("@applications_to_add", applicationsToAdd); }); var userId = Convert.ToInt32(dbUserId.Value); var ids = await GetUserId(connectionString, userId); if (ids == null) { throw new ListenerException("Cannot map external account to the StarChef account"); } var userConfig = ids.Item2; var isEnabled = ids.Item3; var isDeleted = ids.Item4; var dbLoginId = new SqlParameter("@login_id", SqlDbType.Int) { Direction = ParameterDirection.Output }; await Exec(loginDbConnectionString, "sc_admin_update_login", p => { p.Add(dbLoginId); p.AddWithValue("@login_name", user.Username); p.AddWithValue("@db_application_id", values["db_application_id"]); p.AddWithValue("@db_database_id", orgId); p.AddWithValue("@user_id", userId); p.AddWithValue("@db_role_id", values["db_role_id"]); var pwd = Fourth.StarChef.Invariables.Security.PasswordGenerator.RandomSsoGuidPassword(); pwd = new Fourth.StarChef.Invariables.Security.CustomEncryption().Encrypt(pwd); p.AddWithValue("@login_password", pwd); p.AddWithValue("@login_config", userConfig); p.AddWithValue("@is_enabled", isEnabled); p.AddWithValue("@is_deleted", isDeleted); p.AddWithValue("@external_login_id", user.ExternalLoginId); }); return(Convert.ToInt32(dbLoginId.Value)); }