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

refact backend #6

Merged
merged 13 commits into from
Feb 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_namespace_declarations = file_scoped:silent
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_extended_property_pattern = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
csharp_style_var_elsewhere = true:silent

[*.vb]
#### Estilos de nomenclatura ####
Expand Down
56 changes: 56 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Workflow responsible for validating the project's build, tests and code coverage when creating a pull request

name: 'Checks'

on:
pull_request:

permissions:
contents: read
pull-requests: write

jobs:
checks:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x

- name: Restore dependencies
run: dotnet restore

- name: Build
run: dotnet build --no-restore

- name: Install EF Core CLI
run: dotnet tool install --global dotnet-ef

- name: Check has pending model changes
run: dotnet ef migrations has-pending-model-changes -p Living.Infraestructure -s Living.WebAPI

- name: Tests
run: dotnet test --configuration Release --logger GitHubActions /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=../coverage/ /p:ExcludeByFile="**/*Migrations/*.cs"

- name: Code Coverage Report
uses: irongut/[email protected]
with:
filename: coverage/**/coverage.cobertura.xml
badge: true
fail_below_min: false # throws failure if code coverage does not reach the configured thresholds
format: markdown
hide_branch_rate: false
hide_complexity: true
indicators: true
output: both
thresholds: '80 40'

- name: Add Coverage PR Comment
uses: marocchino/sticky-pull-request-comment@v2
with:
recreate: true
path: code-coverage-results.md
9 changes: 7 additions & 2 deletions Living.Application/Living.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MediatR" Version="12.1.1" />
<PackageReference Include="MediatR.Extensions.FluentValidation.AspNetCore" Version="5.0.0" />
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="MediatR.Extensions.FluentValidation.AspNetCore" Version="5.1.0" />
</ItemGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<Folder Include="UseCases\Posts\Comment\" />
<Folder Include="UseCases\Posts\Like\" />
Expand Down
6 changes: 6 additions & 0 deletions Living.Application/Mapping/BaseProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
using AutoMapper;

namespace Living.Application.Mapping;
public class BaseProfile : Profile
{
}
11 changes: 11 additions & 0 deletions Living.Application/Mapping/Users/UserProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Living.Application.UseCases.Users.Register;
using Living.Domain.Entities.Users;

