Skip to content

Commit 8cff916

Browse files
changes
1 parent f54311a commit 8cff916

File tree

8 files changed

+263
-127
lines changed

8 files changed

+263
-127
lines changed

api/Controllers/Auth/v1/AuthController.cs

Lines changed: 93 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,32 @@
1111
namespace api.Controllers.Auth.v1;
1212

1313
[ApiController]
14-
[Route("api/auth")]
14+
[Route("api/v{version:apiVersion}/auth")]
1515
[ApiVersion("1")]
16-
public class AuthController(IAuthService service) : ControllerBase
16+
public class AuthController(IAuthService service, ILogger<AuthController> logger) : ControllerBase
1717
{
1818
private readonly IAuthService _service = service ?? throw new ArgumentNullException(nameof(service));
19+
private readonly ILogger<AuthController> _logger = logger;
1920

2021

2122
[HttpGet("me")]
2223
[Authorize]
24+
[ProducesResponseType(typeof(UserDto) ,200)]
25+
[ProducesResponseType(401)]
26+
[ProducesResponseType(404)]
2327
public async Task<IActionResult> AuthMe()
2428
{
2529

2630

2731
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
28-
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out Guid userId))
32+
if (string.IsNullOrEmpty(userIdClaim) )
2933
{
30-
return Unauthorized("Invalid token");
34+
return Unauthorized("Invalid or missing user token");
35+
}
36+
37+
if (!Guid.TryParse(userIdClaim, out Guid userId))
38+
{
39+
return Unauthorized("Invalid user identifier in token");
3140
}
3241

3342
UserDto? response= await _service.GetById(userId);
@@ -39,66 +48,127 @@ public async Task<IActionResult> AuthMe()
3948
}
4049

4150
[HttpPost("register")]
51+
[ProducesResponseType(typeof(UserDto), 200)]
52+
[ProducesResponseType(400)]
53+
[ProducesResponseType(500)]
4254
public async Task<IActionResult> Register([FromBody] RegisterRequestDto requestDto)
4355
{
4456
if (!ModelState.IsValid)
4557
{
4658
return BadRequest(ModelState);
4759
}
4860

49-
var existingUser = await _service.GetByEmail(requestDto.email);
50-
if (existingUser is not null)
61+
try
5162
{
52-
return BadRequest("User with this email already exists");
53-
}
63+
var existingUser = await _service.GetByEmail(requestDto.email);
64+
if (existingUser is not null)
65+
{
66+
return BadRequest("Registration failed. Please check your details and try again.");
67+
}
5468

55-
var response = await _service.Register(requestDto.lastName, requestDto.firstName, requestDto.password, requestDto.email);
56-
if (response==null)
69+
var response = await _service.Register(requestDto.lastName, requestDto.firstName, requestDto.password, requestDto.email);
70+
if (response==null)
71+
{
72+
return StatusCode(500, "Registration failed. Please try again later.");
73+
}
74+
75+
76+
return Ok(response);
77+
}
78+
catch (Exception ex)
5779
{
58-
return StatusCode(500, "Something went wrong while creating the user");
80+
_logger.LogError(ex, "Error during user registration for email: {Email}", requestDto.email);
81+
return StatusCode(500, "Registration failed. Please try again later.");
5982
}
6083

61-
62-
return Ok(response);
6384
}
6485

6586

6687
[HttpPost("login")]
88+
[ProducesResponseType(200)]
89+
[ProducesResponseType(400)]
90+
[ProducesResponseType(429)]
6791
public async Task<IActionResult> Login([FromBody] LoginRequestDto requestDto)
6892
{
6993
if (!ModelState.IsValid)
7094
{
7195
return BadRequest(ModelState);
7296
}
7397

74-
var response = await _service.Authenticate(requestDto.email, requestDto.password);
98+
try
99+
{
100+
var response = await _service.Authenticate(requestDto.email, requestDto.password);
101+
102+
if (response==null)
103+
{
104+
return BadRequest("Invalid credentials. Please check your email and password.");
105+
}
75106

76-
if (response==null)
107+
return Ok(response);
108+
}
109+
catch (Exception ex)
77110
{
78-
return BadRequest("Invalid email or password");
111+
_logger.LogError(ex, "Error during authentication for email: {Email}", requestDto.email);
112+
return StatusCode(500, "Authentication failed. Please try again later.");
79113
}
80114

81-
return Ok(response);
115+
82116
}
83117

