Skip to content

Commit

Permalink
Merge pull request #366 from SharebookBR/release
Browse files Browse the repository at this point in the history
Release
  • Loading branch information
raffacabofrio authored Jun 16, 2020
2 parents f06167c + d8e3fd8 commit e01b895
Show file tree
Hide file tree
Showing 48 changed files with 2,109 additions and 289 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,35 @@ protected DomainToViewModelMappingProfile(string profileName) : base(profileName
{
#region [ Book ]

CreateMap<Book, BooksVM>()
CreateMap<Book, BookVMAdm>()
.ForMember(dest => dest.Donor, opt => opt.MapFrom(src => src.User.Name))
.ForMember(dest => dest.City, opt => opt.MapFrom(src => src.User.Address.City))
.ForMember(dest => dest.State, opt => opt.MapFrom(src => src.User.Address.State))
.ForMember(dest => dest.Facilitator, opt => opt.MapFrom(src => src.UserFacilitator.Name))
.ForMember(dest => dest.FacilitatorNotes, opt => opt.MapFrom(src => src.FacilitatorNotes))
.ForMember(dest => dest.Donated, opt => opt.MapFrom(src => src.Donated()))
.ForMember(dest => dest.PhoneDonor, opt => opt.MapFrom(src => src.User.Phone))
.ForMember(dest => dest.DaysInShowcase, opt => opt.MapFrom(src => src.DaysInShowcase()))
.ForMember(dest => dest.TotalInterested, opt => opt.MapFrom(src => src.TotalInterested()))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status().Description()))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status.ToString()))
.ForMember(dest => dest.FreightOption, opt => opt.MapFrom(src => src.FreightOption.ToString()))
.ForMember(dest => dest.CreationDate, opt => opt.MapFrom(src => src.CreationDate))
.ForMember(dest => dest.ChooseDate, opt => opt.MapFrom(src => src.ChooseDate))
.ForMember(dest => dest.Winner, opt => opt.MapFrom(src => src.Winner()))
.ForMember(dest => dest.TrackingNumber, opt => opt.MapFrom(src => src.TrackingNumber));
.ForMember(dest => dest.TrackingNumber, opt => opt.MapFrom(src => src.TrackingNumber))
.ForMember(dest => dest.Category, opt => opt.MapFrom(src => src.Category.Name));

CreateMap<Book, BookVM>()
.ForMember(dest => dest.City, opt => opt.MapFrom(src => src.User.Address.City))
.ForMember(dest => dest.State, opt => opt.MapFrom(src => src.User.Address.State))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status.ToString()))
.ForMember(dest => dest.FreightOption, opt => opt.MapFrom(src => src.FreightOption.ToString()))
.ForMember(dest => dest.CreationDate, opt => opt.MapFrom(src => src.CreationDate))
.ForMember(dest => dest.Category, opt => opt.MapFrom(src => src.Category.Name));

CreateMap<BookUser, MyBookRequestVM>()
.ForMember(dest => dest.Author, opt => opt.MapFrom(src => src.Book.Author))
.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.Status, opt => opt.MapFrom(src => src.Status.ToString()))
.ForMember(dest => dest.RequestId, opt => opt.MapFrom(src => src.Id));

#endregion [ Book ]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Sharebook.Jobs;
using ShareBook.Service.Notification;
using ShareBook.Service.Muambator;
using ShareBook.Service.AWSSQS;