namespace Living.Application.Mapping.Users;
public class UserProfile : BaseProfile
{
public UserProfile()
{
CreateMap<RegisterUserCommand, User>();
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
using Living.Domain.Entity.Posts;
using Living.Domain.Entities.Posts;

namespace Living.Application.UseCases.Posts.Create;
public class CreatePostCommand : IRequest<BaseResponse<Guid>>
{
public string Content { get; set; }
public PostAccess Access { get; set; }

#warning add upload attachments
}
23 changes: 23 additions & 0 deletions Living.Application/UseCases/Users/Login/LoginUserCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using FluentValidation;
using Microsoft.AspNetCore.Http;

namespace Living.Application.UseCases.Users.Login;
public class LoginUserCommand : IRequest<IResult>
{
public string Email { get; set; } = null!;
public string Password { get; set; } = null!;

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");
}
}
34 changes: 34 additions & 0 deletions Living.Application/UseCases/Users/Login/LoginUserHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Living.Domain.Entities.Users;
using Living.Domain.Entities.Users.Constants;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace Living.Application.UseCases.Users.Login;
public class LoginUserHandler(UserManager<User> userManager) : IRequestHandler<LoginUserCommand, IResult>
{
public async Task<IResult> Handle(LoginUserCommand request, CancellationToken cancellationToken)
{
var user = await userManager.FindByEmailAsync(request.Email);

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

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

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

var identity = new ClaimsIdentity(GetClaims(user), authenticationScheme);
var principal = new ClaimsPrincipal(identity);

return TypedResults.SignIn(principal, null, authenticationScheme);
}

private List<Claim> GetClaims(User user)
{
return [new(UserClaimsTypes.USER_ID, user.Id.ToString())];
}
}
10 changes: 10 additions & 0 deletions Living.Application/UseCases/Users/Register/RegisterUserCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Http;

namespace Living.Application.UseCases.Users.Register;
public class RegisterUserCommand : IRequest<IResult>
{
public string Name { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
20 changes: 20 additions & 0 deletions Living.Application/UseCases/Users/Register/RegisterUserHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using AutoMapper;
using Living.Domain.Entities.Users;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;

namespace Living.Application.UseCases.Users.Register;
public class RegisterUserHandler(IMapper mapper, UserManager<User> userManager) : IRequestHandler<RegisterUserCommand, IResult>
{
public async Task<IResult> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
{
var user = mapper.Map<User>(request);

var result = await userManager.CreateAsync(user, request.Password);

if (!result.Succeeded)
return Results.BadRequest(new BaseResponse(result.Errors));

return Results.Ok(new BaseResponse());
}
}
28 changes: 0 additions & 28 deletions Living.Application/Validation/ValidationBehavior.cs

This file was deleted.

55 changes: 40 additions & 15 deletions Living.Domain/Base/BaseResponse.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,59 @@
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Identity;

namespace Living.Domain.Base;
public class BaseResponse<T> : IBaseResponse
public class BaseResponse<T> : BaseResponse
{
public BaseResponse(T data, StatusCodes statusCode)
public BaseResponse(T data)
{
StatusCode = statusCode;
Data = data;
}

public BaseResponse(T data)
public BaseResponse(Notification notification) : base(notification)
{
StatusCode = StatusCodes.OK;
Data = data;
}

public BaseResponse(Dictionary<string, string> erros)
public BaseResponse(IEnumerable<Notification> notifications) : base(notifications)
{
StatusCode = StatusCodes.UnprocessableEntity;
Erros = erros;
}


public BaseResponse()
public BaseResponse(IEnumerable<IdentityError> errors) : base(errors)
{
}

public StatusCodes StatusCode { get; set; }
public T? Data { get; set; }
}

public class BaseResponse
{
public BaseResponse()
{
}

public BaseResponse(Notification notification)
{
Notifications.TryAdd(notification.Key, []);
Notifications[notification.Key] = [..Notifications[notification.Key], notification.Code];
}

public BaseResponse(IEnumerable<Notification> notifications)
{
foreach (var notification in notifications)
{
Notifications.TryAdd(notification.Key, []);
Notifications[notification.Key] = [..Notifications[notification.Key], notification.Code];
}
}

public BaseResponse(IEnumerable<IdentityError> errors)
{
foreach (var error in errors)
{
Notifications.TryAdd("IDENTITY", []);
Notifications["IDENTITY"] = [..Notifications["IDENTITY"], error.Code];
}
}

public bool HasNotifications => Notifications.Count > 0;

[JsonInclude]
public Dictionary<string, string> Erros = new();
public Dictionary<string, string[]> Notifications { get; set; } = [];
}
5 changes: 0 additions & 5 deletions Living.Domain/Base/IBaseResponse.cs

This file was deleted.

2 changes: 1 addition & 1 deletion Living.Domain/Base/Interfaces/IEntity.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
namespace Living.Domain.Base.Interfaces;
public interface IEntity
{
Guid Id { get; init; }
Guid Id { get; }
}
2 changes: 1 addition & 1 deletion Living.Domain/Base/Interfaces/ITimestamp.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
namespace Living.Domain.Base.Interfaces;
internal interface ITimestamp
public interface ITimestamp
{
DateTime CreatedAt { get; set; }
}
7 changes: 3 additions & 4 deletions Living.Domain/Base/Interfaces/ITimestamps.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
namespace Living.Domain.Base.Interfaces;
public interface ITimestamps
public interface ITimestamps : ITimestamp
{
DateTime CreatedAt { get; }
DateTime? LastUpdatedAt { get; }
DateTime? DeletedAt { get; set; }
DateTime LastUpdatedAt { get; set; }

}
11 changes: 11 additions & 0 deletions Living.Domain/Base/Notification.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Living.Domain.Base;
public class Notification(string key, string code)
{
public string Key { get; set; } = key;
public string Code { get; set; } = code;

public override string ToString()
{
return $"{Key}: {Code}";
}
}
Loading
Loading