Skip to content

Commit

Permalink
add new exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
emrecoskun705 committed Sep 13, 2023
1 parent 3e6fc14 commit 94dd44b
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 30 deletions.
9 changes: 9 additions & 0 deletions Unitagram.Application/Exceptions/AccountLockoutException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Unitagram.Application.Exceptions;

public class AccountLockoutException : Exception
{
public AccountLockoutException(string message) : base(message)
{

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Unitagram.Application.Exceptions;

public class InvalidAccountCredentialsException : Exception
{
public InvalidAccountCredentialsException(string message) : base(message)
{

}
}
9 changes: 9 additions & 0 deletions Unitagram.Application/Exceptions/JwtTokenException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Unitagram.Application.Exceptions;

public class JwtTokenException : Exception
{
public JwtTokenException(string message) : base(message)
{

}
}
14 changes: 14 additions & 0 deletions Unitagram.Application/Exceptions/UserNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Unitagram.Application.Exceptions;

public class UserNotFoundException : Exception
{
public UserNotFoundException() : base("User not found")
{

}

public UserNotFoundException(string value) : base($"User ({value}) was not found")
{

}
}
40 changes: 20 additions & 20 deletions Unitagram.Identity/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task<Result<AuthResponse>> Login(AuthRequest request)

if (user == null)
{
var notFoundException = new NotFoundException("User", request.UserName);
var notFoundException = new UserNotFoundException(request.UserName);
return new Result<AuthResponse>(notFoundException);
}

Expand All @@ -71,15 +71,13 @@ public async Task<Result<AuthResponse>> Login(AuthRequest request)
var lockoutEndDate = await _userManager.GetLockoutEndDateAsync(user);
if (lockoutEndDate >= DateTimeOffset.UtcNow)
{
var lockoutException = new BadRequestException($"Account locked out. Try again later.");
var lockoutException = new AccountLockoutException("Account locked out. Try again later.");
return new Result<AuthResponse>(lockoutException);
}
else
{
// If lockout has expired, reset the AccessFailedCount and LockoutEnd
await _userManager.ResetAccessFailedCountAsync(user);
await _userManager.SetLockoutEndDateAsync(user, null); // Reset lockout end date
}

// If lockout has expired, reset the AccessFailedCount and LockoutEnd
await _userManager.ResetAccessFailedCountAsync(user);
await _userManager.SetLockoutEndDateAsync(user, null); // Reset lockout end date
}

var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
Expand All @@ -92,11 +90,11 @@ public async Task<Result<AuthResponse>> Login(AuthRequest request)
{
await _userManager.SetLockoutEndDateAsync(user,
DateTimeOffset.UtcNow.Add(_userManager.Options.Lockout.DefaultLockoutTimeSpan));
var lockoutException = new BadRequestException($"Account locked out. Try again later.");
var lockoutException = new AccountLockoutException("Account locked out. Try again later.");
return new Result<AuthResponse>(lockoutException);
}

var badRequestException = new BadRequestException($"Credentials for '{request.UserName} aren't valid'.");
var badRequestException = new InvalidAccountCredentialsException($"Credentials for '{request.UserName} aren't valid'.");
return new Result<AuthResponse>(badRequestException);
}

Expand Down Expand Up @@ -146,15 +144,17 @@ public async Task<Result<RegisterResponse>> Register(RegisterRequest request)
if (!result.Succeeded)
{
string errorMessage = string.Join("|", result.Errors.Select(e => e.Description));
var exception = new BadRequestException(errorMessage);
var exception = new ValidationException(errorMessage);
return new Result<RegisterResponse>(exception);
}

// Add the user to the "UniversityUser" role
await AddRoleToUserAsync(user, "UniversityUser");


try
{
// Add the user to the "UniversityUser" role
await AddRoleToUserAsync(user, "UniversityUser");

await _universityUserRepository.CreateAsync(new UniversityUser()
{
UserId = user.Id,
Expand Down Expand Up @@ -191,14 +191,14 @@ public async Task<Result<EmailVerificationResponse>> ConfirmEmail(EmailVerificat

if (username == null)
{
var exception = new NotFoundException("Username", "token");
var exception = new UserNotFoundException("token");
return new Result<EmailVerificationResponse>(exception);
}

var user = await _userManager.FindByNameAsync(username);
if (user == null)
{
var exception = new NotFoundException("User", username);
var exception = new UserNotFoundException();
return new Result<EmailVerificationResponse>(exception);
}

Expand All @@ -219,14 +219,14 @@ public async Task<Result<GenerateOtpResponse>> GenerateOtpEmail(GenerateOtpReque

if (username == null)
{
var exception = new NotFoundException("Username", "token");
var exception = new UserNotFoundException("token");
return new Result<GenerateOtpResponse>(exception);
}

var user = await _userManager.FindByNameAsync(username);
if (user == null)
{
var exception = new NotFoundException("User", username);
var exception = new UserNotFoundException(username);
return new Result<GenerateOtpResponse>(exception);
}

Expand Down Expand Up @@ -262,23 +262,23 @@ public async Task<Result<AuthResponse>> RefreshToken(RefreshRequest request)
string? username = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (username == null)
{
var exception = new BadRequestException("Invalid access token");
var exception = new JwtTokenException("Invalid access token");
return new Result<AuthResponse>(exception);
}

ApplicationUser? user = await _userManager.FindByNameAsync(username);

if (user is null)
{
var exception = new NotFoundException("User", username);
var exception = new UserNotFoundException(username);
return new Result<AuthResponse>(exception);
}

bool isValidRefreshToken = user.RefreshToken != request.RefreshToken ||
user.RefreshTokenExpirationDateTime <= DateTime.Now;
if (isValidRefreshToken)
{
var exception = new BadRequestException("Invalid refresh token");
var exception = new JwtTokenException("Invalid refresh token");
return new Result<AuthResponse>(exception);
}

Expand Down
17 changes: 7 additions & 10 deletions Unitagram.WebAPI/Controllers/ControllerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ private static ActionResult<TResult> HandleException<TResult>(Exception exceptio
// Define a dictionary to map exception types to status codes
var statusCodeMap = new Dictionary<Type, int>
{
{ typeof(ValidationException), 400 },
{ typeof(BadRequestException), 400 },
{ typeof(NotFoundException), 404 }
{ typeof(ValidationException), StatusCodes.Status400BadRequest },
{ typeof(BadRequestException), StatusCodes.Status400BadRequest },
{ typeof(InvalidAccountCredentialsException), StatusCodes.Status400BadRequest },
{ typeof(AccountLockoutException), StatusCodes.Status403Forbidden },
{ typeof(NotFoundException), StatusCodes.Status404NotFound },
{ typeof(UserNotFoundException), StatusCodes.Status404NotFound }
};

// Get the status code from the dictionary, defaulting to 500 if not found
Expand All @@ -48,12 +51,6 @@ private static ActionResult<TResult> HandleException<TResult>(Exception exceptio
Instance = requestUrl
};

// Use a single switch statement to determine the result
return exception switch
{
ValidationException or BadRequestException => new BadRequestObjectResult(problemDetails),
NotFoundException => new NotFoundObjectResult(problemDetails),
_ => new StatusCodeResult(statusCode)
};
return new ObjectResult(problemDetails);
}
}

0 comments on commit 94dd44b

Please sign in to comment.