diff --git a/src/Application/Interfaces/Services/IAccountService.cs b/src/Application/Interfaces/Services/IAccountService.cs index 0596443..2fc8d60 100644 --- a/src/Application/Interfaces/Services/IAccountService.cs +++ b/src/Application/Interfaces/Services/IAccountService.cs @@ -6,6 +6,6 @@ namespace Application.Interfaces.Services; public interface IAccountService { Task AddAccountsFromCsvAsync(string filePath); - Task GetAccountByIdAsync(long accountId); + Task> GetAccountByIdAsync(long accountId); Task>> GetAllAccountsAsync(); } \ No newline at end of file diff --git a/src/Application/Interfaces/Services/IProfileService.cs b/src/Application/Interfaces/Services/IProfileService.cs index 561a7cd..17a658b 100644 --- a/src/Application/Interfaces/Services/IProfileService.cs +++ b/src/Application/Interfaces/Services/IProfileService.cs @@ -1,5 +1,5 @@ using Application.DTOs; -using Application.DTOs.Profile.ChangePassword; +using Application.DTOs.Profile; using Application.DTOs.Profile.EditProfile; using Application.DTOs.Profile.GetProfileInfo; diff --git a/src/Application/Interfaces/Services/IUserService.cs b/src/Application/Interfaces/Services/IUserService.cs index a2ac77c..1726571 100644 --- a/src/Application/Interfaces/Services/IUserService.cs +++ b/src/Application/Interfaces/Services/IUserService.cs @@ -1,15 +1,14 @@ using Application.DTOs; -using Application.DTOs.Identity.ChangeRole; using Application.DTOs.Identity.CreateUser; -using Application.DTOs.Identity.GetUser; using Application.DTOs.Identity.LoginUser; +using Application.DTOs.User; namespace Application.Interfaces.Services; public interface IUserService { - Task> SignUpUser(CreateUserRequest createIdentityDto); + Task> SignUp(CreateUserRequest createIdentityDto); Task> Login(LoginUserRequest loginDto); Task ChangeRole(ChangeRoleRequest changeRoleRequest); - Task> GetUsersAsync(); + Task>> GetAllUsersAsync(); } \ No newline at end of file diff --git a/src/Application/Services/DomainService/AccountService.cs b/src/Application/Services/DomainService/AccountService.cs index d09360d..8e8cef1 100644 --- a/src/Application/Services/DomainService/AccountService.cs +++ b/src/Application/Services/DomainService/AccountService.cs @@ -19,13 +19,14 @@ public AccountService(IAccountRepository accountRepository) public async Task AddAccountsFromCsvAsync(string filePath) { - var accountCsvModels = CsvReaderService.ReadFromCsv(filePath); - - var accounts = accountCsvModels - .Select(csvModel => csvModel.ToAccount()) - .ToList(); try { + var accountCsvModels = CsvReaderService.ReadFromCsv(filePath); + + var accounts = accountCsvModels + .Select(csvModel => csvModel.ToAccount()) + .ToList(); + var existingAccountIds = await _accountRepository.GetAllIdsAsync(); var newAccounts = accounts.Where(a => !existingAccountIds.Contains(a.AccountId)).ToList(); @@ -34,13 +35,26 @@ public async Task AddAccountsFromCsvAsync(string filePath) } catch (Exception ex) { - return Result.Fail($"An error occurred: {ex.Message}"); + return Result.Fail($"An unexpected error occurred: {ex.Message}"); } } - public async Task GetAccountByIdAsync(long accountId) + public async Task> GetAccountByIdAsync(long accountId) { - return await _accountRepository.GetByIdAsync(accountId); + try + { + var account = await _accountRepository.GetByIdAsync(accountId); + if (account == null) + { + return Result.Fail("Account not found"); + } + + return Result.Ok(account); + } + catch (Exception ex) + { + return Result.Fail($"An unexpected error occurred: {ex.Message}"); + } } public async Task>> GetAllAccountsAsync() @@ -52,7 +66,7 @@ public async Task>> GetAllAccountsAsync() } catch (Exception ex) { - return Result>.Fail($"An error occurred: {ex.Message}"); + return Result>.Fail($"An unexpected error occurred: {ex.Message}"); } } } \ No newline at end of file diff --git a/src/Application/Services/DomainService/ProfileService.cs b/src/Application/Services/DomainService/ProfileService.cs index aa916f6..69b6bf6 100644 --- a/src/Application/Services/DomainService/ProfileService.cs +++ b/src/Application/Services/DomainService/ProfileService.cs @@ -1,5 +1,5 @@ using Application.DTOs; -using Application.DTOs.Profile.ChangePassword; +using Application.DTOs.Profile; using Application.DTOs.Profile.EditProfile; using Application.DTOs.Profile.GetProfileInfo; using Application.ExtensionMethods; @@ -20,56 +20,75 @@ public ProfileService(IUserManagerRepository userManagerRepository) public async Task> EditProfileInfo(EditProfileInfoRequest infoRequest) { - var user = await _userManagerRepository.FindByIdAsync(infoRequest.UserId); - if (user == null) - return Result.Fail("User not found!"); - - - if (user.UserName != infoRequest.UserName) + try { - var existingUser = await _userManagerRepository.FindByNameAsync(infoRequest.UserName); - if (existingUser != null) - return Result.Fail("Username is already reserved by another user!"); - } + var user = await _userManagerRepository.FindByIdAsync(infoRequest.UserId); + if (user == null) + return Result.Fail("User not found!"); - user.UserName = infoRequest.UserName; - user.FirstName = infoRequest.FirstName; - user.LastName = infoRequest.LastName; - - var updateResult = await _userManagerRepository.UpdateAsync(user); - if (!updateResult.Succeeded) - return Result.Fail(updateResult.Errors.FirstMessage()); + if (user.UserName != infoRequest.UserName) + { + var existingUser = await _userManagerRepository.FindByNameAsync(infoRequest.UserName); + if (existingUser != null) + return Result.Fail("Username is already reserved by another user!"); + } + user.UserName = infoRequest.UserName; + user.FirstName = infoRequest.FirstName; + user.LastName = infoRequest.LastName; + + var updateResult = await _userManagerRepository.UpdateAsync(user); + if (!updateResult.Succeeded) + return Result.Fail(updateResult.Errors.FirstMessage()); - return Result.Ok(user.ToEditProfileInfoResponse()); + return Result.Ok(user.ToEditProfileInfoResponse()); + } + catch (Exception ex) + { + return Result.Fail($"An unexpected error occurred: {ex.Message}"); + } } public async Task> GetProfileInfo(GetProfileInfoRequest getProfileInfoRequest) { - var user = await _userManagerRepository.FindByIdAsync(getProfileInfoRequest.UserId); + try + { + var user = await _userManagerRepository.FindByIdAsync(getProfileInfoRequest.UserId); - if (user == null) - return Result.Fail("User not found!"); + if (user == null) + return Result.Fail("User not found!"); - var role = await _userManagerRepository.GetRoleAsync(user); + var role = await _userManagerRepository.GetRoleAsync(user); - return Result.Ok(user.ToGetProfileInfoResponse(role)); + return Result.Ok(user.ToGetProfileInfoResponse(role)); + } + catch (Exception ex) + { + return Result.Fail($"An unexpected error occurred: {ex.Message}"); + } } public async Task ChangePassword(ChangePasswordRequest request) { - var user = await _userManagerRepository.FindByIdAsync(request.UserId); - if (user == null) - return Result.Fail("User not found!"); + try + { + var user = await _userManagerRepository.FindByIdAsync(request.UserId); + if (user == null) + return Result.Fail("User not found!"); - var isPasswordCorrect = await _userManagerRepository.CheckPasswordAsync(user, request.CurrentPassword); - if (!isPasswordCorrect) - return Result.Fail("Incorrect current password!"); + var isPasswordCorrect = await _userManagerRepository.CheckPasswordAsync(user, request.CurrentPassword); + if (!isPasswordCorrect) + return Result.Fail("Incorrect current password!"); - var passwordChangeResult = await _userManagerRepository.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword); - if (!passwordChangeResult.Succeeded) - return Result.Fail(passwordChangeResult.Errors.FirstMessage()); + var passwordChangeResult = await _userManagerRepository.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword); + if (!passwordChangeResult.Succeeded) + return Result.Fail(passwordChangeResult.Errors.FirstMessage()); - return Result.Ok(); + return Result.Ok(); + } + catch (Exception ex) + { + return Result.Fail($"An unexpected error occurred: {ex.Message}"); + } } } \ No newline at end of file diff --git a/src/Application/Services/DomainService/UserService.cs b/src/Application/Services/DomainService/UserService.cs index ca2491e..6e0268f 100644 --- a/src/Application/Services/DomainService/UserService.cs +++ b/src/Application/Services/DomainService/UserService.cs @@ -1,8 +1,7 @@ using Application.DTOs; -using Application.DTOs.Identity.ChangeRole; using Application.DTOs.Identity.CreateUser; -using Application.DTOs.Identity.GetUser; using Application.DTOs.Identity.LoginUser; +using Application.DTOs.User; using Application.ExtensionMethods; using Application.Interfaces; using Application.Interfaces.Repositories; @@ -26,86 +25,114 @@ public UserService(IUserManagerRepository userManagerRepository, _tokenService = tokenService; } - public async Task> SignUpUser(CreateUserRequest createUserRequest) + public async Task> SignUp(CreateUserRequest createUserRequest) { - if (!await _roleManagerRepository.RoleExistsAsync(createUserRequest.Role)) + try { - return Result.Fail("role does not exist"); + if (!await _roleManagerRepository.RoleExistsAsync(createUserRequest.Role)) + { + return Result.Fail("Role does not exist."); + } + + var appUser = createUserRequest.ToAppUser(); + + var appUserResult = await _userManagerRepository.CreateAsync(appUser, createUserRequest.Password); + if (!appUserResult.Succeeded) + { + return Result.Fail(appUserResult.Errors.FirstMessage()); + } + + var roleResult = await _userManagerRepository.SetRoleAsync(appUser, createUserRequest.Role); + if (!roleResult.Succeeded) + { + return Result.Fail(roleResult.Errors.FirstMessage()); + } + + return Result.Ok(appUser.ToCreateUserResponse(createUserRequest.Role)); } - - var appUser = createUserRequest.ToAppUser(); - - var appUserResult = await _userManagerRepository.CreateAsync(appUser, createUserRequest.Password); - if (!appUserResult.Succeeded) - { - return Result.Fail(appUserResult.Errors.FirstMessage()); - } - - var roleResult = await _userManagerRepository.SetRoleAsync(appUser, createUserRequest.Role); - if (!roleResult.Succeeded) + catch (Exception ex) { - return Result.Fail(roleResult.Errors.FirstMessage()); + return Result.Fail($"An unexpected error occurred: {ex.Message}"); } - - return Result.Ok(appUser.ToCreateUserResponse(createUserRequest.Role)); } public async Task> Login(LoginUserRequest loginUserRequest) { - AppUser? appUser; - - if (!string.IsNullOrEmpty(loginUserRequest.UserName)) - { - appUser = await _userManagerRepository.FindByNameAsync(loginUserRequest.UserName); - } - else if (!string.IsNullOrEmpty(loginUserRequest.Email)) + try { - appUser = await _userManagerRepository.FindByEmailAsync(loginUserRequest.Email); + AppUser? appUser; + + if (!string.IsNullOrEmpty(loginUserRequest.UserName)) + { + appUser = await _userManagerRepository.FindByNameAsync(loginUserRequest.UserName); + } + else if (!string.IsNullOrEmpty(loginUserRequest.Email)) + { + appUser = await _userManagerRepository.FindByEmailAsync(loginUserRequest.Email); + } + else + { + return Result.Fail("You should enter email or username!"); + } + + if (appUser is null) return Result.Fail("Invalid username/email!"); + + var succeed = await _userManagerRepository.CheckPasswordAsync(appUser, loginUserRequest.Password); + + if (!succeed) return Result.Fail("Username/Email not found and/or password incorrect"); + + var role = await _userManagerRepository.GetRoleAsync(appUser); + var token = _tokenService.GenerateToken(appUser, role); + + return Result.Ok(appUser.ToLoginUserResponse(role, token)); } - else + catch (Exception ex) { - return Result.Fail("You should enter email or username!"); + return Result.Fail($"An unexpected error occurred: {ex.Message}"); } - - if (appUser is null) return Result.Fail("Invalid username/email!"); - - var succeed = await _userManagerRepository.CheckPasswordAsync(appUser, loginUserRequest.Password); - - if (!succeed) return Result.Fail("Username/Email not found and/or password incorrect"); - - var role = await _userManagerRepository.GetRoleAsync(appUser); - var token = _tokenService.GenerateToken(appUser, role); - - return Result.Ok(appUser.ToLoginUserResponse(role, token)); } public async Task ChangeRole(ChangeRoleRequest request) { - if (!await _roleManagerRepository.RoleExistsAsync(request.Role)) + try { - return Result.Fail("role does not exist"); - } - AppUser? appUser = await _userManagerRepository.FindByNameAsync(request.UserName); + if (!await _roleManagerRepository.RoleExistsAsync(request.Role)) + { + return Result.Fail("role does not exist"); + } + AppUser? appUser = await _userManagerRepository.FindByNameAsync(request.UserName); - if (appUser is null) return Result.Fail("Invalid username"); + if (appUser is null) return Result.Fail("Invalid username"); - var result = await _userManagerRepository.ChangeRoleAsync(appUser, request.Role); + var result = await _userManagerRepository.ChangeRoleAsync(appUser, request.Role); - return result.Succeeded ? Result.Ok() : Result.Fail(result.Errors.FirstMessage()); + return result.Succeeded ? Result.Ok() : Result.Fail(result.Errors.FirstMessage()); + } + catch (Exception ex) + { + return Result.Fail($"An unexpected error occurred: {ex.Message}"); + } } - public async Task> GetUsersAsync() + public async Task>> GetAllUsersAsync() { - var users = await _userManagerRepository.GetUsersAsync(); - var userWithRoles = new List(); + try + { + var users = await _userManagerRepository.GetUsersAsync(); + var userWithRoles = new List(); - foreach (var user in users) + foreach (var user in users) + { + var role = await _userManagerRepository.GetRoleAsync(user); + var userResponse = user.ToGetUserResponse(role); + userWithRoles.Add(userResponse); + } + + return Result>.Ok(userWithRoles); + } + catch (Exception ex) { - var role = await _userManagerRepository.GetRoleAsync(user); - var userResponse = user.ToGetUserResponse(role); - userWithRoles.Add(userResponse); + return Result>.Fail($"An unexpected error occurred: {ex.Message}"); } - - return userWithRoles; } } \ No newline at end of file diff --git a/src/Web/Services/TokenService.cs b/src/Web/Services/TokenService.cs index bd730b4..1134a4c 100644 --- a/src/Web/Services/TokenService.cs +++ b/src/Web/Services/TokenService.cs @@ -4,7 +4,7 @@ using Application.Interfaces; using Domain.Entities; using Microsoft.IdentityModel.Tokens; -using Web.Identity; +using Web.AccessControl; namespace Web.Services; diff --git a/test/Application.UnitTests/Services/DomainService/ProfileServiceTests.cs b/test/Application.UnitTests/Services/DomainService/ProfileServiceTests.cs index ee8e8dd..f701b9c 100644 --- a/test/Application.UnitTests/Services/DomainService/ProfileServiceTests.cs +++ b/test/Application.UnitTests/Services/DomainService/ProfileServiceTests.cs @@ -1,4 +1,4 @@ -using Application.DTOs.Profile.ChangePassword; +using Application.DTOs.Profile; using Application.DTOs.Profile.EditProfile; using Application.DTOs.Profile.GetProfileInfo; using Application.Interfaces.Repositories; diff --git a/test/Application.UnitTests/Services/DomainService/UserServiceTests.cs b/test/Application.UnitTests/Services/DomainService/UserServiceTests.cs index 6c3c749..ebfc0a3 100644 --- a/test/Application.UnitTests/Services/DomainService/UserServiceTests.cs +++ b/test/Application.UnitTests/Services/DomainService/UserServiceTests.cs @@ -1,7 +1,6 @@ -using Application.DTOs.Identity.ChangeRole; -using Application.DTOs.Identity.CreateUser; -using Application.DTOs.Identity.GetUser; +using Application.DTOs.Identity.CreateUser; using Application.DTOs.Identity.LoginUser; +using Application.DTOs.User; using Application.Interfaces; using Application.Interfaces.Repositories; using Application.Mappers; @@ -9,7 +8,7 @@ using Domain.Entities; using Microsoft.AspNetCore.Identity; using NSubstitute; -using Web.DTOs.Identity; +using Web.DTOs.User.Login; using Web.Mappers; namespace test.Application.UnitTests.Services.DomainService; @@ -45,7 +44,7 @@ public async Task SignUpUser_WhenRoleDoesNotExist_ReturnsFailResult() _roleManagerRepository.RoleExistsAsync(createUserRequest.Role).Returns(Task.FromResult(false)); // Act - var result = await _userService.SignUpUser(createUserRequest); + var result = await _userService.SignUp(createUserRequest); // Assert Assert.False(result.Succeed); @@ -70,7 +69,7 @@ public async Task SignUpUser_WhenUserCreationFails_ReturnsFailResult() .Returns(Task.FromResult(IdentityResult.Failed(new IdentityError { Description = "User creation failed" }))); // Act - var result = await _userService.SignUpUser(createUserRequest); + var result = await _userService.SignUp(createUserRequest); // Assert Assert.False(result.Succeed); @@ -98,7 +97,7 @@ public async Task SignUpUser_WhenRoleAssignmentFails_ReturnsFailResult() .Returns(Task.FromResult(IdentityResult.Failed(new IdentityError { Description = "Role assignment failed" }))); // Act - var result = await _userService.SignUpUser(createUserRequest); + var result = await _userService.SignUp(createUserRequest); // Assert Assert.False(result.Succeed); @@ -139,7 +138,7 @@ public async Task SignUpUser_WhenUserIsCreatedAndRoleAssignedSuccessfully_Return }; // Act - var result = await _userService.SignUpUser(createUserRequest); + var result = await _userService.SignUp(createUserRequest); // Assert Assert.True(result.Succeed); @@ -330,10 +329,9 @@ public async Task GetUsersAsync_ReturnsUserListWithRoles() new GetUserResponse { UserName = "User2", Email = "user2@example.com", Role = "User" } }; - // Mock the repository methods _userManagerRepository.GetUsersAsync() .Returns(Task.FromResult(users)); - + _userManagerRepository.GetRoleAsync(users[0]) .Returns(Task.FromResult(roles[0])); @@ -341,12 +339,21 @@ public async Task GetUsersAsync_ReturnsUserListWithRoles() .Returns(Task.FromResult(roles[1])); // Act - var result = await _userService.GetUsersAsync(); + var result = await _userService.GetAllUsersAsync(); // Assert Assert.NotNull(result); - Assert.Equal(2, result.Count); - Assert.Contains(result, r => r.UserName == "User1" && r.Role == "Admin"); - Assert.Contains(result, r => r.UserName == "User2" && r.Role == "User"); + Assert.True(result.Succeed, "Result should be successful"); + Assert.NotNull(result.Value); + Assert.Equal(2, result.Value.Count); + + var user1Response = result.Value.SingleOrDefault(r => r.UserName == "User1"); + Assert.NotNull(user1Response); + Assert.Equal("Admin", user1Response.Role); + + var user2Response = result.Value.SingleOrDefault(r => r.UserName == "User2"); + Assert.NotNull(user2Response); + Assert.Equal("User", user2Response.Role); } + } \ No newline at end of file