namespace Diligent.WebAPI.Business.Services { public class UserService : IUserService { private readonly FrontEndSettings _frontEndSettings; private readonly UserManager _userManager; private readonly IMapper _mapper; private readonly DatabaseContext _databaseContext; private readonly IEmailer _emailer; private readonly ILogger _logger; public UserService(IOptions frontEndSettings, UserManager userManager, IMapper mapper, DatabaseContext databaseContext, IEmailer emailer, ILogger logger) { _frontEndSettings = frontEndSettings.Value; _userManager = userManager; _mapper = mapper; _databaseContext = databaseContext; _emailer = emailer; _logger = logger; } public async Task> GetAll() { _logger.LogInformation("Start getting all users"); _logger.LogInformation("Getting data from DB"); var fromDb = await _userManager.GetUsersInRoleAsync("Admin"); _logger.LogInformation($"Received {fromDb.Count} ads from db."); return fromDb; } public async Task GetFirst() { var result = await _userManager.Users.FirstOrDefaultAsync(); if (result == null) throw new EntityNotFoundException("No users in database"); return result; } #region REFACTORING CODE HERE TO CHECK IF USER IS NULL public async Task GetById(int id) { _logger.LogInformation($"Start searching user with id = {id}"); var result = await _userManager.FindByIdAsync(id.ToString()); if (result == null) { throw new EntityNotFoundException("User not found"); } return result; } public async Task GetByEmail(string email) { _logger.LogInformation($"Start searching user with mail = {email}"); var result = await _userManager.FindByEmailAsync(email); if (result == null) { throw new EntityNotFoundException("User not found"); } return result; } #endregion public async Task CreateUser(CreateUserRequestDto model) { _logger.LogInformation($"Start creating user"); var user = _mapper.Map(model); _logger.LogInformation($"User created successfully"); _logger.LogInformation($"Saving user to db..."); await _userManager.CreateAsync(user, model.Password); _logger.LogInformation($"User saved to DB"); } public async Task RemoveUser(User user) { await _userManager.DeleteAsync(user); await _databaseContext.SaveChangesAsync(); } public async Task ToggleEnable(User user) { user.IsEnabled = !user.IsEnabled; await _databaseContext.SaveChangesAsync(); return user.IsEnabled; } public async Task> SendRegistrationLink(InviteDTO invite) { // check if user exists var check = await _userManager.FindByEmailAsync(invite.Email); if (check != null) return new ServiceResponseDTO() { IsError = true, ErrorMessage = "User already registered." }; // create template user // this user is disabled to log in until confirming invitation var user = new User { UserName = invite.Email, Email = invite.Email, FirstName = invite.FirstName, LastName = invite.LastName, IsEnabled = false }; await _userManager.CreateAsync(user, StringGenerator.GenerateRandomPassword()); await _userManager.AddToRoleAsync(user, "Admin"); // generate invitation token for user // encoded for URLs var token = await _userManager.GeneratePasswordResetTokenAsync(user); token = HttpUtility.UrlEncode(token); // send link await _emailer.SendEmailAndWriteToDbAsync(invite.Email, "Welcome", HTMLHelper.RenderRegisterPage($"{_frontEndSettings.BaseUrl}/register?token={token}&email={invite.Email}"), isHtml: true); await _databaseContext.SaveChangesAsync(); return new ServiceResponseDTO { Data = new { Message = "Link has been sent!" } }; } public async Task GrantCategoryToUserAsync(GrantUserCategoryRequestDto request) { //for (int i = 0; i < request.CategoriesId.Count; i++) //{ // await _databaseContext.UserCategories.AddAsync(new UserCategories { UserId = request.UserId, CategoryId = request.CategoriesId[i] }); //} //await _databaseContext.SaveChangesAsync(); for (int i = 0; i < request.Categories.Count; i++) { if (request.Categories[i].IsChecked == false) { var category = await _databaseContext.UserCategories.Where(x => x.UserId == request.UserId && x.CategoryId == request.Categories[i].Id).FirstOrDefaultAsync(); _databaseContext.UserCategories.Remove(category); } else { await _databaseContext.UserCategories.AddAsync(new UserCategories { UserId = request.UserId, CategoryId = request.Categories[i].Id }); } } await _databaseContext.SaveChangesAsync(); } } }