Skip to content

Commit

Permalink
refactor: add error handling & set signature conventions to services
Browse files Browse the repository at this point in the history
  • Loading branch information
mobinbr committed Aug 28, 2024
1 parent ca3166a commit 0866bed
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 121 deletions.
2 changes: 1 addition & 1 deletion src/Application/Interfaces/Services/IAccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ namespace Application.Interfaces.Services;
public interface IAccountService
{
Task<Result> AddAccountsFromCsvAsync(string filePath);
Task<Account?> GetAccountByIdAsync(long accountId);
Task<Result<Account>> GetAccountByIdAsync(long accountId);
Task<Result<List<Account>>> GetAllAccountsAsync();
}
2 changes: 1 addition & 1 deletion src/Application/Interfaces/Services/IProfileService.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
7 changes: 3 additions & 4 deletions src/Application/Interfaces/Services/IUserService.cs
Original file line number Diff line number Diff line change
@@ -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<Result<CreateUserResponse>> SignUpUser(CreateUserRequest createIdentityDto);
Task<Result<CreateUserResponse>> SignUp(CreateUserRequest createIdentityDto);
Task<Result<LoginUserResponse>> Login(LoginUserRequest loginDto);
Task<Result> ChangeRole(ChangeRoleRequest changeRoleRequest);
Task<List<GetUserResponse>> GetUsersAsync();
Task<Result<List<GetUserResponse>>> GetAllUsersAsync();
}
32 changes: 23 additions & 9 deletions src/Application/Services/DomainService/AccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ public AccountService(IAccountRepository accountRepository)

public async Task<Result> AddAccountsFromCsvAsync(string filePath)
{
var accountCsvModels = CsvReaderService.ReadFromCsv<AccountCsvModel>(filePath);

var accounts = accountCsvModels
.Select(csvModel => csvModel.ToAccount())
.ToList();
try
{
var accountCsvModels = CsvReaderService.ReadFromCsv<AccountCsvModel>(filePath);

var accounts = accountCsvModels
.Select(csvModel => csvModel.ToAccount())
.ToList();

var existingAccountIds = await _accountRepository.GetAllIdsAsync();
var newAccounts = accounts.Where(a => !existingAccountIds.Contains(a.AccountId)).ToList();

Expand All @@ -34,13 +35,26 @@ public async Task<Result> 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<Account?> GetAccountByIdAsync(long accountId)
public async Task<Result<Account>> GetAccountByIdAsync(long accountId)
{
return await _accountRepository.GetByIdAsync(accountId);
try
{
var account = await _accountRepository.GetByIdAsync(accountId);
if (account == null)
{
return Result<Account>.Fail("Account not found");
}

return Result<Account>.Ok(account);
}
catch (Exception ex)
{
return Result<Account>.Fail($"An unexpected error occurred: {ex.Message}");
}
}

public async Task<Result<List<Account>>> GetAllAccountsAsync()
Expand All @@ -52,7 +66,7 @@ public async Task<Result<List<Account>>> GetAllAccountsAsync()
}
catch (Exception ex)
{
return Result<List<Account>>.Fail($"An error occurred: {ex.Message}");
return Result<List<Account>>.Fail($"An unexpected error occurred: {ex.Message}");
}
}
}
87 changes: 53 additions & 34 deletions src/Application/Services/DomainService/ProfileService.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -20,56 +20,75 @@ public ProfileService(IUserManagerRepository userManagerRepository)

public async Task<Result<EditProfileInfoResponse>> EditProfileInfo(EditProfileInfoRequest infoRequest)
{
var user = await _userManagerRepository.FindByIdAsync(infoRequest.UserId);
if (user == null)
return Result<EditProfileInfoResponse>.Fail("User not found!");


if (user.UserName != infoRequest.UserName)
try
{
var existingUser = await _userManagerRepository.FindByNameAsync(infoRequest.UserName);
if (existingUser != null)
return Result<EditProfileInfoResponse>.Fail("Username is already reserved by another user!");
}
var user = await _userManagerRepository.FindByIdAsync(infoRequest.UserId);
if (user == null)
return Result<EditProfileInfoResponse>.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<EditProfileInfoResponse>.Fail(updateResult.Errors.FirstMessage());
if (user.UserName != infoRequest.UserName)
{
var existingUser = await _userManagerRepository.FindByNameAsync(infoRequest.UserName);
if (existingUser != null)
return Result<EditProfileInfoResponse>.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<EditProfileInfoResponse>.Fail(updateResult.Errors.FirstMessage());

return Result<EditProfileInfoResponse>.Ok(user.ToEditProfileInfoResponse());
return Result<EditProfileInfoResponse>.Ok(user.ToEditProfileInfoResponse());
}
catch (Exception ex)
{
return Result<EditProfileInfoResponse>.Fail($"An unexpected error occurred: {ex.Message}");
}
}

