Skip to content

Commit dc0d306

Browse files
committed
refactor: cleaned and removed duplicate endpoints in auth, roles, users and accounts endpoints
1 parent e792ea1 commit dc0d306

File tree

11 files changed

+969
-131
lines changed

11 files changed

+969
-131
lines changed

Controllers/AccountController.cs

Lines changed: 51 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Security.Claims;
2+
using AdminHubApi.Dtos.Auth;
23
using AdminHubApi.Dtos.UserManagement;
34
using AdminHubApi.Entities;
45
using AdminHubApi.Interfaces;
@@ -9,22 +10,27 @@
910
namespace AdminHubApi.Controllers;
1011

1112
[ApiController]
12-
[Route("api/[controller]")]
13-
[Authorize] // Requires authentication
13+
[Route("api/account")]
14+
[Authorize] // Everything here requires authentication
1415
public class AccountController : ControllerBase
1516
{
1617
private readonly IUserService _userService;
1718
private readonly UserManager<ApplicationUser> _userManager;
19+
private readonly IUserClaimsService _userClaimsService;
1820

1921
public AccountController(
2022
IUserService userService,
21-
UserManager<ApplicationUser> userManager)
23+
UserManager<ApplicationUser> userManager,
24+
IUserClaimsService userClaimsService)
2225
{
2326
_userService = userService;
2427
_userManager = userManager;
28+
_userClaimsService = userClaimsService;
2529
}
2630

27-
// GET api/account/profile
31+
/// <summary>
32+
/// Get the current user's profile
33+
/// </summary>
2834
[HttpGet("profile")]
2935
public async Task<IActionResult> GetProfile()
3036
{
@@ -39,7 +45,9 @@ public async Task<IActionResult> GetProfile()
3945
return Ok(response);
4046
}
4147

42-
// PUT api/account/profile
48+
/// <summary>
49+
/// Update the current user's profile
50+
/// </summary>
4351
[HttpPut("profile")]
4452
public async Task<IActionResult> UpdateProfile([FromBody] UpdateUserDto model)
4553
{
@@ -58,18 +66,49 @@ public async Task<IActionResult> UpdateProfile([FromBody] UpdateUserDto model)
5866
return Ok(response);
5967
}
6068

61-
// POST api/account/change-password
69+
/// <summary>
70+
/// Change the current user's password
71+
/// </summary>
6272
[HttpPost("change-password")]
63-
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordDto model)
73+
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequestDto model)
74+
{
75+
if (!ModelState.IsValid)
76+
return BadRequest(ModelState);
77+
78+
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
79+
if (string.IsNullOrEmpty(userId))
80+
return Unauthorized();
81+
82+
var user = await _userManager.FindByIdAsync(userId);
83+
if (user == null)
84+
return NotFound();
85+
86+
var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
87+
88+
if (!result.Succeeded)
89+
return BadRequest(new {
90+
message = "Password change failed",
91+
errors = result.Errors.Select(e => e.Description)
92+
});
93+
94+
return Ok(new { message = "Password changed successfully" });
95+
}
96+
97+
/// <summary>
98+
/// Get the current user's claims
99+
/// </summary>
100+
[HttpGet("claims")]
101+
public async Task<IActionResult> GetMyClaims()
64102
{
65103
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
66104
if (string.IsNullOrEmpty(userId))
67105
return Unauthorized();
68106

69-
var response = await _userService.ChangePasswordAsync(userId, model);
70-
if (!response.Succeeded)
71-
return BadRequest(response);
72-
73-
return Ok(response);
107+
var claims = await _userClaimsService.GetUserClaimsAsync(userId);
108+
109+
return Ok(new
110+
{
111+
Claims = claims.Select(c => new { Type = c.Type, Value = c.Value })
112+
});
74113
}
75114
}

Controllers/AuthController.cs

Lines changed: 20 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1-
using AdminHubApi.Dtos.Auth;
1+
using System.Security.Claims;
2+
using AdminHubApi.Dtos.Auth;
23
using AdminHubApi.Entities;
34
using AdminHubApi.Interfaces;
4-
using Microsoft.AspNetCore.Authorization;
55
using Microsoft.AspNetCore.Identity;
66
using Microsoft.AspNetCore.Mvc;
77
using Microsoft.Extensions.Options;
8-
using System.Security.Claims;
98

109
namespace AdminHubApi.Controllers;
1110

