Skip to content

Commit 6adfd8d

Browse files
Merge pull request #317 from SharebookBR/OperationsController
Operations controller
2 parents c4ac456 + 0498876 commit 6adfd8d

10 files changed

+207
-140
lines changed

ShareBook/ShareBook.Api/Controllers/AccountController.cs

+88-81
Original file line numberDiff line numberDiff line change
@@ -13,154 +13,161 @@
1313
using ShareBook.Infra.CrossCutting.Identity.Interfaces;
1414
using ShareBook.Service;
1515

16-
namespace ShareBook.Api.Controllers {
17-
[Route ("api/[controller]")]
18-
[EnableCors ("AllowAllHeaders")]
16+
namespace ShareBook.Api.Controllers
17+
{
18+
[Route("api/[controller]")]
19+
[EnableCors("AllowAllHeaders")]
1920
[GetClaimsFilter]
20-
public class AccountController : Controller {
21+
public class AccountController : Controller
22+
{
2123
private readonly IUserService _userService;
2224
private readonly IApplicationSignInManager _signManager;
2325

24-
public AccountController (IUserService userService, IApplicationSignInManager signManager) {
26+
public AccountController(IUserService userService, IApplicationSignInManager signManager)
27+
{
2528
_userService = userService;
2629
_signManager = signManager;
2730
}
2831

2932
#region GET
30-
[Authorize ("Bearer")]
33+
[Authorize("Bearer")]
3134
[HttpGet]
32-
public UserVM Get () {
33-
var id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
34-
var user = _userService.Find (id);
35+
public UserVM Get()
36+
{
37+
var id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
38+
var user = _userService.Find(id);
3539

36-
var userVM = Mapper.Map<User, UserVM> (user);
40+
var userVM = Mapper.Map<User, UserVM>(user);
3741
return userVM;
3842
}
3943

40-
[Authorize ("Bearer")]
41-
[HttpGet ("Profile")]
42-
public object Profile () {
43-
var id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
44-
return new { profile = _userService.Find (id).Profile.ToString () };
44+
[Authorize("Bearer")]
45+
[HttpGet("Profile")]
46+
public object Profile()
47+
{
48+
var id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
49+
return new { profile = _userService.Find(id).Profile.ToString() };
4550
}
4651

47-
[Authorize ("Bearer")]
48-
[HttpGet ("ListFacilitators/{userIdDonator}")]
49-
public IActionResult ListFacilitators (Guid userIdDonator) {
50-
var facilitators = _userService.GetFacilitators (userIdDonator);
51-
var facilitatorsClean = Mapper.Map<List<UserFacilitatorVM>> (facilitators);
52-
return Ok (facilitatorsClean);
52+
[Authorize("Bearer")]
53+
[HttpGet("ListFacilitators/{userIdDonator}")]
54+
public IActionResult ListFacilitators(Guid userIdDonator)
55+
{
56+
var facilitators = _userService.GetFacilitators(userIdDonator);
57+
var facilitatorsClean = Mapper.Map<List<UserFacilitatorVM>>(facilitators);
58+
return Ok(facilitatorsClean);
5359
}
5460
#endregion
5561

5662
#region POST
57-
[HttpPost ("Register")]
58-
[ProducesResponseType (typeof (object), 200)]
59-
[ProducesResponseType (409)]
60-
public IActionResult Post ([FromBody] RegisterUserVM registerUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) {
63+
[HttpPost("Register")]
64+
[ProducesResponseType(typeof(object), 200)]
65+
[ProducesResponseType(409)]
66+
public IActionResult Post([FromBody] RegisterUserVM registerUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
67+
{
6168
if (!ModelState.IsValid)
62-
return BadRequest ();
69+
return BadRequest();
6370

64-
var user = Mapper.Map<RegisterUserVM, User> (registerUserVM);
71+
var user = Mapper.Map<RegisterUserVM, User>(registerUserVM);
6572

66-
var result = _userService.Insert (user);
73+
var result = _userService.Insert(user);
6774

6875
if (result.Success)
69-
return Ok (_signManager.GenerateTokenAndSetIdentity (result.Value, signingConfigurations, tokenConfigurations));
76+
return Ok(_signManager.GenerateTokenAndSetIdentity(result.Value, signingConfigurations, tokenConfigurations));
7077

71-
return Conflict (result);
78+
return Conflict(result);
7279
}
7380

74-
[HttpPost ("Login")]
75-
[ProducesResponseType (typeof (object), 200)]
76-
[ProducesResponseType (404)]
77-
public IActionResult Login ([FromBody] LoginUserVM loginUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) {
81+
[HttpPost("Login")]
82+
[ProducesResponseType(typeof(object), 200)]
83+
[ProducesResponseType(404)]
84+
public IActionResult Login([FromBody] LoginUserVM loginUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
85+
{
7886
if (!ModelState.IsValid)
79-
return BadRequest ();
87+
return BadRequest();
8088

81-
var user = Mapper.Map<LoginUserVM, User> (loginUserVM);
89+
var user = Mapper.Map<LoginUserVM, User>(loginUserVM);
8290

83-
var result = _userService.AuthenticationByEmailAndPassword (user);
91+
var result = _userService.AuthenticationByEmailAndPassword(user);
8492

85-
if (result.Success) {
86-
var response = new Result {
87-
Value = _signManager.GenerateTokenAndSetIdentity (result.Value, signingConfigurations, tokenConfigurations)
93+
if (result.Success)
94+
{
95+
var response = new Result
96+
{
97+
Value = _signManager.GenerateTokenAndSetIdentity(result.Value, signingConfigurations, tokenConfigurations)
8898
};
8999

90-
return Ok (response);
100+
return Ok(response);
91101
}
92102

93-
return NotFound (result);
103+
return NotFound(result);
94104
}
95105

96-
[HttpPost ("ForgotMyPassword")]
97-
[ProducesResponseType (typeof (Result), 200)]
98-
[ProducesResponseType (404)]
99-
public IActionResult ForgotMyPassword ([FromBody] ForgotMyPasswordVM forgotMyPasswordVM) {
100-
var result = _userService.GenerateHashCodePasswordAndSendEmailToUser (forgotMyPasswordVM.Email);
106+
[HttpPost("ForgotMyPassword")]
107+
[ProducesResponseType(typeof(Result), 200)]
108+
[ProducesResponseType(404)]
109+
public IActionResult ForgotMyPassword([FromBody] ForgotMyPasswordVM forgotMyPasswordVM)
110+
{
111+
var result = _userService.GenerateHashCodePasswordAndSendEmailToUser(forgotMyPasswordVM.Email);
101112

102113
if (result.Success)
103-
return Ok (result);
114+
return Ok(result);
104115

105-
return NotFound (result);
116+
return NotFound(result);
106117
}
107118

108119
#endregion
109120

110121
#region PUT
111-
[Authorize ("Bearer")]
122+
[Authorize("Bearer")]
112123
[HttpPut]
113-
[ProducesResponseType (typeof (Result<User>), 200)]
114-
[ProducesResponseType (409)]
115-
public IActionResult Update ([FromBody] UpdateUserVM updateUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) {
124+
[ProducesResponseType(typeof(Result<User>), 200)]
125+
[ProducesResponseType(409)]
126+
public IActionResult Update([FromBody] UpdateUserVM updateUserVM, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations)
127+
{
116128
if (!ModelState.IsValid)
117-
return BadRequest ();
129+
return BadRequest();
118130

119-
var user = Mapper.Map<UpdateUserVM, User> (updateUserVM);
131+
var user = Mapper.Map<UpdateUserVM, User>(updateUserVM);
120132

121-
user.Id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
133+
user.Id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
122134

123-
var result = _userService.Update (user);
135+
var result = _userService.Update(user);
124136

125137
if (!result.Success)
126-
return Conflict (result);
138+
return Conflict(result);
127139

128-
return Ok (_signManager.GenerateTokenAndSetIdentity (result.Value, signingConfigurations, tokenConfigurations));
140+
return Ok(_signManager.GenerateTokenAndSetIdentity(result.Value, signingConfigurations, tokenConfigurations));
129141
}
130142

131-
[Authorize ("Bearer")]
132-
[HttpPut ("ChangePassword")]
133-
public Result<User> ChangePassword ([FromBody] ChangePasswordUserVM changePasswordUserVM) {
134-
var user = new User () { Password = changePasswordUserVM.OldPassword };
135-
user.Id = new Guid (Thread.CurrentPrincipal?.Identity?.Name);
136-
return _userService.ValidOldPasswordAndChangeUserPassword (user, changePasswordUserVM.NewPassword);
143+
[Authorize("Bearer")]
144+
[HttpPut("ChangePassword")]
145+
public Result<User> ChangePassword([FromBody] ChangePasswordUserVM changePasswordUserVM)
146+
{
147+
var user = new User() { Password = changePasswordUserVM.OldPassword };
148+
user.Id = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
149+
return _userService.ValidOldPasswordAndChangeUserPassword(user, changePasswordUserVM.NewPassword);
137150
}
138151

139-
[HttpPut ("ChangeUserPasswordByHashCode")]
140-
[ProducesResponseType (typeof (Result<User>), 200)]
141-
[ProducesResponseType (404)]
142-
public IActionResult ChangeUserPasswordByHashCode ([FromBody] ChangeUserPasswordByHashCodeVM changeUserPasswordByHashCodeVM) {
143-
var result = _userService.ConfirmHashCodePassword (changeUserPasswordByHashCodeVM.HashCodePassword);
152+
[HttpPut("ChangeUserPasswordByHashCode")]
153+
[ProducesResponseType(typeof(Result<User>), 200)]
154+
[ProducesResponseType(404)]
155+
public IActionResult ChangeUserPasswordByHashCode([FromBody] ChangeUserPasswordByHashCodeVM changeUserPasswordByHashCodeVM)
156+
{
157+
var result = _userService.ConfirmHashCodePassword(changeUserPasswordByHashCodeVM.HashCodePassword);
144158
if (!result.Success)
145-
return NotFound (result);
159+
return NotFound(result);
146160
var newPassword = changeUserPasswordByHashCodeVM.NewPassword;
147161
var user = _userService.Find((result.Value as User).Id);
148162
user.Password = newPassword;
149163

150164
var resultChangePasswordUser = _userService.ChangeUserPassword(user, newPassword);
151-
165+
152166
if (!resultChangePasswordUser.Success)
153-
return BadRequest (resultChangePasswordUser);
167+
return BadRequest(resultChangePasswordUser);
154168

155-
return Ok (resultChangePasswordUser);
169+
return Ok(resultChangePasswordUser);
156170
}
157171
#endregion
158-
159-
[HttpGet]
160-
[Route ("ForceException")]
161-
public IActionResult ForceException () {
162-
var teste = 1 / Convert.ToInt32 ("Teste");
163-
return BadRequest ();
164-
}
165172
}
166173
}

ShareBook/ShareBook.Api/Controllers/BookController.cs

+1-15
Original file line numberDiff line numberDiff line change
@@ -38,21 +38,7 @@ protected void SetDefault(Expression<Func<Book, object>> defaultOrder)
3838
{
3939
_defaultOrder = defaultOrder;
4040
}
41-
42-
[HttpGet("Ping")]
43-
public IActionResult Ping()
44-
{
45-
var result = new
46-
{
47-
ServerNow = DateTime.Now,
48-
SaoPauloNow = DateTimeHelper.ConvertDateTimeSaoPaulo(DateTime.Now),
49-
ServerToday = DateTime.Today,
50-
SaoPauloToday = DateTimeHelper.GetTodaySaoPaulo(),
51-
Message = "Pong!"
52-
};
53-
return Ok(result);
54-
}
55-
41+
5642
[HttpGet()]
5743
[Authorize("Bearer")]
5844
[AuthorizationFilter(Permissions.Permission.DonateBook)]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Cors;
3+
using Microsoft.AspNetCore.Mvc;
4+
using ShareBook.Api.Filters;
5+
using ShareBook.Helper;
6+
using System;
7+
8+
namespace ShareBook.Api.Controllers
9+
{
10+
[Route("api/[controller]")]
11+
[EnableCors("AllowAllHeaders")]
12+
public class OperationsController : ControllerBase
13+
{
14+
[HttpGet]
15+
[Authorize("Bearer")]
16+
[AuthorizationFilter]
17+
[Route("ForceException")]
18+
public IActionResult ForceException()
19+
{
20+
var teste = 1 / Convert.ToInt32("Teste");
21+
return BadRequest();
22+
}
23+
24+
[HttpGet("Ping")]
25+
public IActionResult Ping()
26+
{
27+
var result = new
28+
{
29+
ServerNow = DateTime.Now,
30+
SaoPauloNow = DateTimeHelper.ConvertDateTimeSaoPaulo(DateTime.Now),
31+
ServerToday = DateTime.Today,
32+
SaoPauloToday = DateTimeHelper.GetTodaySaoPaulo(),
33+
Message = "Pong!"
34+
};
35+
return Ok(result);
36+
}
37+
}
38+
}

ShareBook/ShareBook.Api/Middleware/ExceptionHandlerMiddleware.cs

+43-21
Original file line numberDiff line numberDiff line change
@@ -4,49 +4,71 @@
44
using Microsoft.AspNetCore.Http;
55
using Newtonsoft.Json;
66
using Rollbar;
7+
using ShareBook.Api.Services;
78
using ShareBook.Domain.Common;
89
using ShareBook.Domain.Exceptions;
910

10-
namespace ShareBook.Api.Middleware {
11+
namespace ShareBook.Api.Middleware
12+
{
1113
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
12-
public class ExceptionHandlerMiddleware {
14+
public class ExceptionHandlerMiddleware
15+
{
1316
private readonly RequestDelegate _next;
1417

15-
public ExceptionHandlerMiddleware (RequestDelegate next) {
18+
public ExceptionHandlerMiddleware(RequestDelegate next)
19+
{
1620
_next = next;
1721
}
1822

19-
public async Task Invoke (HttpContext httpContext) {
20-
try {
23+
public async Task Invoke(HttpContext httpContext)
24+
{
25+
try
26+
{
2127
await _next(httpContext);
22-
} catch (ShareBookException ex) {
23-
28+
}
29+
catch (ShareBookException ex)
30+
{
2431
var result = new Result();
2532
result.Messages.Add(ex.Message);
2633
var jsonResponse = JsonConvert.SerializeObject(result);
2734

2835
httpContext.Response.Clear();
2936
httpContext.Response.StatusCode = (int)ex.ErrorType;
3037
await httpContext.Response.WriteAsync(jsonResponse);
31-
32-
RollbarLocator.RollbarInstance.Log(ErrorLevel.Error, jsonResponse);
33-
34-
return;
35-
} catch (Exception ex) {
36-
object error = new
38+
}
39+
catch (Exception ex)
40+
{
41+
if (RollbarConfigurator.IsActive)
3742
{
38-
Message = ex.Message,
39-
StackTrace = ex.StackTrace,
40-
Source = ex.Source
41-
};
42-
RollbarLocator.RollbarInstance.Log(ErrorLevel.Critical, error);
43-
throw ex;
43+
SendErrorToRollbar(ex);
44+
}
45+
var result = new Result();
46+
result.Messages.Add(ex.Message);
47+
var jsonResponse = JsonConvert.SerializeObject(result);
48+
49+
httpContext.Response.Clear();
50+
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
51+
await httpContext.Response.WriteAsync(jsonResponse);
4452
}
4553
}
54+
55+
private void SendErrorToRollbar(Exception ex)
56+
{
57+
object error = new
58+
{
59+
Message = ex.Message,
60+
StackTrace = ex.StackTrace,
61+
Source = ex.Source
62+
};
63+
64+
RollbarLocator.RollbarInstance.Log(ErrorLevel.Critical, error);
65+
}
4666
}
4767

4868
// Extension method used to add the middleware to the HTTP request pipeline.
49-
public static class ExceptionHandlerMiddlewareExtensions {
50-
public static IApplicationBuilder UseExceptionHandlerMiddleware (this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionHandlerMiddleware> ();
69+
public static class ExceptionHandlerMiddlewareExtensions
70+
{
71+
public static IApplicationBuilder UseExceptionHandlerMiddleware(this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionHandlerMiddleware>();
5172
}
73+
5274
}

0 commit comments

Comments
 (0)