public async Task<Result<GetProfileInfoResponse>> GetProfileInfo(GetProfileInfoRequest getProfileInfoRequest)
{
var user = await _userManagerRepository.FindByIdAsync(getProfileInfoRequest.UserId);
try
{
var user = await _userManagerRepository.FindByIdAsync(getProfileInfoRequest.UserId);

if (user == null)
return Result<GetProfileInfoResponse>.Fail("User not found!");
if (user == null)
return Result<GetProfileInfoResponse>.Fail("User not found!");

var role = await _userManagerRepository.GetRoleAsync(user);
var role = await _userManagerRepository.GetRoleAsync(user);

return Result<GetProfileInfoResponse>.Ok(user.ToGetProfileInfoResponse(role));
return Result<GetProfileInfoResponse>.Ok(user.ToGetProfileInfoResponse(role));
}
catch (Exception ex)
{
return Result<GetProfileInfoResponse>.Fail($"An unexpected error occurred: {ex.Message}");
}
}

public async Task<Result> 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}");
}
}
}
139 changes: 83 additions & 56 deletions src/Application/Services/DomainService/UserService.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -26,86 +25,114 @@ public UserService(IUserManagerRepository userManagerRepository,
_tokenService = tokenService;
}

public async Task<Result<CreateUserResponse>> SignUpUser(CreateUserRequest createUserRequest)
public async Task<Result<CreateUserResponse>> SignUp(CreateUserRequest createUserRequest)
{
if (!await _roleManagerRepository.RoleExistsAsync(createUserRequest.Role))
try
{
return Result<CreateUserResponse>.Fail("role does not exist");
if (!await _roleManagerRepository.RoleExistsAsync(createUserRequest.Role))
{
return Result<CreateUserResponse>.Fail("Role does not exist.");
}

var appUser = createUserRequest.ToAppUser();

var appUserResult = await _userManagerRepository.CreateAsync(appUser, createUserRequest.Password);
if (!appUserResult.Succeeded)
{
return Result<CreateUserResponse>.Fail(appUserResult.Errors.FirstMessage());
}

var roleResult = await _userManagerRepository.SetRoleAsync(appUser, createUserRequest.Role);
if (!roleResult.Succeeded)
{
return Result<CreateUserResponse>.Fail(roleResult.Errors.FirstMessage());
}

return Result<CreateUserResponse>.Ok(appUser.ToCreateUserResponse(createUserRequest.Role));
}

var appUser = createUserRequest.ToAppUser();

var appUserResult = await _userManagerRepository.CreateAsync(appUser, createUserRequest.Password);
if (!appUserResult.Succeeded)
{
return Result<CreateUserResponse>.Fail(appUserResult.Errors.FirstMessage());
}

var roleResult = await _userManagerRepository.SetRoleAsync(appUser, createUserRequest.Role);
if (!roleResult.Succeeded)
catch (Exception ex)
{
return Result<CreateUserResponse>.Fail(roleResult.Errors.FirstMessage());
return Result<CreateUserResponse>.Fail($"An unexpected error occurred: {ex.Message}");
}

return Result<CreateUserResponse>.Ok(appUser.ToCreateUserResponse(createUserRequest.Role));
}

public async Task<Result<LoginUserResponse>> 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<LoginUserResponse>.Fail("You should enter email or username!");
}

if (appUser is null) return Result<LoginUserResponse>.Fail("Invalid username/email!");

var succeed = await _userManagerRepository.CheckPasswordAsync(appUser, loginUserRequest.Password);

if (!succeed) return Result<LoginUserResponse>.Fail("Username/Email not found and/or password incorrect");

var role = await _userManagerRepository.GetRoleAsync(appUser);
var token = _tokenService.GenerateToken(appUser, role);

return Result<LoginUserResponse>.Ok(appUser.ToLoginUserResponse(role, token));
}
else
catch (Exception ex)
{
return Result<LoginUserResponse>.Fail("You should enter email or username!");
return Result<LoginUserResponse>.Fail($"An unexpected error occurred: {ex.Message}");
}

if (appUser is null) return Result<LoginUserResponse>.Fail("Invalid username/email!");

var succeed = await _userManagerRepository.CheckPasswordAsync(appUser, loginUserRequest.Password);

if (!succeed) return Result<LoginUserResponse>.Fail("Username/Email not found and/or password incorrect");

var role = await _userManagerRepository.GetRoleAsync(appUser);
var token = _tokenService.GenerateToken(appUser, role);

return Result<LoginUserResponse>.Ok(appUser.ToLoginUserResponse(role, token));
}

public async Task<Result> 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<LoginUserResponse>.Fail("Invalid username");
if (appUser is null) return Result<LoginUserResponse>.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<List<GetUserResponse>> GetUsersAsync()
public async Task<Result<List<GetUserResponse>>> GetAllUsersAsync()
{
var users = await _userManagerRepository.GetUsersAsync();
var userWithRoles = new List<GetUserResponse>();
try
{
var users = await _userManagerRepository.GetUsersAsync();
var userWithRoles = new List<GetUserResponse>();

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<List<GetUserResponse>>.Ok(userWithRoles);
}
catch (Exception ex)
{
var role = await _userManagerRepository.GetRoleAsync(user);
var userResponse = user.ToGetUserResponse(role);
userWithRoles.Add(userResponse);
return Result<List<GetUserResponse>>.Fail($"An unexpected error occurred: {ex.Message}");
}

return userWithRoles;
}
}
Loading

0 comments on commit 0866bed

Please sign in to comment.