Skip to content

Commit

Permalink
Merge pull request #317 from SharebookBR/OperationsController
Browse files Browse the repository at this point in the history
Operations controller
  • Loading branch information
raffacabofrio authored Apr 16, 2020
2 parents c4ac456 + 0498876 commit 6adfd8d
Show file tree
Hide file tree
Showing 10 changed files with 207 additions and 140 deletions.
169 changes: 88 additions & 81 deletions ShareBook/ShareBook.Api/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,154 +13,161 @@
using ShareBook.Infra.CrossCutting.Identity.Interfaces;
using ShareBook.Service;

namespace ShareBook.Api.Controllers {
[Route ("api/[controller]")]
[EnableCors ("AllowAllHeaders")]
namespace ShareBook.Api.Controllers
{
[Route("api/[controller]")]
[EnableCors("AllowAllHeaders")]
[GetClaimsFilter]
public class AccountController : Controller {
public class AccountController : Controller
{
private readonly IUserService _userService;
private readonly IApplicationSignInManager _signManager;

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

#region GET
[Authorize ("Bearer")]
[Authorize("Bearer")]
[HttpGet]
public UserVM Get () {
var id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
var user = _userService.Find (id);
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<User, UserVM>(user);
return userVM;
}

[Authorize ("Bearer")]
[HttpGet ("Profile")]
public object Profile () {
var id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
return new { profile = _userService.Find (id).Profile.ToString () };
[Authorize("Bearer")]
[HttpGet("Profile")]
public object Profile()
{
var id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
return new { profile = _userService.Find(id).Profile.ToString() };
}

[Authorize ("Bearer")]
[HttpGet ("ListFacilitators/{userIdDonator}")]
public IActionResult ListFacilitators (Guid userIdDonator) {
var facilitators = _userService.GetFacilitators (userIdDonator);
var facilitatorsClean = Mapper.Map<List<UserFacilitatorVM>> (facilitators);
return Ok (facilitatorsClean);
[Authorize("Bearer")]
[HttpGet("ListFacilitators/{userIdDonator}")]
public IActionResult ListFacilitators(Guid userIdDonator)
{
var facilitators = _userService.GetFacilitators(userIdDonator);
var facilitatorsClean = Mapper.Map<List<UserFacilitatorVM>>(facilitators);
return Ok(facilitatorsClean);
}
#endregion

#region POST
[HttpPost ("Register")]
[ProducesResponseType (typeof (object), 200)]
[ProducesResponseType (409)]
public IActionResult Post ([FromBody] RegisterUserVM registerUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) {
[HttpPost("Register")]
[ProducesResponseType(typeof(object), 200)]
[ProducesResponseType(409)]
public IActionResult Post([FromBody] RegisterUserVM registerUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
{
if (!ModelState.IsValid)
return BadRequest ();
return BadRequest();

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

var result = _userService.Insert (user);
var result = _userService.Insert(user);

if (result.Success)
return Ok (_signManager.GenerateTokenAndSetIdentity (result.Value, signingConfigurations, tokenConfigurations));
return Ok(_signManager.GenerateTokenAndSetIdentity(result.Value, signingConfigurations, tokenConfigurations));

return Conflict (result);
return Conflict(result);
}

[HttpPost ("Login")]
[ProducesResponseType (typeof (object), 200)]
[ProducesResponseType (404)]
public IActionResult Login ([FromBody] LoginUserVM loginUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) {
[HttpPost("Login")]
[ProducesResponseType(typeof(object), 200)]
[ProducesResponseType(404)]
public IActionResult Login([FromBody] LoginUserVM loginUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
{
if (!ModelState.IsValid)
return BadRequest ();
return BadRequest();

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

var result = _userService.AuthenticationByEmailAndPassword (user);
var result = _userService.AuthenticationByEmailAndPassword(user);

if (result.Success) {
var response = new Result {
Value = _signManager.GenerateTokenAndSetIdentity (result.Value, signingConfigurations, tokenConfigurations)
if (result.Success)
{
var response = new Result
{
Value = _signManager.GenerateTokenAndSetIdentity(result.Value, signingConfigurations, tokenConfigurations)
};

return Ok (response);
return Ok(response);
}

return NotFound (result);
return NotFound(result);
}

[HttpPost ("ForgotMyPassword")]
[ProducesResponseType (typeof (Result), 200)]
[ProducesResponseType (404)]
public IActionResult ForgotMyPassword ([FromBody] ForgotMyPasswordVM forgotMyPasswordVM) {
var result = _userService.GenerateHashCodePasswordAndSendEmailToUser (forgotMyPasswordVM.Email);
[HttpPost("ForgotMyPassword")]
[ProducesResponseType(typeof(Result), 200)]
[ProducesResponseType(404)]
public IActionResult ForgotMyPassword([FromBody] ForgotMyPasswordVM forgotMyPasswordVM)
{
var result = _userService.GenerateHashCodePasswordAndSendEmailToUser(forgotMyPasswordVM.Email);

if (result.Success)
return Ok (result);
return Ok(result);

return NotFound (result);
return NotFound(result);
}

#endregion

#region PUT
[Authorize ("Bearer")]
[Authorize("Bearer")]
[HttpPut]
[ProducesResponseType (typeof (Result<User>), 200)]
[ProducesResponseType (409)]
public IActionResult Update ([FromBody] UpdateUserVM updateUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) {
[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();

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

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

var result = _userService.Update (user);
var result = _userService.Update(user);

if (!result.Success)
return Conflict (result);
return Conflict(result);

return Ok (_signManager.GenerateTokenAndSetIdentity (result.Value, signingConfigurations, tokenConfigurations));
return Ok(_signManager.GenerateTokenAndSetIdentity(result.Value, signingConfigurations, tokenConfigurations));
}

[Authorize ("Bearer")]
[HttpPut ("ChangePassword")]
public Result<User> ChangePassword ([FromBody] ChangePasswordUserVM changePasswordUserVM) {
var user = new User () { Password = changePasswordUserVM.OldPassword };
user.Id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
return _userService.ValidOldPasswordAndChangeUserPassword (user, changePasswordUserVM.NewPassword);
[Authorize("Bearer")]
[HttpPut("ChangePassword")]
public Result<User> ChangePassword([FromBody] ChangePasswordUserVM changePasswordUserVM)
{
var user = new User() { Password = changePasswordUserVM.OldPassword };
user.Id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
return _userService.ValidOldPasswordAndChangeUserPassword(user, changePasswordUserVM.NewPassword);
}

[HttpPut ("ChangeUserPasswordByHashCode")]
[ProducesResponseType (typeof (Result<User>), 200)]
[ProducesResponseType (404)]
public IActionResult ChangeUserPasswordByHashCode ([FromBody] ChangeUserPasswordByHashCodeVM changeUserPasswordByHashCodeVM) {
var result = _userService.ConfirmHashCodePassword (changeUserPasswordByHashCodeVM.HashCodePassword);
[HttpPut("ChangeUserPasswordByHashCode")]
[ProducesResponseType(typeof(Result<User>), 200)]
[ProducesResponseType(404)]
public IActionResult ChangeUserPasswordByHashCode([FromBody] ChangeUserPasswordByHashCodeVM changeUserPasswordByHashCodeVM)
{
var result = _userService.ConfirmHashCodePassword(changeUserPasswordByHashCodeVM.HashCodePassword);
if (!result.Success)
return NotFound (result);
return NotFound(result);
var newPassword = changeUserPasswordByHashCodeVM.NewPassword;
var user = _userService.Find((result.Value as User).Id);
user.Password = newPassword;

var resultChangePasswordUser = _userService.ChangeUserPassword(user, newPassword);

if (!resultChangePasswordUser.Success)
return BadRequest (resultChangePasswordUser);
return BadRequest(resultChangePasswordUser);

return Ok (resultChangePasswordUser);
return Ok(resultChangePasswordUser);
}
#endregion

[HttpGet]
[Route ("ForceException")]
public IActionResult ForceException () {
var teste = 1 / Convert.ToInt32 ("Teste");
return BadRequest ();
}
}
}
16 changes: 1 addition & 15 deletions ShareBook/ShareBook.Api/Controllers/BookController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,7 @@ protected void SetDefault(Expression<Func<Book, object>> defaultOrder)
{
_defaultOrder = defaultOrder;
}

[HttpGet("Ping")]
public IActionResult Ping()
{
var result = new
{
ServerNow = DateTime.Now,
SaoPauloNow = DateTimeHelper.ConvertDateTimeSaoPaulo(DateTime.Now),
ServerToday = DateTime.Today,
SaoPauloToday = DateTimeHelper.GetTodaySaoPaulo(),
Message = "Pong!"
};
return Ok(result);
}


[HttpGet()]
[Authorize("Bearer")]
[AuthorizationFilter(Permissions.Permission.DonateBook)]
Expand Down
38 changes: 38 additions & 0 deletions ShareBook/ShareBook.Api/Controllers/OperationsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using ShareBook.Api.Filters;
using ShareBook.Helper;
using System;

namespace ShareBook.Api.Controllers
{
[Route("api/[controller]")]
[EnableCors("AllowAllHeaders")]
public class OperationsController : ControllerBase
{
[HttpGet]
[Authorize("Bearer")]
[AuthorizationFilter]
[Route("ForceException")]
public IActionResult ForceException()
{
var teste = 1 / Convert.ToInt32("Teste");
return BadRequest();
}

[HttpGet("Ping")]
public IActionResult Ping()
{
var result = new
{
ServerNow = DateTime.Now,
SaoPauloNow = DateTimeHelper.ConvertDateTimeSaoPaulo(DateTime.Now),
ServerToday = DateTime.Today,
SaoPauloToday = DateTimeHelper.GetTodaySaoPaulo(),
Message = "Pong!"
};
return Ok(result);
}
}
}
64 changes: 43 additions & 21 deletions ShareBook/ShareBook.Api/Middleware/ExceptionHandlerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,71 @@
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Rollbar;
using ShareBook.Api.Services;
using ShareBook.Domain.Common;
using ShareBook.Domain.Exceptions;

namespace ShareBook.Api.Middleware {
namespace ShareBook.Api.Middleware
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class ExceptionHandlerMiddleware {
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;

public ExceptionHandlerMiddleware (RequestDelegate next) {
public ExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke (HttpContext httpContext) {
try {
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
} catch (ShareBookException ex) {

}
catch (ShareBookException ex)
{
var result = new Result();
result.Messages.Add(ex.Message);
var jsonResponse = JsonConvert.SerializeObject(result);

httpContext.Response.Clear();
httpContext.Response.StatusCode = (int)ex.ErrorType;
await httpContext.Response.WriteAsync(jsonResponse);

RollbarLocator.RollbarInstance.Log(ErrorLevel.Error, jsonResponse);

return;
} catch (Exception ex) {
object error = new
}
catch (Exception ex)
{
if (RollbarConfigurator.IsActive)
{
Message = ex.Message,
StackTrace = ex.StackTrace,
Source = ex.Source
};
RollbarLocator.RollbarInstance.Log(ErrorLevel.Critical, error);
throw ex;
SendErrorToRollbar(ex);
}
var result = new Result();
result.Messages.Add(ex.Message);
var jsonResponse = JsonConvert.SerializeObject(result);

httpContext.Response.Clear();
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsync(jsonResponse);
}
}

private void SendErrorToRollbar(Exception ex)
{
object error = new
{
Message = ex.Message,
StackTrace = ex.StackTrace,
Source = ex.Source
};

RollbarLocator.RollbarInstance.Log(ErrorLevel.Critical, error);
}
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class ExceptionHandlerMiddlewareExtensions {
public static IApplicationBuilder UseExceptionHandlerMiddleware (this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionHandlerMiddleware> ();
public static class ExceptionHandlerMiddlewareExtensions
{
public static IApplicationBuilder UseExceptionHandlerMiddleware(this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionHandlerMiddleware>();
}

}
Loading

0 comments on commit 6adfd8d

Please sign in to comment.