Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move user repo logic to service and handle errors #25

Merged
merged 13 commits into from
Mar 20, 2024
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using DotnetFoundation.Api.Helpers;
using DotnetFoundation.Application.Exceptions;
using DotnetFoundation.Application.Interfaces.Services;
using DotnetFoundation.Application.Interfaces.Validator;
using DotnetFoundation.Application.Models.Common;
using DotnetFoundation.Application.Models.DTOs.AuthenticationDTO;
using DotnetFoundation.Application.Models.Enums;
Expand All @@ -8,12 +11,14 @@ namespace DotnetFoundation.Api.Controllers;

[ApiController]
[Route("/api/auth")]
public class AuthenticationController : ControllerBase
public class AuthenticationController : BaseController
{
private readonly IAuthenticationService _authenticationService;
public AuthenticationController(IAuthenticationService authenticationService)
private readonly IUserValidator _userValidator;
public AuthenticationController(IAuthenticationService authenticationService, IUserValidator userValidator)
{
_authenticationService = authenticationService;
_userValidator = userValidator;
}

/// <summary>
Expand All @@ -27,11 +32,33 @@ public AuthenticationController(IAuthenticationService authenticationService)
public async Task<ActionResult<BaseResponse<AuthenticationResponse>>> RegisterAsync(RegisterRequest request)
{
BaseResponse<AuthenticationResponse> response = new(ResponseStatus.Fail);
try
{
bool isRegisteredEmail = await _userValidator.IsEmailRegistered(request.Email).ConfigureAwait(false);
if (isRegisteredEmail)
{
ModelState.AddModelError("email", "Email already in use");
throw new IdentityUserException(ErrorValues.GenricValidationMessage);
}
response.Data = await _authenticationService.RegisterAsync(request).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

response.Data = await _authenticationService.RegisterAsync(request).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

return Ok(response);
return Ok(response);
}
catch (IdentityUserException ex)
{
response.Message = ex.Message;
Harish-osmosys marked this conversation as resolved.
Show resolved Hide resolved
response.Status = ResponseStatus.Error;
response.Errors = GetErrorResponse();
return BadRequest(response);
}
catch (Exception ex)
{
response.Message = ex.Message;
response.Errors = GetErrorResponse();
response.Status = ResponseStatus.Error;
return StatusCode(StatusCodes.Status500InternalServerError, response);
}
}

/// <summary>
Expand All @@ -45,46 +72,113 @@ public async Task<ActionResult<BaseResponse<AuthenticationResponse>>> RegisterAs
public async Task<ActionResult<BaseResponse<AuthenticationResponse>>> LoginAsync(LoginRequest request)
{
BaseResponse<AuthenticationResponse> response = new(ResponseStatus.Fail);
try
{
response.Data = await _authenticationService.LoginAsync(request).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

response.Data = await _authenticationService.LoginAsync(request).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

return Ok(response);
return Ok(response);
}
catch (InvalidCredentialsException ex)
{
response.Message = ex.Message;
response.Status = ResponseStatus.Error;
response.Errors = GetErrorResponse();
return BadRequest(response);
}
catch (Exception ex)
{
response.Message = ex.Message;
response.Errors = GetErrorResponse();
response.Status = ResponseStatus.Error;
return StatusCode(StatusCodes.Status500InternalServerError, response);
}
}

/// <summary>
/// User password reset using reset token.
/// </summary>
/// <param name="request">New password details request</param>
[HttpPost("reset-password")]
[HttpPost("resetpassword")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<BaseResponse<AuthenticationResponse>>> ResetPasswordAsync(PasswordResetRequest request)
public async Task<ActionResult<BaseResponse<int>>> ResetPasswordAsync(PasswordResetRequest request)
{
BaseResponse<AuthenticationResponse> response = new(ResponseStatus.Fail);
BaseResponse<int> response = new(ResponseStatus.Fail);
try
{
bool isValidEmail = await _userValidator.ValidEmailId(request.Email).ConfigureAwait(false);
if (!isValidEmail)
{
ModelState.AddModelError("email", "Error Finding User");
throw new UserNotFoundException(ErrorValues.GenricNotFoundMessage);
}
await _authenticationService.ResetPasswordAsync(request).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

response.Data = await _authenticationService.ResetPasswordAsync(request).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

return Ok(response);
return Ok(response);
}
catch (UserNotFoundException ex)
{
response.Message = ex.Message;
response.Status = ResponseStatus.Error;
response.Errors = GetErrorResponse();
return BadRequest(response);
}
catch (InvalidTokenException ex)
{
response.Message = ex.Message;
response.Status = ResponseStatus.Error;
response.Errors = GetErrorResponse();
return BadRequest(response);
}
catch (Exception ex)
{
response.Message = ex.Message;
response.Errors = GetErrorResponse();
response.Status = ResponseStatus.Error;
return StatusCode(StatusCodes.Status500InternalServerError, response);
}
}

/// <summary>
/// Forgot user password.
/// </summary>
/// <param name="email">Email of user to reset password</param>
[HttpPost("forgot-password")]
[HttpPost("forgotpassword")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<BaseResponse<string>>> ForgotPasswordAsync(string email)
public async Task<ActionResult<BaseResponse<int>>> ForgotPasswordAsync(string email)
{
BaseResponse<string> response = new(ResponseStatus.Fail);

response.Data = await _authenticationService.ForgotPasswordAsync(email).ConfigureAwait(false);
response.Status = ResponseStatus.Success;
BaseResponse<int> response = new(ResponseStatus.Fail);
try
{
bool isValidEmail = await _userValidator.ValidEmailId(email).ConfigureAwait(false);
if (!isValidEmail)
{
ModelState.AddModelError("email", "Error Finding User");
throw new UserNotFoundException(ErrorValues.GenricNotFoundMessage);
}
await _authenticationService.ForgotPasswordAsync(email).ConfigureAwait(false);
response.Status = ResponseStatus.Success;

return Ok(response);
return Ok(response);
}
catch (UserNotFoundException ex)
{
response.Message = ex.Message;
response.Status = ResponseStatus.Error;
response.Errors = GetErrorResponse();
return BadRequest(response);
}
catch (Exception ex)
{
response.Message = ex.Message;
response.Status = ResponseStatus.Error;
response.Errors = GetErrorResponse();
return StatusCode(StatusCodes.Status500InternalServerError, response);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DotnetFoundation.Api.Controllers;

public class BaseController : ControllerBase
{
protected Dictionary<string, List<string>> GetErrorResponse()
{
return ModelState
.Where(modelError => modelError.Value!.Errors.Any())
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value!.Errors.Select(error => error.ErrorMessage).ToList()
);
}
}
Loading
Loading