namespace ShareBook.Api.Configuration
{
Expand All @@ -30,6 +31,7 @@ public static IServiceCollection RegisterRepositoryServices(
services.AddScoped<IContactUsService, ContactUsService>();
services.AddScoped<IContactUsEmailService, ContactUsEmailService>();
services.AddScoped<IMuambatorService, MuambatorService>();
services.AddSingleton<IAWSSQSService, AWSSQSService>();

//repositories
services.AddScoped<IBookRepository, BookRepository>();
Expand Down Expand Up @@ -63,6 +65,7 @@ public static IServiceCollection RegisterRepositoryServices(
services.AddScoped<RemoveBookFromShowcase>();
services.AddScoped<ChooseDateReminder>();
services.AddScoped<LateDonationNotification>();
services.AddScoped<NewBookNotify>();

//notification
services.AddScoped<INotificationService, NotificationService>();
Expand Down
39 changes: 35 additions & 4 deletions ShareBook/ShareBook.Api/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using ShareBook.Api.Filters;
using ShareBook.Api.ViewModels;
using ShareBook.Domain;
using ShareBook.Domain.Common;
using ShareBook.Domain.Exceptions;
using ShareBook.Infra.CrossCutting.Identity;
using ShareBook.Infra.CrossCutting.Identity.Interfaces;
using ShareBook.Service;
Expand All @@ -23,14 +25,17 @@ public class AccountController : ControllerBase
private readonly IUserService _userService;
private readonly IApplicationSignInManager _signManager;
private readonly IMapper _mapper;
private readonly IConfiguration _configuration;

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

#region GET
Expand Down Expand Up @@ -90,13 +95,22 @@ public IActionResult Post([FromBody] RegisterUserVM registerUserVM, [FromService
[HttpPost("Login")]
[ProducesResponseType(typeof(object), 200)]
[ProducesResponseType(404)]
public IActionResult Login([FromBody] LoginUserVM loginUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
public IActionResult Login(
[FromBody] LoginUserVM loginUserVM,
[FromServices] SigningConfigurations signingConfigurations,
[FromServices] TokenConfigurations tokenConfigurations,
[FromHeader(Name = "x-requested-with")] string client,
[FromHeader(Name = "client-version")] string clientVersion)
{

if (!ModelState.IsValid)
return BadRequest();
return BadRequest(ModelState);

var user = _mapper.Map<User>(loginUserVM);
// mensagem amigável para usuários mobile antigos
if (!IsValidClientVersion(client, clientVersion))
throw new ShareBookException("Não é possível fazer login porque seu app está desatualizado. Por favor atualize seu app na loja do Google Play.");

var user = _mapper.Map<User>(loginUserVM);
var result = _userService.AuthenticationByEmailAndPassword(user);

if (result.Success)
Expand Down Expand Up @@ -180,5 +194,22 @@ public IActionResult ChangeUserPasswordByHashCode([FromBody] ChangeUserPasswordB
}

#endregion PUT

private bool IsValidClientVersion(string client, string clientVersion)
{
switch (client)
{
case "web":
return true;

// mobile android
case "com.makeztec.sharebook":
var minVersion = _configuration["ClientSettings:AndroidMinVersion"];
return Helper.ClientVersionValidation.IsValidVersion(clientVersion, minVersion);

default:
return false;
}
}
}
}
83 changes: 59 additions & 24 deletions ShareBook/ShareBook.Api/Controllers/BookController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,19 @@ protected void SetDefault(Expression<Func<Book, object>> defaultOrder)
[HttpGet()]
[Authorize("Bearer")]
[AuthorizationFilter(Permissions.Permission.DonateBook)]
public PagedList<BooksVM> GetAll() => Paged(1, 15);
public PagedList<BookVMAdm> GetAll() => Paged(1, 15);

[HttpGet("{page}/{items}")]
[Authorize("Bearer")]
[AuthorizationFilter(Permissions.Permission.DonateBook)]
public PagedList<BooksVM> Paged(int page, int items)
public PagedList<BookVMAdm> Paged(int page, int items)
{
// TODO: parar de usar esse get complicado e fazer uma query linq/ef tradicional usando
// ThenInclude(). fonte: https://stackoverflow.com/questions/10822656/entity-framework-include-multiple-levels-of-properties
var books = _service.Get(x => x.Title, page, items, new IncludeList<Book>(x => x.User, x => x.BookUsers, x => x.UserFacilitator));
var responseVM = _mapper.Map<List<BooksVM>>(books.Items);
var responseVM = _mapper.Map<List<BookVMAdm>>(books.Items);

return new PagedList<BooksVM>()
return new PagedList<BookVMAdm>()
{
Page = page,
TotalItems = books.TotalItems,
Expand All @@ -67,13 +67,14 @@ public PagedList<BooksVM> Paged(int page, int items)
};
}

[HttpGet("{id}")]
public Book GetById(string id) => _service.Find(new Guid(id));

[Authorize("Bearer")]
[HttpPost("Approve/{id}")]
[AuthorizationFilter(Permissions.Permission.ApproveBook)]
public Result<Book> Approve(string id, [FromBody] ApproveBookVM model) => _service.Approve(new Guid(id), model?.ChooseDate);
public Result Approve(string id, [FromBody] ApproveBookVM model)
{
_service.Approve(new Guid(id), model?.ChooseDate);
return new Result("Livro aprovado com sucesso.");
}

[Authorize("Bearer")]
[HttpPost("Cancel/{id}")]
Expand Down Expand Up @@ -107,28 +108,49 @@ public IActionResult GetRequestersList(Guid bookId)
}

[HttpGet("Slug/{slug}")]
[ProducesResponseType(typeof(BookVM), 200)]
public IActionResult Get(string slug)
{
var book = _service.BySlug(slug);
return book != null ? (IActionResult)Ok(book) : NotFound();
var bookVM = _mapper.Map<BookVM>(book);
return book != null ? (IActionResult)Ok(bookVM) : NotFound();
}

[HttpGet("Top15NewBooks")]
public IList<Book> Top15NewBooks() => _service.Top15NewBooks();

[HttpGet("Random15Books")]
public IList<Book> Random15Books() => _service.Random15Books();

[Authorize("Bearer")]
[HttpGet("Title/{title}/{page}/{items}")]
public PagedList<Book> ByTitle(string title, int page, int items) => _service.ByTitle(title, page, items);
[AuthorizationFilter(Permissions.Permission.ApproveBook)] // apenas adms
[ProducesResponseType(typeof(BookVM), 200)]
[HttpGet("{id}")]
public IActionResult GetById(string id)
{
var book = _service.Find(new Guid(id));
var bookVM = _mapper.Map<BookVMAdm>(book);
return bookVM != null ? (IActionResult)Ok(bookVM) : NotFound();
}

[Authorize("Bearer")]
[HttpGet("Author/{author}/{page}/{items}")]
public PagedList<Book> ByAuthor(string author, int page, int items) => _service.ByAuthor(author, page, items);
[HttpGet("AvailableBooks")]
public IList<BookVM> AvailableBooks() {
var books = _service.AvailableBooks();
return _mapper.Map<List<BookVM>>(books);
}

[HttpGet("Random15Books")]
public IList<BookVM> Random15Books() {
var books = _service.Random15Books();
return _mapper.Map<List<BookVM>>(books);
}

[HttpGet("FullSearch/{criteria}/{page}/{items}")]
public PagedList<Book> FullSearch(string criteria, int page, int items) => _service.FullSearch(criteria, page, items);
public PagedList<BookVM> FullSearch(string criteria, int page, int items) {
var books = _service.FullSearch(criteria, page, items);
var booksVM = _mapper.Map<List<BookVM>>(books.Items);
return new PagedList<BookVM>()
{
Page = page,
TotalItems = books.TotalItems,
ItemsPerPage = items,
Items = booksVM
};
}

[Authorize("Bearer")]
[HttpGet("FullSearchAdmin/{criteria}")]
Expand All @@ -140,7 +162,20 @@ public PagedList<Book> FullSearchAdmin(string criteria, int page, int items)
}

[HttpGet("Category/{categoryId}/{page}/{items}")]
public PagedList<Book> ByCategoryId(Guid categoryId, int page, int items) => _service.ByCategoryId(categoryId, page, items);
public PagedList<BookVM> ByCategoryId(Guid categoryId, int page, int items)
{
var booksPaged = _service.ByCategoryId(categoryId, page, items);
var books = booksPaged.Items;
var booksVM = _mapper.Map<List<BookVM>>(books);

return new PagedList<BookVM>()
{
Page = page,
ItemsPerPage = items,
TotalItems = booksPaged.TotalItems,
Items = booksVM
};
}

[Authorize("Bearer")]
[HttpPost("Request")]
Expand Down Expand Up @@ -223,11 +258,11 @@ public PagedList<MyBookRequestVM> MyRequests(int page, int items)

[Authorize("Bearer")]
[HttpGet("MyDonations")]
public IList<BooksVM> MyDonations()
public IList<BookVMAdm> MyDonations()
{
Guid userId = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
var donations = _service.GetUserDonations(userId);
return _mapper.Map<List<BooksVM>>(donations);
return _mapper.Map<List<BookVMAdm>>(donations);
}

[Authorize("Bearer")]
Expand Down
18 changes: 17 additions & 1 deletion ShareBook/ShareBook.Api/Controllers/OperationsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
using Microsoft.Extensions.Options;
using Sharebook.Jobs;
using ShareBook.Api.Filters;
using ShareBook.Api.ViewModels;
using ShareBook.Helper;
using ShareBook.Service;
using ShareBook.Service.Authorization;
using ShareBook.Service.Server;
using System;
Expand All @@ -18,11 +20,13 @@ public class OperationsController : Controller

protected IJobExecutor _executor;
protected string _validToken;
IEmailService _emailService;

public OperationsController(IJobExecutor executor, IOptions<ServerSettings> settings)
public OperationsController(IJobExecutor executor, IOptions<ServerSettings> settings, IEmailService emailService)
{
_executor = executor;
_validToken = settings.Value.JobExecutorToken;
_emailService = emailService;
}

[HttpGet]
Expand Down Expand Up @@ -59,6 +63,18 @@ public IActionResult Executor()
return Ok(_executor.Execute());
}

[HttpPost("EmailTest")]
[Authorize("Bearer")]
[AuthorizationFilter(Permissions.Permission.ApproveBook)] // adm
public IActionResult EmailTest([FromBody] EmailTestVM emailVM)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);

_emailService.Test(emailVM.Email, emailVM.Name);
return Ok();
}

