支持所有角色验证原密码后修改本人密码
This commit is contained in:
parent
f2c3a73581
commit
db64c27267
@ -68,12 +68,30 @@ public sealed class UserAccess : BindableBase
|
||||
public bool Login(string name, string password)
|
||||
{
|
||||
var account = _accounts.FirstOrDefault(a => string.Equals(a.Name, name.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
if (account is null || !CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(account.Hash),
|
||||
Rfc2898DeriveBytes.Pbkdf2(password, Convert.FromBase64String(account.Salt), 210000, HashAlgorithmName.SHA256, 32))) return false;
|
||||
if (account is null || !VerifyPassword(account, password)) return false;
|
||||
SetSession(new(account.Name, account.Role));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证原密码和两次新密码后,只更新当前登录账号的密码;不改变角色或登录状态。
|
||||
/// 未登录、原密码错误或新密码校验失败时不写盘,持久化失败也不会修改内存账号。
|
||||
/// </summary>
|
||||
public void ChangeOwnPassword(string currentPassword, string newPassword, string confirmation)
|
||||
{
|
||||
if (_user is null) throw new UnauthorizedAccessException("请先登录后再修改密码");
|
||||
var account = _accounts.First(a => a.Name == _user.Name);
|
||||
if (!VerifyPassword(account, currentPassword)) throw new ArgumentException("原密码错误");
|
||||
if (newPassword != confirmation) throw new ArgumentException("两次输入的新密码不一致");
|
||||
var replacement = Create(account.Name, newPassword, account.Role);
|
||||
Persist(_accounts.Select(a => a == account ? replacement : a).ToList());
|
||||
}
|
||||
|
||||
// 登录与本人改密复用同一密码校验,避免通过登录接口验证原密码而意外改变会话。
|
||||
private static bool VerifyPassword(Account account, string password) =>
|
||||
CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(account.Hash),
|
||||
Rfc2898DeriveBytes.Pbkdf2(password, Convert.FromBase64String(account.Salt), 210000, HashAlgorithmName.SHA256, 32));
|
||||
|
||||
/// <summary>退出当前会话,通知命令与设置界面立即收回权限。</summary>
|
||||
public void Logout() => SetSession(null);
|
||||
|
||||
|
||||
@ -0,0 +1,48 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Media;
|
||||
using SopHelper.Models;
|
||||
|
||||
namespace SopHelper.VVMs.MainWindow;
|
||||
|
||||
/// <summary>所有角色共用的本人改密窗口,账号由当前会话确定,不提供修改他人密码的入口。</summary>
|
||||
public sealed class ChangePasswordWindow : Window
|
||||
{
|
||||
public ChangePasswordWindow()
|
||||
{
|
||||
var access = UserAccess.Current;
|
||||
Title = "修改密码"; Width = 440; SizeToContent = SizeToContent.Height; CanResize = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
var panel = new StackPanel { Margin = new Thickness(24), Spacing = 12 };
|
||||
Content = panel;
|
||||
panel.Children.Add(new TextBlock { Text = "修改密码", FontSize = 20 });
|
||||
panel.Children.Add(new TextBlock { Text = access.DisplayName });
|
||||
var original = PasswordInput("CurrentPasswordInput", "原密码");
|
||||
var password = PasswordInput("NewPasswordInput", "新密码(至少 8 个字符)");
|
||||
var confirmation = PasswordInput("ConfirmPasswordInput", "再次输入新密码");
|
||||
panel.Children.Add(original); panel.Children.Add(password); panel.Children.Add(confirmation);
|
||||
var status = new TextBlock { Name = "ChangePasswordStatus", TextWrapping = TextWrapping.Wrap };
|
||||
panel.Children.Add(status);
|
||||
var buttons = new StackPanel { Orientation = Avalonia.Layout.Orientation.Horizontal, Spacing = 12 };
|
||||
var save = new Button { Name = "SaveOwnPasswordButton", Content = "保存", IsDefault = true };
|
||||
var cancel = new Button { Content = "取消", IsCancel = true };
|
||||
buttons.Children.Add(save); buttons.Children.Add(cancel); panel.Children.Add(buttons);
|
||||
cancel.Click += (_, _) => Close();
|
||||
save.Click += (_, _) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
access.ChangeOwnPassword(original.Text ?? "", password.Text ?? "", confirmation.Text ?? "");
|
||||
// 保存成功后清空口令并保留成功反馈,避免用户误以为窗口关闭代表取消。
|
||||
original.Text = password.Text = confirmation.Text = "";
|
||||
original.IsEnabled = password.IsEnabled = confirmation.IsEnabled = save.IsEnabled = false;
|
||||
status.Text = "密码修改成功,下次登录请使用新密码。";
|
||||
cancel.Content = "完成";
|
||||
}
|
||||
catch (Exception error) { status.Text = error.Message; }
|
||||
};
|
||||
}
|
||||
|
||||
private static TextBox PasswordInput(string name, string placeholder) => new()
|
||||
{ Name = name, PlaceholderText = placeholder, PasswordChar = '●' };
|
||||
}
|
||||
@ -69,6 +69,7 @@
|
||||
<TextBlock Text="{Binding Access.DisplayName}" VerticalAlignment="Center" />
|
||||
<Button Content="登录 / 切换用户" Click="Login" IsEnabled="{Binding CanChangeAccount}" />
|
||||
<Button Content="退出登录" Click="Logout" IsEnabled="{Binding CanChangeAccount}" IsVisible="{Binding Access.IsAuthenticated}" />
|
||||
<Button Content="修改密码" Click="ChangePassword" IsEnabled="{Binding CanChangeAccount}" />
|
||||
<Button Content="人员管理" Click="ManageUsers" IsEnabled="{Binding CanChangeAccount}" />
|
||||
</StackPanel>
|
||||
<ContentControl Grid.Row="1" Grid.Column="1" prism:RegionManager.RegionName="ContentRegion" />
|
||||
|
||||
@ -23,5 +23,11 @@ public partial class MainWindow : Window
|
||||
private bool CanChange => DataContext is MainWindowViewModel model && model.CanChangeAccount;
|
||||
private async void Login(object? sender, RoutedEventArgs e) { if (CanChange) await new AccountWindow().ShowDialog(this); }
|
||||
private void Logout(object? sender, RoutedEventArgs e) { if (CanChange) UserAccess.Current.Logout(); }
|
||||
/// <summary>所有已登录角色均可修改本人密码;沿用停机后操作账号的交互约定。</summary>
|
||||
private async void ChangePassword(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (CanChange && UserAccess.Current.CheckPermission(UserAccess.Current.IsAuthenticated, "修改本人密码"))
|
||||
await new ChangePasswordWindow().ShowDialog(this);
|
||||
}
|
||||
private async void ManageUsers(object? sender, RoutedEventArgs e) { if (CanChange && UserAccess.Current.CheckPermission(UserAccess.Current.IsAdministrator, "管理人员")) await new AccountWindow(true).ShowDialog(this); }
|
||||
}
|
||||
|
||||
@ -108,7 +108,7 @@ internal static class Smoke
|
||||
await Task.Delay(150);
|
||||
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
|
||||
if (Environment.GetCommandLineArgs().Contains("--permissions-only"))
|
||||
{ await CheckPermissions(app, window); _exit = 0; return; }
|
||||
{ await CheckPermissions(app, window); await CheckOwnPasswords(window); _exit = 0; return; }
|
||||
// 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。
|
||||
UserAccess.Current.Setup("smoke-admin", "SmokePassword123");
|
||||
if(Environment.GetCommandLineArgs().Contains("--djev-shutdown-only"))
|
||||
@ -1694,6 +1694,66 @@ internal static class Smoke
|
||||
rendered.Save(Path.Combine(screenshots, "user-permissions.png"));
|
||||
}
|
||||
|
||||
/// <summary>检查全部角色的本人改密、失败时不落盘、角色隔离,以及真实窗口保存入口。</summary>
|
||||
private static async Task CheckOwnPasswords(Window window)
|
||||
{
|
||||
var access = UserAccess.Current;
|
||||
var path = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!, "workspace", "users.json");
|
||||
foreach (var role in Enum.GetValues<UserRole>())
|
||||
access.SaveUser("self-" + role, "OriginalPassword123", role);
|
||||
access.Logout();
|
||||
bool Rejected(Action action)
|
||||
{
|
||||
try { action(); return false; }
|
||||
catch (Exception error) when (error is UnauthorizedAccessException or ArgumentException) { return true; }
|
||||
}
|
||||
Check(Rejected(() => access.ChangeOwnPassword("", "UpdatedPassword123", "UpdatedPassword123")), "未登录不能修改本人密码");
|
||||
foreach (var role in Enum.GetValues<UserRole>())
|
||||
{
|
||||
var name = "self-" + role;
|
||||
Check(access.Login(name, "OriginalPassword123"), "本人改密前登录:" + role);
|
||||
var before = File.ReadAllText(path);
|
||||
Check(Rejected(() => access.ChangeOwnPassword("wrong", "UpdatedPassword123", "UpdatedPassword123"))
|
||||
&& Rejected(() => access.ChangeOwnPassword("OriginalPassword123", "UpdatedPassword123", "different"))
|
||||
&& Rejected(() => access.ChangeOwnPassword("OriginalPassword123", "short", "short"))
|
||||
&& File.ReadAllText(path) == before, "原密码、确认密码和密码长度校验失败均不写盘:" + role);
|
||||
access.ChangeOwnPassword("OriginalPassword123", "UpdatedPassword123", "UpdatedPassword123");
|
||||
var saved = new UserAccess(path);
|
||||
Check(access.User == new UserSummary(name, role) && !saved.Login(name, "OriginalPassword123")
|
||||
&& saved.Login(name, "UpdatedPassword123") && saved.User!.Role == role,
|
||||
"三类角色均可改密,新密码持久化且原密码失效、身份角色保持:" + role);
|
||||
Check(saved.Login("admin", "AdminPassword123"), "本人改密不改变其他账号密码:" + role);
|
||||
}
|
||||
await Task.Delay(40);
|
||||
window.GetVisualDescendants().OfType<Button>().Single(b => Equals(b.Content, "修改密码"))
|
||||
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
await Task.Delay(40);
|
||||
var dialog = window.OwnedWindows.OfType<SopHelper.VVMs.MainWindow.ChangePasswordWindow>().Single();
|
||||
TextBox Input(string name) => dialog.GetVisualDescendants().OfType<TextBox>().Single(b => b.Name == name);
|
||||
var save = dialog.GetVisualDescendants().OfType<Button>().Single(b => b.Name == "SaveOwnPasswordButton");
|
||||
var status = dialog.GetVisualDescendants().OfType<TextBlock>().Single(b => b.Name == "ChangePasswordStatus");
|
||||
Input("CurrentPasswordInput").Text = "UpdatedPassword123";
|
||||
Input("NewPasswordInput").Text = "UiChangedPassword123";
|
||||
Input("ConfirmPasswordInput").Text = "mismatch";
|
||||
save.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
Check(status.Text!.Contains("不一致") && save.IsEnabled, "改密窗口显示两次密码不一致并允许重试");
|
||||
Input("ConfirmPasswordInput").Text = "UiChangedPassword123";
|
||||
save.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
await Task.Delay(40);
|
||||
Check(status.Text!.Contains("成功") && !save.IsEnabled
|
||||
&& dialog.GetVisualDescendants().OfType<TextBox>().All(b => b.PasswordChar == '●' && b.Text == "")
|
||||
&& new UserAccess(path).Login("self-Operator", "UiChangedPassword123"),
|
||||
"操作员通过主窗口修改本人密码,保存成功后清空密码框并显示成功提示");
|
||||
using (var rendered = new RenderTargetBitmap(new PixelSize(440, (int)dialog.Bounds.Height)))
|
||||
{
|
||||
rendered.Render(dialog);
|
||||
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
|
||||
rendered.Save(Path.Combine(output, "change-own-password.png"));
|
||||
}
|
||||
dialog.Close();
|
||||
access.Login("admin", "AdminPassword123");
|
||||
}
|
||||
|
||||
private static void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS: "+message);}
|
||||
}
|
||||
internal sealed class FakeCamera : ICameraService
|
||||
|
||||
Loading…
Reference in New Issue
Block a user