@page "/change-password"
@attribute [Authorize]
@rendermode InteractiveServer
@using System.Security.Claims
@using CannedNet.Admin.Services
@inject AdminAuthService AuthService
@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime
Change Password
Change Password
@code {
[CascadingParameter] private Task? AuthState { get; set; }
private string currentPassword = "";
private string newPassword = "";
private string confirmNewPassword = "";
private bool saving;
private string? message;
private async Task DoChangePassword()
{
saving = true;
message = null;
try
{
if (string.IsNullOrWhiteSpace(currentPassword))
{
message = "Current password is required.";
return;
}
if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Length < 6)
{
message = "New password must be at least 6 characters.";
return;
}
if (newPassword != confirmNewPassword)
{
message = "New passwords do not match.";
return;
}
var state = await AuthState!;
var userIdClaim = state.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out var userId))
{
message = "Error: Could not identify user.";
return;
}
if (!AuthService.ChangePassword(userId, currentPassword, newPassword))
{
message = "Error: Current password is incorrect.";
return;
}
message = "Password changed successfully!";
currentPassword = "";
newPassword = "";
confirmNewPassword = "";
}
catch (Exception ex)
{
message = $"Error: {ex.Message}";
}
finally
{
saving = false;
}
}
}