From b8f879c03aecd14fad0e5d4903fa20a566eb24ce Mon Sep 17 00:00:00 2001 From: urltapas Date: Sat, 20 Apr 2024 15:17:58 -0300 Subject: [PATCH] feat: awaitable endpoints --- .../Endpoints/AuthenticationEndpoint.cs | 4 +- src/HigiaServer.API/Endpoints/TaskEndpoint.cs | 70 ++++++++++++++----- src/HigiaServer.Domain/Entities/Task.cs | 2 +- 3 files changed, 54 insertions(+), 22 deletions(-) diff --git a/src/HigiaServer.API/Endpoints/AuthenticationEndpoint.cs b/src/HigiaServer.API/Endpoints/AuthenticationEndpoint.cs index c30ed5a..f3e433c 100644 --- a/src/HigiaServer.API/Endpoints/AuthenticationEndpoint.cs +++ b/src/HigiaServer.API/Endpoints/AuthenticationEndpoint.cs @@ -47,7 +47,7 @@ private static async Task HandleRegister( IJwtTokenService jwtTokenService ) { - if (repository.GetUserByEmail(request.Email) != null) throw new DuplicateEmailException(request.Email); + if (await repository.GetUserByEmail(request.Email) != null) throw new DuplicateEmailException(request.Email); request.Password = BCrypt.Net.BCrypt.HashPassword(request.Password); var user = mapper.Map(request); @@ -69,7 +69,7 @@ private static async Task HandleLogin( IJwtTokenService jwtTokenService ) { - if (repository.GetUserByEmail(request.Email) is not { } user) throw new EmailGivenNotFoundException(request.Email); + if (await repository.GetUserByEmail(request.Email) is not { } user) throw new EmailGivenNotFoundException(request.Email); if (!BCrypt.Net.BCrypt.Verify(request.Password, user.Password)) throw new InvalidPasswordException(); var authResponse = new AuthenticationResponse( diff --git a/src/HigiaServer.API/Endpoints/TaskEndpoint.cs b/src/HigiaServer.API/Endpoints/TaskEndpoint.cs index 1e01652..3991ad8 100644 --- a/src/HigiaServer.API/Endpoints/TaskEndpoint.cs +++ b/src/HigiaServer.API/Endpoints/TaskEndpoint.cs @@ -5,7 +5,7 @@ using HigiaServer.Application.Contracts.Responses; using HigiaServer.Application.Errors; using HigiaServer.Application.Repositories; -using Task = HigiaServer.Domain.Entities.Task; +using HigiaServer.Domain.Enums; namespace HigiaServer.API.Endpoints; @@ -13,8 +13,7 @@ public static class TaskEndpoint { public static IEndpointRouteBuilder AddTaskEndpoint(this IEndpointRouteBuilder app) { - var authEndpoint = app.MapGroup("higia-server/api/tasks") - .WithTags("Tasks"); + var authEndpoint = app.MapGroup("higia-server/api/tasks").WithTags("Tasks"); // add task authEndpoint.MapPost("/", HandleAddTask) @@ -25,9 +24,9 @@ public static IEndpointRouteBuilder AddTaskEndpoint(this IEndpointRouteBuilder a x.Summary = "Add Tasks"; return x; }); - + // get task by id - authEndpoint.MapGet("/{taskId}", GetTask) + authEndpoint.MapGet("/{taskId}", HandleGetTask) .WithName("Get task by id") .Produces() .WithOpenApi(x => @@ -36,47 +35,80 @@ public static IEndpointRouteBuilder AddTaskEndpoint(this IEndpointRouteBuilder a return x; }); + authEndpoint.MapPatch("/{taskId}/{status}", HandleUpdateTaskStatus) + .WithName("Update Task Status") + .WithOpenApi(x => + { + x.Summary = "Get task by id"; + return x; + }); + return app; } #region private methods - + + private static async Task HandleUpdateTaskStatus( + HttpContext context, + string taskId, + Status status, + ITaskRepository taskRepository + ) + { + CheckAuthorizationAsAdministrator(context); + if (!Guid.TryParse(taskId, out var id)) throw new NonGuidTypeException(taskId); + var task = await taskRepository.GetTaskById(id) ?? throw new TaskIdGivenNotFoundException(id.ToString()); + + task.UpdateTaskStatus(status); + taskRepository.UpdateTask(task); + + context.Response.Headers.Location = $"{context.Request.Scheme}://{context.Request.Host}/{context.Request.Path}/{task.Id}"; + return Results.Ok(); + } + private static async Task HandleAddTask( HttpContext context, AddTaskRequest request, IUserRepository userRepository, ITaskRepository taskRepository, - IMapper mapper) + IMapper mapper + ) { - if (!context.User!.Identity!.IsAuthenticated) throw new UnauthenticatedException(); - if (context.User.FindFirstValue(ClaimTypes.Role) == "collaborator") throw new UnauthorizedAccessException(); - var task = mapper.Map(request); - - var collaborators = request.CollaboratorsId - .Select(id => userRepository.GetUserById(id) ?? throw new CollaboratorIdNotFound(id.ToString())) + CheckAuthorizationAsAdministrator(context); + var task = mapper.Map(request); + + var collaborators = (await Task.WhenAll(request.CollaboratorsId + .Select(async id => await userRepository.GetUserById(id) ?? throw new CollaboratorIdNotFound(id.ToString())))) .ToList(); task.AddCollaboratorsToTask(collaborators); taskRepository.AddTask(task); var location = new Uri($"{context.Request.Scheme}://{context.Request.Host}/{context.Request.Path}/{task.Id}"); + var taskResponse = mapper.Map(task); return Results.Created(location, new StandardSuccessResponse(taskResponse, location)); } - private static async Task GetTask( + private static async Task HandleGetTask( HttpContext context, string taskId, ITaskRepository taskRepository, - IMapper mapper) + IMapper mapper + ) { if (!context.User!.Identity!.IsAuthenticated) throw new AuthenticationException(); if (!Guid.TryParse(taskId, out var id)) throw new NonGuidTypeException(taskId); - - var task = taskRepository.GetTaskById(id) ?? throw new TaskIdGivenNotFoundException(id.ToString()); + var task = await taskRepository.GetTaskById(id) ?? throw new TaskIdGivenNotFoundException(id.ToString()); + var taskResponse = mapper.Map(task); return Results.Ok(new StandardSuccessResponse(taskResponse)); } - + + private static void CheckAuthorizationAsAdministrator(HttpContext context) + { + if (!context.User!.Identity!.IsAuthenticated) throw new UnauthenticatedException(); + if (context.User.FindFirstValue(ClaimTypes.Role) != "admin") throw new UnauthorizedAccessException(); + } #endregion -} \ No newline at end of file +} diff --git a/src/HigiaServer.Domain/Entities/Task.cs b/src/HigiaServer.Domain/Entities/Task.cs index 93a38f7..d59410d 100644 --- a/src/HigiaServer.Domain/Entities/Task.cs +++ b/src/HigiaServer.Domain/Entities/Task.cs @@ -19,7 +19,7 @@ public class Task( public void AddCollaboratorToTask(User user) => Collaborators.Add(user); - public void AddCollaboratorsToTask(IEnumerable user) => Collaborators.AddRange(user); + public void AddCollaboratorsToTask(List user) => Collaborators.AddRange(user); public void UpdateTaskStatus(Status newStatus) => Status = newStatus; }