Skip to content

Commit

Permalink
Merge pull request #339 from raffacabofrio/master
Browse files Browse the repository at this point in the history
Publicando .net core 3.1 em produção.
  • Loading branch information
raffacabofrio committed Apr 27, 2020
2 parents 29dd996 + 042bb26 commit 48d51e5
Show file tree
Hide file tree
Showing 42 changed files with 521 additions and 385 deletions.
15 changes: 0 additions & 15 deletions ShareBook/ShareBook.Api/AutoMapper/AutoMapperConfig.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ namespace ShareBook.Api.AutoMapper
{
public class DomainToViewModelMappingProfile : Profile
{
public DomainToViewModelMappingProfile() : this("Profile") { }
public DomainToViewModelMappingProfile() : this("Profile")
{
}

protected DomainToViewModelMappingProfile(string profileName) : base(profileName)
{
#region [ Book ]

CreateMap<Book, BooksVM>()
.ForMember(dest => dest.Donor, opt => opt.MapFrom(src => src.User.Name))
.ForMember(dest => dest.Facilitator, opt => opt.MapFrom(src => src.UserFacilitator.Name))
Expand All @@ -31,25 +34,32 @@ protected DomainToViewModelMappingProfile(string profileName) : base(profileName
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Book.Title))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status.Description()))
.ForMember(dest => dest.RequestId, opt => opt.MapFrom(src => src.Id));
#endregion

#endregion [ Book ]

#region [ User ]

CreateMap<User, UserVM>()
.ForMember(dest => dest.Address, opt => opt.MapFrom(src => src.Address));
#endregion

CreateMap<User, UserFacilitatorVM>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name));

#endregion [ User ]

#region [ BookUser ]

CreateMap<BookUser, RequestersListVM>()
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId))
.ForMember(dest => dest.RequesterNickName, opt => opt.MapFrom(src => src.NickName))
.ForMember(dest => dest.Location, opt => opt.MapFrom(src => src.User.Location()))
.ForMember(dest => dest.TotalBooksWon, opt => opt.MapFrom(src => src.User.TotalBooksWon()))
.ForMember(dest => dest.Location, opt => opt.MapFrom(src => src.User.Location()))
.ForMember(dest => dest.TotalBooksWon, opt => opt.MapFrom(src => src.User.TotalBooksWon()))
.ForMember(dest => dest.TotalBooksDonated, opt => opt.MapFrom(src => src.User.TotalBooksDonated()))
.ForMember(dest => dest.RequestText, opt => opt.MapFrom(src => src.Reason))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status));
.ForMember(dest => dest.RequestText, opt => opt.MapFrom(src => src.Reason))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status));

#endregion
#endregion [ BookUser ]
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,23 @@ namespace ShareBook.Api.AutoMapper
{
public class ViewModelToDomainMappingProfile : Profile
{
public ViewModelToDomainMappingProfile() : this("Profile") { }
public ViewModelToDomainMappingProfile() : this("Profile")
{
}

protected ViewModelToDomainMappingProfile(string profileName) : base(profileName)
{
#region [ Book ]

CreateMap<CreateBookVM, Book>().ReverseMap();
CreateMap<UpdateBookVM, Book>().ReverseMap();
CreateMap<DonateBookUserVM, BookUser>().ReverseMap();
#endregion

#endregion [ Book ]

#region [ User ]
CreateMap<LoginUserVM, User>();

CreateMap<LoginUserVM, User>();
CreateMap<RegisterUserVM, User>()
.ForPath(dest => dest.Address.Street, opt => opt.MapFrom(src => src.Street))
.ForPath(dest => dest.Address.Number, opt => opt.MapFrom(src => src.Number))
Expand All @@ -28,17 +32,21 @@ protected ViewModelToDomainMappingProfile(string profileName) : base(profileName
.ForPath(dest => dest.Address.Neighborhood, opt => opt.MapFrom(src => src.Neighborhood))
.ForPath(dest => dest.Address.Country, opt => opt.MapFrom(src => src.Country))
.ForPath(dest => dest.Address.Complement, opt => opt.MapFrom(src => src.Complement));

CreateMap<UpdateUserVM, User>();
#endregion

#endregion [ User ]

#region [ ContactUs ]

CreateMap<ContactUsVM, ContactUs>();
#endregion

#endregion [ ContactUs ]

#region [ Notification ]

CreateMap<NotificationOnesignalVM, NotificationOnesignal>();
#endregion

#endregion [ Notification ]
}
}
}
}
14 changes: 4 additions & 10 deletions ShareBook/ShareBook.Api/Configuration/JWTConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ namespace ShareBook.Api.Configuration
{
public static class JWTConfig
{

public static void RegisterJWT(IServiceCollection services, IConfiguration configuration)
{
var tokenConfigurations = ConfigureToken(services, configuration);
var signingConfigurations = ConfigureSigning(services);
ConfigureAuth(services, signingConfigurations, tokenConfigurations);

}

private static TokenConfigurations ConfigureToken(IServiceCollection services, IConfiguration configuration)
Expand Down Expand Up @@ -49,7 +47,6 @@ private static void ConfigureAuth(IServiceCollection services, SigningConfigurat
var paramsValidation = bearerOptions.TokenValidationParameters;
paramsValidation.IssuerSigningKey = signingConfigurations.Key;
// Valida a assinatura de um token recebido
paramsValidation.ValidateIssuerSigningKey = true;
Expand All @@ -59,21 +56,18 @@ private static void ConfigureAuth(IServiceCollection services, SigningConfigurat
// Verifica se um token recebido ainda é válido
paramsValidation.ValidateLifetime = true;
// Tempo de tolerância para a expiração de um token (utilizado
// caso haja problemas de sincronismo de horário entre diferentes
// computadores envolvidos no processo de comunicação)
// Tempo de tolerância para a expiração de um token (utilizado caso haja problemas
// de sincronismo de horário entre diferentes computadores envolvidos no processo de comunicação)
paramsValidation.ClockSkew = TimeSpan.Zero;
});

// Ativa o uso do token como forma de autorizar o acesso
// a recursos deste projeto
// Ativa o uso do token como forma de autorizar o acesso a recursos deste projeto
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
.RequireAuthenticatedUser().Build());
});

}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ public static IServiceCollection RegisterRepositoryServices(
//Auth
services.AddScoped<IApplicationSignInManager, ApplicationSignInManager>();

//Email
//Email
services.AddScoped<IEmailService, EmailService>();
services.AddSingleton<IEmailTemplate, EmailTemplate>();

//Upload
//Upload
services.AddScoped<IUploadService, UploadService>();

//UnitOfWork
Expand All @@ -70,4 +70,4 @@ public static IServiceCollection RegisterRepositoryServices(
return services;
}
}
}
}
59 changes: 59 additions & 0 deletions ShareBook/ShareBook.Api/Configuration/SwaggerConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Linq;

