Add ability for admins to change user password

Ref #28
media
Pat Hartl 2023-09-17 17:26:48 -05:00
parent f94e5f63a8
commit 07a41aeaf5
2 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,61 @@
@page "/Settings/Users/{id:guid}/ChangePassword"
@layout SettingsLayout
@inject UserManager<User> UserManager
@inject IMessageService MessageService
@attribute [Authorize(Roles = "Administrator")]
<PageHeader Title="Change Password" Subtitle="@User.UserName" />
<div style="padding: 0 24px;">
<Form Model="Model" Layout="@FormLayout.Vertical">
<FormItem Label="New Password">
<InputPassword @bind-Value="context.NewPassword" />
</FormItem>
<FormItem Label="Confirm Password">
<InputPassword @bind-Value="context.NewPasswordConfirm" />
</FormItem>
<FormItem>
<Button OnClick="Change" Type="@ButtonType.Primary">Change</Button>
</FormItem>
</Form>
</div>
@code {
[Parameter] public Guid Id { get; set; }
User User;
ChangePasswordModel Model = new ChangePasswordModel();
protected override async Task OnInitializedAsync()
{
if (Id != Guid.Empty)
{
User = await UserManager.FindByIdAsync(Id.ToString());
}
}
async void Change()
{
try
{
var token = await UserManager.GeneratePasswordResetTokenAsync(User);
if (Model.NewPassword == Model.NewPasswordConfirm)
await UserManager.ResetPasswordAsync(User, token, Model.NewPassword);
await MessageService.Success("Password changed!");
}
catch
{
await MessageService.Error("The user's password could not be changed");
}
}
public class ChangePasswordModel
{
public string NewPassword { get; set; }
public string NewPasswordConfirm { get; set; }
}
}

View File

@ -4,6 +4,7 @@
@inject UserManager<User> UserManager @inject UserManager<User> UserManager
@inject RoleManager<Role> RoleManager @inject RoleManager<Role> RoleManager
@inject IMessageService MessageService @inject IMessageService MessageService
@inject NavigationManager NavigationManager
@attribute [Authorize(Roles = "Administrator")] @attribute [Authorize(Roles = "Administrator")]
<PageHeader Title="Users" /> <PageHeader Title="Users" />
@ -37,6 +38,12 @@
} }
</SpaceItem> </SpaceItem>
<SpaceItem>
<Tooltip Title="Change Password">
<Button Icon="@IconType.Outline.Key" Type="@ButtonType.Text" OnClick="() => ChangePassword(context)" />
</Tooltip>
</SpaceItem>
<SpaceItem> <SpaceItem>
@if (!context.Roles.Any(r => r == "Administrator")) @if (!context.Roles.Any(r => r == "Administrator"))
{ {
@ -151,4 +158,9 @@
await MessageService.Success($"Deleted {user.UserName}!"); await MessageService.Success($"Deleted {user.UserName}!");
} }
} }
private void ChangePassword(UserViewModel user)
{
NavigationManager.NavigateTo($"/Settings/Users/{user.Id}/ChangePassword", true);
}
} }