mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat: password resets
fix: frontend docker file chore: format via csharpier again
This commit is contained in:
@@ -52,9 +52,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
var existingUser = await _userService.GetByUsername(request.Username);
|
||||
if (existingUser != null)
|
||||
return Conflict(new { success = false, message = "Username already exists." });
|
||||
if (!string.IsNullOrEmpty(request.Email))
|
||||
|
||||
var normalizedEmail = UserService.NormalizeEmail(request.Email);
|
||||
if (normalizedEmail != null)
|
||||
{
|
||||
var existingEmailUser = await _userService.GetByEmail(request.Email);
|
||||
var existingEmailUser = await _userService.GetByEmail(normalizedEmail);
|
||||
if (existingEmailUser != null)
|
||||
return Conflict(new { success = false, message = "Email already in use." });
|
||||
}
|
||||
@@ -64,13 +66,16 @@ namespace SharpbinV3.Server.Controllers
|
||||
User user;
|
||||
try
|
||||
{
|
||||
user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
|
||||
user = await _authService.CreateUser(request.Username, request.Password, normalizedEmail, request.DisplayName);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
if (await _userService.GetByUsername(request.Username) != null)
|
||||
return Conflict(new { success = false, message = "Username already exists." });
|
||||
|
||||
if (normalizedEmail != null && await _userService.GetByEmail(normalizedEmail) != null)
|
||||
return Conflict(new { success = false, message = "Email already in use." });
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
@@ -178,6 +183,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
{
|
||||
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
|
||||
registration_enabled = authSettings.Registration_Enabled,
|
||||
admins_require_2fa = authSettings.Admins_Require_2FA,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -349,5 +355,247 @@ namespace SharpbinV3.Server.Controllers
|
||||
else
|
||||
return BadRequest(new { success = false, message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[EnableRateLimiting("Strict")]
|
||||
[Route("password/forgot")]
|
||||
public async Task<IActionResult> RequestPasswordReset([FromBody] PasswordResetRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
|
||||
return BadRequest(new { success = false, message = "Verification failed." });
|
||||
|
||||
var result = await _authService.RequestPasswordResetForEmail(request.Email);
|
||||
if (!result.success)
|
||||
return Ok(new { success = true, message = "If an account exists for that email, a reset link has been sent." });
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("password/reset-info")]
|
||||
public async Task<IActionResult> GetPasswordResetInfo([FromQuery] string token)
|
||||
{
|
||||
var info = await _authService.GetPasswordResetTokenInfo(token);
|
||||
if (!info.success || info.user == null)
|
||||
return BadRequest(new { success = false, message = info.message });
|
||||
if (info.blocked)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
username = info.username,
|
||||
requiresTotp = info.requiresTotp,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Route("password/reset")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ResetPassword([FromBody] PasswordResetDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var result = await _authService.ResetPasswordWithToken(request.Token, request.NewPassword, request.TotpCode);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.message == "2FA is required to perform this action.")
|
||||
return StatusCode(403, new { success = false, message = result.message });
|
||||
return BadRequest(new { success = false, message = result.message });
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[Route("password/change")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> ChangePassword([FromBody] PasswordChangeDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var result = await _authService.ChangeOwnPassword(user, request.CurrentPassword, request.NewPassword, request.TotpCode);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.message == "2FA is required to perform this action.")
|
||||
return StatusCode(403, new { success = false, message = result.message });
|
||||
return BadRequest(new { success = false, message = result.message });
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[Route("password/admin-reset-link/{uuid}")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> AdminGeneratePasswordResetLink(Guid uuid, [FromBody] AdminPasswordResetLinkDto request)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
if (!jwtUser.Roles.HasFlag(Role.Admin))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
|
||||
|
||||
var targetUser = await _userService.GetByUUID(uuid);
|
||||
if (targetUser == null)
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (jwtUser.TotpEnabled)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(request.TotpCode)
|
||||
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = request.TotpCode })
|
||||
)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
else if (options.Value.Admins_Require_2FA)
|
||||
{
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
}
|
||||
|
||||
var result = await _authService.GeneratePasswordResetLink(targetUser, sendEmail: !string.IsNullOrWhiteSpace(targetUser.Email));
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
message = result.message,
|
||||
resetLink = result.resetLink,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Route("email/resend-verification")]
|
||||
public async Task<IActionResult> ResendEmailVerification()
|
||||
{
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var result = await _authService.ResendEmailVerification(user);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "JwtOnly")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
[Route("email/change")]
|
||||
public async Task<IActionResult> ChangeEmail([FromBody] ChangeEmailDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
if (user == null)
|
||||
return BadRequest(new { success = false, message = "User not found." });
|
||||
|
||||
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
|
||||
if (totpEnabled)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(request.TotpCode)
|
||||
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode })
|
||||
)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
|
||||
var result = await _authService.RequestEmailChange(user, request.Email);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
[Route("api/[controller]")]
|
||||
public class UserController(
|
||||
UserService userService,
|
||||
AuthService authService,
|
||||
AppDbContext db,
|
||||
TotpVerificationProvider totp,
|
||||
VerificationService verificationService,
|
||||
@@ -30,6 +31,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
) : ControllerBase
|
||||
{
|
||||
private readonly UserService _userService = userService;
|
||||
private readonly AuthService _authService = authService;
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly TotpVerificationProvider _totp = totp;
|
||||
private readonly VerificationService _verificationService = verificationService;
|
||||
@@ -130,12 +132,12 @@ namespace SharpbinV3.Server.Controllers
|
||||
if ((updatedUser.Roles.HasValue || updatedUser.IsBanned.HasValue) && !actorIsAdmin)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
|
||||
|
||||
if (updatedUser.Email != null)
|
||||
return BadRequest(new { success = false, message = "Use the email change endpoint to update email addresses." });
|
||||
|
||||
bool isSensitiveUpdate =
|
||||
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != targetUser.Roles) // updating roles
|
||||
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned) // updating ban status
|
||||
|| (
|
||||
updatedUser.Email != null && updatedUser.Email != targetUser.Email // updating email
|
||||
);
|
||||
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned); // updating ban status
|
||||
|
||||
if (actorIsAdmin && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
@@ -167,7 +169,6 @@ namespace SharpbinV3.Server.Controllers
|
||||
targetUser.DisplayName = updatedUser.DisplayName ?? targetUser.DisplayName;
|
||||
if (actorIsAdmin || isSelfUpdate)
|
||||
{
|
||||
targetUser.Email = updatedUser.Email ?? targetUser.Email;
|
||||
targetUser.Visibility = updatedUser.Visibility ?? targetUser.Visibility;
|
||||
}
|
||||
if (actorIsAdmin)
|
||||
@@ -193,6 +194,8 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||
|
||||
var isSelfDelete = user.UUID == jwtUser.UUID;
|
||||
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
if (user.Roles.HasFlag(Role.Admin))
|
||||
@@ -208,22 +211,70 @@ namespace SharpbinV3.Server.Controllers
|
||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (isSelfDelete && user.EmailVerified && !string.IsNullOrWhiteSpace(user.Email))
|
||||
{
|
||||
if (
|
||||
string.IsNullOrEmpty(dto.Token)
|
||||
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
|
||||
)
|
||||
if (string.IsNullOrEmpty(dto.Token) || !await _authService.VerifyAccountDeletionToken(user, dto.Token))
|
||||
{
|
||||
return Unauthorized(new { message = "Invalid verification token." });
|
||||
return Unauthorized(new { message = "Invalid account deletion verification token." });
|
||||
}
|
||||
}
|
||||
|
||||
var deletedEmail = user.EmailVerified ? user.Email : null;
|
||||
var deletedUsername = user.Username;
|
||||
_db.Users.Remove(user);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(deletedEmail))
|
||||
await _authService.SendAccountDeletedNotification(deletedEmail, deletedUsername);
|
||||
|
||||
return Ok(new { message = "User deleted successfully." });
|
||||
}
|
||||
|
||||
[HttpPost("uuid/{uuid}/delete-verification")]
|
||||
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||
[EnableRateLimiting("Sensitive")]
|
||||
public async Task<IActionResult> RequestDeleteVerification(Guid uuid)
|
||||
{
|
||||
var jwtUser = HttpContext.GetJwtUser()!;
|
||||
if (jwtUser.UUID != uuid)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (user.Roles.HasFlag(Role.Admin))
|
||||
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
|
||||
|
||||
if (jwtUser.TotpEnabled)
|
||||
return BadRequest(new { success = false, message = "Use TOTP to delete this account." });
|
||||
|
||||
if (!user.EmailVerified || string.IsNullOrWhiteSpace(user.Email))
|
||||
return BadRequest(new { success = false, message = "A verified email address is required for email deletion verification." });
|
||||
|
||||
var result = await _authService.RequestAccountDeletionVerification(user);
|
||||
if (!result.success)
|
||||
{
|
||||
if (result.retryAfter.HasValue)
|
||||
{
|
||||
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||
return StatusCode(
|
||||
StatusCodes.Status429TooManyRequests,
|
||||
new
|
||||
{
|
||||
success = false,
|
||||
message = result.message,
|
||||
retryAfter = result.retryAfter,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return BadRequest(new { success = false, message = result.message });
|
||||
}
|
||||
|
||||
return Ok(new { success = true, message = result.message });
|
||||
}
|
||||
|
||||
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
|
||||
{
|
||||
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
|
||||
|
||||
Reference in New Issue
Block a user