protected bool _IsValidJobToken() => Request.Headers["Authorization"].ToString() == _validToken;
}
}
24 changes: 21 additions & 3 deletions ShareBook/ShareBook.Api/Middleware/ExceptionHandlerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Rollbar;
using ShareBook.Api.Services;
using ShareBook.Domain.Common;
Expand All @@ -29,7 +30,7 @@ public async Task Invoke(HttpContext httpContext)
{
var result = new Result();
result.Messages.Add(ex.Message);
var jsonResponse = JsonConvert.SerializeObject(result);
var jsonResponse = ToJson(result);

httpContext.Response.Clear();
httpContext.Response.StatusCode = (int)ex.ErrorType;
Expand All @@ -42,14 +43,15 @@ public async Task Invoke(HttpContext httpContext)
{
SendErrorToRollbar(ex);
}

var result = new Result();
result.Messages.Add(ex.Message);
result.Messages.Add(ex.ToString());

// detalhes do erro real pra facilitar o desenvolvimento.
if (ex is AggregateException)
result.Messages.Add(ex.InnerException.ToString());

var jsonResponse = JsonConvert.SerializeObject(result);
var jsonResponse = ToJson(result);

httpContext.Response.Clear();
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
Expand All @@ -58,6 +60,22 @@ public async Task Invoke(HttpContext httpContext)
}
}

private string ToJson(Object obj)
{
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};

string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});

return json;
}

private void SendErrorToRollbar(Exception ex)
{
object error = new
Expand Down
Loading

0 comments on commit e01b895

Please sign in to comment.