Skip to content

Commit d842181

Browse files
committed
Refactored AuthController with rate limiting and logging
1 parent ac39e30 commit d842181

File tree

1 file changed

+35
-120
lines changed

1 file changed

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

15-
namespace Streetcode.WebApi.Controllers.Authentication
16-
{
17-
[ApiController]
18-
public class AuthController : BaseApiController
19-
{
20-
// Login action for regular user login
21-
[HttpPost]
22-
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LoginResponseDTO))]
23-
public async Task<IActionResult> Login([FromBody] LoginRequestDTO loginDTO)
24-
{
25-
return HandleResult(await Mediator.Send(new LoginQuery(loginDTO)));
26-
}
27-
28-
// Register action for new user registration
29-
[HttpPost]
30-
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(RegisterResponseDTO))]
31-
public async Task<IActionResult> Register([FromBody] RegisterRequestDTO registerDTO)
32-
{
33-
return HandleResult(await Mediator.Send(new RegisterQuery(registerDTO)));
34-
}
35-
36-
// Refresh token action to obtain a new access token
37-
[HttpPost]
38-
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(RefreshTokenResponceDTO))]
39-
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequestDTO token)
40-
{
41-
return HandleResult(await Mediator.Send(new RefreshTokenQuery(token)));
42-
}
43-
44-
// Logout action to invalidate the user session or token
45-
[Authorize]
46-
[HttpPost]
47-
[ProducesResponseType(StatusCodes.Status200OK)]
48-
public async Task<IActionResult> Logout()
49-
{
50-
var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
51-
52-
if (string.IsNullOrEmpty(userId))
53-
{
54-
return Unauthorized("User is not authenticated.");
55-
}
3+
Implement consistent security measures across the controller.
564

57-
// Invalidate the authentication session (sign out)
58-
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
5+
Consider applying these security measures controller-wide:
596

60-
var result = await Mediator.Send(new LogoutCommand(userId));
7+
CSRF protection for all state-changing operations
8+
Rate limiting for all public endpoints
9+
Consistent error handling and logging strategy
6110

62-
if (result.IsFailed)
63-
{
64-
return BadRequest(result.Errors.First().Message);
65-
}
66-
67-
return Ok("Logout successful. Refresh token invalidated.");
68-
}
69-
70-
// Google Login action to handle authentication via Google ID Token
71-
[HttpPost]
72-
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LoginResponseDTO))]
73-
public async Task<IActionResult> GoogleLogin([FromBody] string idToken)
74-
{
75-
var result = await Mediator.Send(new LoginGoogleQuery(idToken));
11+
Example implementation:
7612

77-
if (result.IsSuccess)
78-
{
79-
var user = result.Value; // Assume this contains user data after successful login
80-
var roles = user.Roles; // Make sure roles are part of the returned user object
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+
+ }
8124

82-
// Add claims based on roles after successful Google login
83-
var claims = new List<Claim>
84-
{
85-
new Claim(ClaimTypes.NameIdentifier, user.UserId),
86-
new Claim(ClaimTypes.Name, user.Username)
87-
};
25+
📝 Committable suggestion
8826

89-
// Add roles as claims
90-
foreach (var role in roles)
91-
{
92-
claims.Add(new Claim(ClaimTypes.Role, role));
93-
}
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.
9429

95-
var identity = new ClaimsIdentity(claims, "Google");
96-
var principal = new ClaimsPrincipal(identity);
97-
await HttpContext.SignInAsync(principal); // Sign in the user
98-
99-
return Ok(result.Value);
100-
}
101-
102-
return Unauthorized(new { message = result.Errors.FirstOrDefault()?.Message });
103-
}
104-
105-
// Example of protected route for admin access only
106-
[Authorize(Roles = "Admin")]
107-
[HttpGet("admin-dashboard")]
108-
public IActionResult AdminDashboard()
109-
{
110-
return Ok("Admin Dashboard");
111-
}
112-
113-
// Example of profile action with access control for regular users and admins
114-
[Authorize]
115-
[HttpGet("profile")]
116-
public IActionResult GetProfile()
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)
11742
{
118-
var currentUser = User.Identity.Name;
119-
120-
if (User.IsInRole("Admin"))
121-
{
122-
return NotFound(); // Redirect admin to 404 or similar (or redirect elsewhere if necessary)
123-
}
124-
125-
// Fetch and return the user's profile info
126-
return Ok("User profile data");
127-
}
128-
}
129-
}
43+
_logger = logger;
44+
}

0 commit comments

Comments
 (0)