namespace ShareBook.Api.Configuration
{
public static class SwaggerConfiguration
{
public static IServiceCollection RegisterSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(swagger =>
{
swagger.SwaggerDoc("v1", new OpenApiInfo
{
Title = "SHAREBOOK API",
Version = "v1",
Description = "Open Source project",
Contact = new OpenApiContact
{
Name = "",
Email = "",
},
License = new OpenApiLicense
{
Name = "MIT License",
Url = new Uri("https://opensource.org/licenses/MIT")
}
});
swagger.ResolveConflictingActions(x => x.First());
swagger.AddSecurityDefinition("Bearer",
new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
}
);
swagger.AddSecurityRequirement(
new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
}
);
});
return services;
}
}
}
37 changes: 24 additions & 13 deletions ShareBook/ShareBook.Api/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,31 @@ namespace ShareBook.Api.Controllers
[Route("api/[controller]")]
[EnableCors("AllowAllHeaders")]
[GetClaimsFilter]
public class AccountController : Controller
public class AccountController : ControllerBase
{
private readonly IUserService _userService;
private readonly IApplicationSignInManager _signManager;
private readonly IMapper _mapper;

public AccountController(IUserService userService, IApplicationSignInManager signManager)
public AccountController(IUserService userService,
IApplicationSignInManager signManager,
IMapper mapper)
{
_userService = userService;
_signManager = signManager;
_mapper = mapper;
}

#region GET
[Authorize("Bearer")]

[HttpGet]
[Authorize("Bearer")]
public UserVM Get()
{
var id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
var user = _userService.Find(id);

var userVM = Mapper.Map<User, UserVM>(user);
var userVM = _mapper.Map<UserVM>(user);
return userVM;
}

Expand All @@ -54,12 +59,16 @@ public object Profile()
public IActionResult ListFacilitators(Guid userIdDonator)
{
var facilitators = _userService.GetFacilitators(userIdDonator);
var facilitatorsClean = Mapper.Map<List<UserFacilitatorVM>>(facilitators);

var facilitatorsClean = _mapper.Map<List<UserFacilitatorVM>>(facilitators);

return Ok(facilitatorsClean);
}
#endregion

#endregion GET

#region POST

[HttpPost("Register")]
[ProducesResponseType(typeof(object), 200)]
[ProducesResponseType(409)]
Expand All @@ -68,7 +77,7 @@ public IActionResult Post([FromBody] RegisterUserVM registerUserVM, [FromService
if (!ModelState.IsValid)
return BadRequest();

var user = Mapper.Map<RegisterUserVM, User>(registerUserVM);
var user = _mapper.Map<User>(registerUserVM);

var result = _userService.Insert(user);

Expand All @@ -86,7 +95,7 @@ public IActionResult Login([FromBody] LoginUserVM loginUserVM, [FromServices] Si
if (!ModelState.IsValid)
return BadRequest();

var user = Mapper.Map<LoginUserVM, User>(loginUserVM);
var user = _mapper.Map<User>(loginUserVM);

var result = _userService.AuthenticationByEmailAndPassword(user);

Expand Down Expand Up @@ -116,19 +125,20 @@ public IActionResult ForgotMyPassword([FromBody] ForgotMyPasswordVM forgotMyPass
return NotFound(result);
}

#endregion
#endregion POST

#region PUT
[Authorize("Bearer")]

[HttpPut]
[Authorize("Bearer")]
[ProducesResponseType(typeof(Result<User>), 200)]
[ProducesResponseType(409)]
public IActionResult Update([FromBody] UpdateUserVM updateUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
{
if (!ModelState.IsValid)
return BadRequest();
return BadRequest(ModelState);

var user = Mapper.Map<UpdateUserVM, User>(updateUserVM);
var user = _mapper.Map<User>(updateUserVM);

user.Id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);

Expand Down Expand Up @@ -168,6 +178,7 @@ public IActionResult ChangeUserPasswordByHashCode([FromBody] ChangeUserPasswordB

return Ok(resultChangePasswordUser);
}
#endregion

#endregion PUT
}
}
Loading

0 comments on commit 48d51e5

Please sign in to comment.