Skip to content

Commit

Permalink
feat: configuration fluent validation
Browse files Browse the repository at this point in the history
  • Loading branch information
migueloliveiradev committed Feb 4, 2024
1 parent 2b9ccad commit d4f809b
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 82 deletions.
15 changes: 14 additions & 1 deletion Living.Application/UseCases/Users/Login/LoginUserCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Http;
using FluentValidation;
using Microsoft.AspNetCore.Http;

namespace Living.Application.UseCases.Users.Login;
public class LoginUserCommand : IRequest<IResult>
Expand All @@ -8,3 +9,15 @@ public class LoginUserCommand : IRequest<IResult>

public bool UseCookies { get; set; } = true;
}

public class LoginCommandValidator : AbstractValidator<LoginUserCommand>
{
public LoginCommandValidator()
{
RuleFor(x => x.Email)
.NotEmpty().WithErrorCode("IS_REQUIRED")
.EmailAddress().WithErrorCode("IS_EMAIL");
RuleFor(x => x.Password)
.NotEmpty().WithErrorCode("IS_REQUIRED");
}
}
4 changes: 2 additions & 2 deletions Living.Application/UseCases/Users/Login/LoginUserHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ public async Task<IResult> Handle(LoginUserCommand request, CancellationToken ca
var user = await userManager.FindByEmailAsync(request.Email);

if (user is null)
return Results.NotFound(new BaseResponse(UserErrors.USER_NOT_FOUND));
return Results.NotFound(new BaseResponse(UserErrors.NOT_FOUND));

var passwordIsValid = await userManager.CheckPasswordAsync(user, request.Password);
if (!passwordIsValid)
return Results.BadRequest(new BaseResponse(UserErrors.USER_PASSWORD_INVALID));
return Results.BadRequest(new BaseResponse(UserErrors.PASSWORD_INVALID));

var authenticationScheme = request.UseCookies ? IdentityConstants.ApplicationScheme : BearerTokenDefaults.AuthenticationScheme;

Expand Down
71 changes: 0 additions & 71 deletions Living.Domain/Base/StatusCodes.cs

This file was deleted.

8 changes: 4 additions & 4 deletions Living.Domain/Entities/Users/Constants/UserErrors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
namespace Living.Domain.Entities.Users.Constants;
public class UserErrors
{
public static Notification USER_NOT_FOUND => new("USER", nameof(USER_NOT_FOUND));
public static Notification USER_PASSWORD_INVALID => new("USER", nameof(USER_NOT_FOUND));
public static Notification USER_EMAIL_ALREADY_IN_USE => new("USER", nameof(USER_NOT_FOUND));
public static Notification USER_USERNAME_ALREADY_IN_USE => new("USER", nameof(USER_NOT_FOUND));
public static Notification NOT_FOUND => new("USER", nameof(NOT_FOUND));
public static Notification PASSWORD_INVALID => new("USER", nameof(NOT_FOUND));
public static Notification EMAIL_ALREADY_IN_USE => new("USER", nameof(NOT_FOUND));
public static Notification USERNAME_ALREADY_IN_USE => new("USER", nameof(NOT_FOUND));
}
4 changes: 2 additions & 2 deletions Living.WebAPI/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ namespace Living.WebAPI.Controllers;
public class AuthController(IMediator mediator) : ControllerBase
{
[HttpPost("register")]
public async Task<IResult> Register(RegisterUserCommand command)
public async Task<IResult> Register([FromBody] RegisterUserCommand command)
{
return await mediator.Send(command);
}

[HttpPost("login")]
public async Task<IResult> Login(LoginUserCommand command)
public async Task<IResult> Login([FromBody] LoginUserCommand command)
{
return await mediator.Send(command);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using FluentValidation;
using Living.Domain.Base;
using Microsoft.AspNetCore.Diagnostics;

namespace Living.WebAPI.ExceptionsHandler;

public class FluentValidationExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
if (exception is ValidationException validation)
{
var notifications = validation.Errors.Select(e => new Notification(e.PropertyName.ToUpper(), e.ErrorCode));

httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
await httpContext.Response.WriteAsJsonAsync(new BaseResponse(notifications.DistinctBy(p => p.Code)), cancellationToken);

return true;
}

return false;
}
}
22 changes: 20 additions & 2 deletions Living.WebAPI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
using Microsoft.AspNetCore.Identity;
using Living.Infraestructure.Context;
using Living.Infraestructure.Context.Interceptors;
using Living.Application.UseCases.Users.Login;
using MediatR.Extensions.FluentValidation.AspNetCore;
using Living.WebAPI.ExceptionsHandler;

namespace Living.WebAPI;
public class Program
Expand All @@ -19,7 +22,8 @@ public static void Main(string[] args)
builder.Services.AddDbContext<DatabaseContext>(options =>
{
options.AddInterceptors(new TimestampsInterceptor());
options.UseNpgsql(builder.Configuration["PostgresConnection"]);
//options.UseNpgsql(builder.Configuration["PostgresConnection"]);
options.UseInMemoryDatabase("Living");
});

builder.Services.AddControllers();
Expand All @@ -39,7 +43,12 @@ public static void Main(string[] args)

builder.Services.AddAutoMapper(typeof(BaseProfile));

builder.Services.AddValidatorsFromAssemblyContaining<CreatePostValidator>();
builder.Services.AddValidatorsFromAssemblyContaining<LoginUserCommand>();

builder.Services.AddFluentValidation([typeof(LoginUserCommand).Assembly]);

builder.Services.AddExceptionHandler<FluentValidationExceptionHandler>();
builder.Services.AddProblemDetails();

builder.Services.AddMediatR(configuration =>
{
Expand All @@ -49,6 +58,11 @@ public static void Main(string[] args)
builder.Services.AddAuthentication().AddBearerToken();
builder.Services.AddAuthorization();

builder.Services.AddCors(options => options.AddDefaultPolicy(
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()));

var app = builder.Build();

if (app.Environment.IsDevelopment())
Expand All @@ -59,6 +73,10 @@ public static void Main(string[] args)

app.UseAuthentication();

app.UseCors();

app.UseExceptionHandler();

app.UseHttpsRedirection();

app.UseAuthorization();
Expand Down

0 comments on commit d4f809b

Please sign in to comment.