Skip to content

Commit d33a844

Browse files
committed
AuthController with rate limiting and logging2
1 parent d842181 commit d33a844

File tree

1 file changed

+85
-35
lines changed

1 file changed

+85
-35
lines changed
Lines changed: 85 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,94 @@
1-
🛠️ Refactor suggestion
1+
using System.Security.Claims;
2+
using Microsoft.AspNetCore.Authorization;
3+
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.AspNetCore.RateLimiting;
5+
using Microsoft.Extensions.Logging;
6+
using Streetcode.BLL.DTO.Authentication.Login;
7+
using Streetcode.BLL.DTO.Authentication.RefreshToken;
8+
using Streetcode.BLL.DTO.Authentication.Register;
9+
using Streetcode.BLL.MediatR.Authentication.Login;
10+
using Streetcode.BLL.MediatR.Authentication.LoginGoogle;
11+
using Streetcode.BLL.MediatR.Authentication.Logout;
12+
using Streetcode.BLL.MediatR.Authentication.RefreshToken;
13+
using Streetcode.BLL.MediatR.Authentication.Register;
214

3-
Implement consistent security measures across the controller.
15+
namespace Streetcode.WebApi.Controllers.Authentication
16+
{
17+
[ApiController]
18+
[EnableRateLimiting("api")] // Apply rate limiting to all endpoints
19+
[Route("api/[controller]")]
20+
public class AuthController : BaseApiController
21+
{
22+
private readonly ILogger<AuthController> _logger;
423

5-
Consider applying these security measures controller-wide:
24+
public AuthController(ILogger<AuthController> logger)
25+
{
26+
_logger = logger;
27+
}
628

7-
CSRF protection for all state-changing operations
8-
Rate limiting for all public endpoints
9-
Consistent error handling and logging strategy
29+
[HttpPost("login")]
30+
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LoginResponseDTO))]
31+
public async Task<IActionResult> Login([FromBody] LoginRequestDTO loginDTO)
32+
{
33+
_logger.LogInformation("Login attempt for user: {Email}", loginDTO.Email);
34+
return HandleResult(await Mediator.Send(new LoginQuery(loginDTO)));
35+
}
1036

11-
Example implementation:
37+
[HttpPost("register")]
38+
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(RegisterResponseDTO))]
39+
public async Task<IActionResult> Register([FromBody] RegisterRequestDTO registerDTO)
40+
{
41+
_logger.LogInformation("New user registration attempt: {Email}", registerDTO.Email);
42+
return HandleResult(await Mediator.Send(new RegisterQuery(registerDTO)));
43+
}
1244

13-
[ApiController]
14-
+[ValidateAntiForgeryToken] // Apply to all POST endpoints
15-
+[EnableRateLimiting("api")] // Configure different limits per endpoint in Program.cs
16-
public class AuthController : BaseApiController
17-
{
18-
+ private readonly ILogger<AuthController> _logger;
19-
+
20-
+ public AuthController(ILogger<AuthController> logger)
21-
+ {
22-
+ _logger = logger;
23-
+ }
45+
[HttpPost("refresh-token")]
46+
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(RefreshTokenResponceDTO))]
47+
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequestDTO token)
48+
{
49+
_logger.LogInformation("Refresh token attempt.");
50+
return HandleResult(await Mediator.Send(new RefreshTokenQuery(token)));
51+
}
2452

25-
📝 Committable suggestion
53+
[Authorize]
54+
[HttpPost("logout")]
55+
[ProducesResponseType(StatusCodes.Status200OK)]
56+
public async Task<IActionResult> Logout()
57+
{
58+
var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
2659

27-
‼️ IMPORTANT
28-
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
60+
if (string.IsNullOrEmpty(userId))
61+
{
62+
_logger.LogWarning("Unauthorized logout attempt.");
63+
return Unauthorized("User is not authenticated.");
64+
}
2965

30-
Suggested change
31-
[ApiController]
32-
public class AuthController : BaseApiController
33-
{
34-
[ApiController]
35-
[ValidateAntiForgeryToken] // Apply to all POST endpoints
36-
[EnableRateLimiting("api")] // Configure different limits per endpoint in Program.cs
37-
public class AuthController : BaseApiController
38-
{
39-
private readonly ILogger<AuthController> _logger;
40-
41-
public AuthController(ILogger<AuthController> logger)
66+
var result = await Mediator.Send(new LogoutCommand(userId));
67+
68+
if (result.IsFailed)
69+
{
70+
_logger.LogError("Logout failed for user: {UserId}", userId);
71+
return BadRequest(result.Errors.First().Message);
72+
}
73+
74+
_logger.LogInformation("User {UserId} logged out successfully.", userId);
75+
return Ok("Logout successful. Refresh token invalidated.");
76+
}
77+
78+
[HttpPost("google-login")]
79+
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LoginResponseDTO))]
80+
public async Task<IActionResult> GoogleLogin([FromBody] string idToken)
4281
{
43-
_logger = logger;
44-
}
82+
_logger.LogInformation("Google login attempt.");
83+
var result = await Mediator.Send(new LoginGoogleQuery(idToken));
84+
85+
if (result.IsSuccess)
86+
{
87+
return Ok(result.Value);
88+
}
89+
90+
_logger.LogWarning("Google login failed.");
91+
return Unauthorized(new { message = result.Errors.FirstOrDefault()?.Message });
92+
}
93+
}
94+
}

0 commit comments

Comments
 (0)