1211
[ApiController]
13-
[Route("/api/auth")]
12+
[Route("api/auth")]
1413
public class AuthController : ControllerBase
1514
{
1615
private readonly UserManager<ApplicationUser> _userManager;
@@ -33,32 +32,28 @@ public AuthController(
3332
_jwtSettings = jwtSettings.Value;
3433
}
3534

35+
/// <summary>
36+
/// Login with username and password
37+
/// </summary>
3638
[HttpPost("login")]
3739
public async Task<IActionResult> Login([FromBody] AuthRequestDto request)
3840
{
39-
// Check if model is valid
4041
if (!ModelState.IsValid)
4142
return BadRequest(ModelState);
4243

43-
// Check if user exists
4444
var user = await _userManager.FindByNameAsync(request.Username);
4545

4646
if (user == null)
4747
return Unauthorized(new { message = "Username or password is incorrect" });
4848

49-
// Verify password
5049
var result = await _signinManager.CheckPasswordSignInAsync(user, request.Password, false);
5150

52-
if (!result.Succeeded) // FIXED: Check for NOT succeeded
51+
if (!result.Succeeded)
5352
return Unauthorized(new { message = "Username or password is incorrect" });
5453

55-
// Get user roles
5654
var userRoles = await _userManager.GetRolesAsync(user);
57-
58-
// Generate token
5955
var token = await _tokenService.GenerateJwtTokenAsync(user, userRoles);
6056

61-
// Return token and user info
6257
return Ok(new AuthResponseDto
6358
{
6459
Token = token,
@@ -68,30 +63,28 @@ public async Task<IActionResult> Login([FromBody] AuthRequestDto request)
6863
});
6964
}
7065

66+
/// <summary>
67+
/// Register a new user
68+
/// </summary>
7169
[HttpPost("register")]
7270
public async Task<IActionResult> Register([FromBody] RegisterRequestDto request)
7371
{
74-
// Check if model is valid
7572
if (!ModelState.IsValid)
7673
return BadRequest(ModelState);
7774

78-
// Check if username already exists
7975
if (await _userManager.FindByNameAsync(request.Username) != null)
8076
return BadRequest(new { message = "Username already exists" });
8177

82-
// Check if email already exists
8378
if (await _userManager.FindByEmailAsync(request.Email) != null)
8479
return BadRequest(new { message = "Email already exists" });
8580

86-
// Create new user
8781
var user = new ApplicationUser
8882
{
8983
UserName = request.Username,
9084
Email = request.Email,
9185
SecurityStamp = Guid.NewGuid().ToString()
9286
};
9387

94-
// Add user to database
9588
var result = await _userManager.CreateAsync(user, request.Password);
9689

9790
if (!result.Succeeded)
@@ -100,7 +93,6 @@ public async Task<IActionResult> Register([FromBody] RegisterRequestDto request)
10093
errors = result.Errors.Select(e => e.Description)
10194
});
10295

103-
// Add user to default role
10496
if (!await _roleManager.RoleExistsAsync("User"))
10597
await _roleManager.CreateAsync(new IdentityRole("User"));
10698

@@ -109,63 +101,11 @@ public async Task<IActionResult> Register([FromBody] RegisterRequestDto request)
109101
return Ok(new { message = "User registered successfully" });
110102
}
111103

112-
[HttpGet("me")]
113-
[Authorize]
114-
public async Task<IActionResult> GetCurrentUser()
115-
{
116-
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
117-
118-
if (string.IsNullOrEmpty(userId))
119-
return Unauthorized();
120-
121-
var user = await _userManager.FindByIdAsync(userId);
122-
123-
if (user == null)
124-
return NotFound();
125-
126-
var roles = await _userManager.GetRolesAsync(user);
127-
var claims = await _userManager.GetClaimsAsync(user);
128-
129-
return Ok(new
130-
{
131-
Id = user.Id,
132-
Username = user.UserName,
133-
Email = user.Email,
134-
Roles = roles,
135-
Claims = claims.Select(c => new { Type = c.Type, Value = c.Value })
136-
});
137-
}
138-
139-
[HttpPost("change-password")]
140-
[Authorize]
141-
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequestDto request)
142-
{
143-
if (!ModelState.IsValid)
144-
return BadRequest(ModelState);
145-
146-
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
147-
148-
if (string.IsNullOrEmpty(userId))
149-
return Unauthorized();
150-
151-
var user = await _userManager.FindByIdAsync(userId);
152-
153-
if (user == null)
154-
return NotFound();
155-
156-
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword);
157-
158-
if (!result.Succeeded)
159-
return BadRequest(new {
160-
message = "Password change failed",
161-
errors = result.Errors.Select(e => e.Description)
162-
});
163-
164-
return Ok(new { message = "Password changed successfully" });
165-
}
166-
104+
/// <summary>
105+
/// Request a password reset link
106+
/// </summary>
167107
[HttpPost("forgot-password")]
168-
public async Task<IActionResult> ForgotPassword([FromBody] ChangePasswordRequestDto request)
108+
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequestDto request)
169109
{
170110
if (!ModelState.IsValid)
171111
return BadRequest(ModelState);
@@ -176,7 +116,6 @@ public async Task<IActionResult> ForgotPassword([FromBody] ChangePasswordRequest
176116
if (user == null)
177117
return Ok(new { message = "If your email is registered, you will receive a password reset link" });
178118

179-
// Generate password reset token
180119
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
181120

182121
// In a real app, you would send an email with the token
@@ -188,6 +127,9 @@ public async Task<IActionResult> ForgotPassword([FromBody] ChangePasswordRequest
188127
});
189128
}
190129

130+
/// <summary>
131+
/// Reset password using token
132+
/// </summary>
191133
[HttpPost("reset-password")]
192134
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequestDto request)
193135
{
@@ -210,6 +152,9 @@ public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequestDt
210152
return Ok(new { message = "Password reset successful" });
211153
}
212154

155+
/// <summary>
156+
/// Refresh an authentication token
157+
/// </summary>
213158
[HttpPost("refresh-token")]
214159
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequestDto request)
215160
{

0 commit comments

Comments
 (0)