public async Task <IActionResult> AddUserAsync([FromBody] UserX user, CancellationToken ct) { if (string.IsNullOrWhiteSpace(user.Password)) { return(BadRequest("Missing password.")); } user.Password = user.Password.Trim(); if (string.IsNullOrWhiteSpace(user.Name)) { return(BadRequest("Missing user name.")); } user.Name = user.Name.Trim(); if (string.IsNullOrWhiteSpace(user.m_FiltersText)) { return(BadRequest($"Missing filters.")); } if (!Enum.TryParse <Filters>(user.m_FiltersText.Trim(), true, out var filter)) { return(BadRequest($"Invalid filters: [{user.m_FiltersText}].")); } user.BaseFilters = filter; if (user.AccessLevel.Value > 10) { return(BadRequest($"Invalid access level (0-10): [{user.AccessLevel}].")); } var orgId = HttpContext.GetOrg(); user.Modified = null; user.OrgId = orgId; using (var db = new ConfigDB()) { var ux = await db.Users .Where(x => x.OrgId.Equals(user.OrgId, StringComparison.OrdinalIgnoreCase)) .SingleOrDefaultAsync(x => x.Password.Equals(user.Password, StringComparison.OrdinalIgnoreCase), ct) .ConfigureAwait(false); if (ux != null) { return(BadRequest($"Password [{user.Password}] already exists.")); } ux = await db.Users .Where(x => x.OrgId.Equals(user.OrgId, StringComparison.OrdinalIgnoreCase)) .SingleOrDefaultAsync(x => x.Name.Equals(user.Name, StringComparison.OrdinalIgnoreCase), ct) .ConfigureAwait(false); if (ux != null) { return(BadRequest($"User name [{user.Name}] already exists.")); } ux = user.GetBase(); db.Users.Add(ux); await db.SaveChangesAsync(ct).ConfigureAwait(false); return(Created($"users/{ux.ID}", new UserX(ux))); } }