84118
[Authorize]
85119
[HttpPost("logout")]
120+
[ProducesResponseType(200)]
121+
[ProducesResponseType(401)]
122+
[ProducesResponseType(500)]
86123
public async Task<IActionResult> Logout( )
87124

88125
{
89126
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
90-
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out Guid userId))
127+
128+
if (string.IsNullOrEmpty(userIdClaim))
91129
{
92-
return Unauthorized("Invalid token");
130+
return Unauthorized("Invalid or missing user token");
93131
}
94132

95-
bool response = await _service.Logout(userId);
96-
if (!response)
133+
if (!Guid.TryParse(userIdClaim, out Guid userId))
97134
{
98-
return StatusCode(500, "Logout failed");
135+
return Unauthorized("Invalid user identifier in token");
99136
}
100137

101-
return Ok(new { message = "Logged out successfully" });
138+
try
139+
{
140+
bool response = await _service.Logout(userId);
141+
if (!response)
142+
{
143+
return StatusCode(500, "Logout failed. Please try again.");
144+
}
145+
146+
return Ok(new { message = "Successfully logged out", timestamp = DateTime.UtcNow });
147+
}
148+
catch (Exception ex)
149+
{
150+
_logger.LogError(ex, "Error during logout for user: {UserId}", userId);
151+
return StatusCode(500, "Logout failed. Please try again.");
152+
}
153+
154+
}
155+
156+
[HttpGet("status")]
157+
[Authorize]
158+
[ProducesResponseType(200)]
159+
[ProducesResponseType(401)]
160+
public IActionResult GetAuthStatus()
161+
{
162+
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
163+
var emailClaim = User.FindFirst(ClaimTypes.Email)?.Value;
164+
165+
return Ok(new
166+
{
167+
isAuthenticated = true,
168+
userId = userIdClaim,
169+
email = emailClaim,
170+
timestamp = DateTime.UtcNow
171+
});
102172
}
103173

104174

api/DTOs/Auth/Requests/LoginRequestDto.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ namespace api.DTOs.Auth.Requests;
44

55
public class LoginRequestDto
66
{
7-
[Required]
8-
[EmailAddress]
9-
public string email { get; set; }
7+
[Required(ErrorMessage = "Email is required")]
8+
[EmailAddress(ErrorMessage = "Invalid email format")]
9+
public string email { get; set; } = string.Empty;
1010

11-
[Required]
12-
public string password { get; set; }
11+
[Required(ErrorMessage = "Password is required")]
12+
public string password { get; set; } = string.Empty;
1313
}

api/DTOs/Auth/Requests/RegisterRequestDto.cs

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,23 @@
33
namespace api.DTOs.Auth.Requests;
44
public class RegisterRequestDto
55
{
6-
[Required]
7-
public string firstName { get; set; }
6+
[Required(ErrorMessage = "First name is required")]
7+
[StringLength(50, ErrorMessage = "First name cannot exceed 50 characters")]
8+
public string firstName { get; set; } = string.Empty;
89

9-
[Required]
10-
public string lastName { get; set; }
10+
[Required(ErrorMessage = "Last name is required")]
11+
[StringLength(50, ErrorMessage = "Last name cannot exceed 50 characters")]
12+
public string lastName { get; set; } = string.Empty;
1113

12-
[Required]
13-
[EmailAddress]
14-
public string email { get; set; }
14+
[Required(ErrorMessage = "Email is required")]
15+
[EmailAddress(ErrorMessage = "Invalid email format")]
16+
[StringLength(100, ErrorMessage = "Email cannot exceed 100 characters")]
17+
public string email { get; set; } = string.Empty;
1518

16-
[Required]
17-
[MinLength(12)]
18-
public string password { get; set; }
19+
[Required(ErrorMessage = "Password is required")]
20+
[StringLength(100, MinimumLength = 8, ErrorMessage = "Password must be between 8 and 100 characters")]
21+
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]",
22+
ErrorMessage = "Password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character")]
23+
public string password { get; set; } = string.Empty;
1924
}
2025

api/DTOs/Auth/Responses/AuthTokenResponse.cs

Lines changed: 0 additions & 8 deletions
This file was deleted.

api/Helpers/JWTMiddleware.cs

Lines changed: 0 additions & 63 deletions
This file was deleted.

0 commit comments

Comments
 (0)