在设置页添加自动登录和用户选择
This commit is contained in:
parent
d42e3a0312
commit
a3e90fa718
@ -120,10 +120,8 @@ public partial class App : PrismApplication
|
||||
/// <summary>授权通过后才创建导航与业务主窗口,并安装授权巡检及原有生命周期清理。</summary>
|
||||
private MainWindow CreateAuthorizedShell()
|
||||
{
|
||||
#if DEBUG
|
||||
// 许可通过后、创建业务界面前建立调试会话,退出登录后仍可手动切换身份。
|
||||
UserAccess.Current.SignInAsDebugAdministrator();
|
||||
#endif
|
||||
// 许可通过后、创建业务界面前读取自动登录选择;手动退出后不会再次触发启动登录。
|
||||
UserAccess.Current.SignInAtStartup();
|
||||
var navigation=Container.Resolve<NavigationModel>();
|
||||
// Index 决定侧栏顺序;显示名称和导航目标来自页面的 NavigationPageAttribute。
|
||||
foreach(var type in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute<NavigationPageAttribute>()!=null)
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Prism.Mvvm;
|
||||
using SopHelper.Presentation;
|
||||
|
||||
@ -14,10 +15,12 @@ public sealed record UserSummary(string Name, UserRole Role)
|
||||
public override string ToString() => $"{Name}({UserAccess.RoleName(Role)})";
|
||||
}
|
||||
|
||||
/// <summary>管理本地账号、密码校验及当前会话。密码使用独立随机盐的 PBKDF2,不保存明文。</summary>
|
||||
/// <summary>管理本地账号、启动自动登录及当前会话。密码使用独立随机盐的 PBKDF2,不保存明文。</summary>
|
||||
public sealed class UserAccess : BindableBase
|
||||
{
|
||||
private sealed record Account(string Name, UserRole Role, string Salt, string Hash);
|
||||
// 自动登录标记随账号原子保存;旧文件没有该字段时默认为关闭。
|
||||
private sealed record Account(string Name, UserRole Role, string Salt, string Hash,
|
||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] bool AutoLogin = false);
|
||||
private readonly string _path;
|
||||
private List<Account> _accounts;
|
||||
private UserSummary? _user;
|
||||
@ -29,6 +32,10 @@ public sealed class UserAccess : BindableBase
|
||||
public bool NeedsSetup => _accounts.Count == 0;
|
||||
public string DisplayName => _user?.ToString() ?? "未登录";
|
||||
public event Action? SessionChanged;
|
||||
/// <summary>账号文件写入成功后通知设置页刷新可选账号与启动配置。</summary>
|
||||
public event Action? AccountsChanged;
|
||||
/// <summary>返回下次启动时使用的账号名;未启用时为空。</summary>
|
||||
public string? AutoLoginUserName => _accounts.FirstOrDefault(account => account.AutoLogin)?.Name;
|
||||
/// <summary>向当前主窗口请求显示权限提示,账号服务不依赖具体窗口实现。</summary>
|
||||
public event Action<string>? PermissionDenied;
|
||||
|
||||
@ -55,14 +62,22 @@ public sealed class UserAccess : BindableBase
|
||||
public static string RoleName(UserRole role) => role switch
|
||||
{ UserRole.Administrator => "管理员", UserRole.Engineer => "工艺师", _ => "操作员" };
|
||||
|
||||
#if DEBUG
|
||||
/// <summary>调试启动时使用首个已有管理员建立会话;新工作区仍走首次初始化流程。</summary>
|
||||
internal void SignInAsDebugAdministrator()
|
||||
/// <summary>仅在授权后的启动入口调用;按已保存的账号及其角色建立初始会话。</summary>
|
||||
internal void SignInAtStartup()
|
||||
{
|
||||
if (!IsAuthenticated && _accounts.FirstOrDefault(account => account.Role == UserRole.Administrator) is { } administrator)
|
||||
SetSession(new(administrator.Name, administrator.Role));
|
||||
if (!IsAuthenticated && _accounts.FirstOrDefault(account => account.AutoLogin) is { } account)
|
||||
SetSession(new(account.Name, account.Role));
|
||||
}
|
||||
|
||||
/// <summary>仅管理员可设置下次启动使用的已有账号;传入 null 表示关闭,当前会话保持原状。</summary>
|
||||
public void SaveAutoLogin(string? userName)
|
||||
{
|
||||
RequireAdministrator("配置自动登录");
|
||||
var selected = userName is null ? null : _accounts.FirstOrDefault(account =>
|
||||
string.Equals(account.Name, userName, StringComparison.OrdinalIgnoreCase));
|
||||
if (userName is not null && selected is null) throw new ArgumentException("请选择已有用户");
|
||||
Persist(_accounts.Select(account => account with { AutoLogin = account == selected }).ToList());
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>仅在没有账号时创建首个管理员并登录,无内置默认口令。</summary>
|
||||
public void Setup(string name, string password)
|
||||
@ -83,7 +98,7 @@ public sealed class UserAccess : BindableBase
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证原密码和两次新密码后,只更新当前登录账号的密码;不改变角色或登录状态。
|
||||
/// 验证原密码和两次新密码后,更新当前登录账号的密码并撤销其自动登录;保留当前角色和会话。
|
||||
/// 未登录、原密码错误或新密码校验失败时不写盘,持久化失败也不会修改内存账号。
|
||||
/// </summary>
|
||||
public void ChangeOwnPassword(string currentPassword, string newPassword, string confirmation)
|
||||
@ -115,13 +130,15 @@ public sealed class UserAccess : BindableBase
|
||||
return _accounts.Select(a => new UserSummary(a.Name, a.Role)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>新增账号或修改角色/重置密码;修改已有账号时留空密码表示保留。</summary>
|
||||
/// <summary>新增账号或修改角色/重置密码;修改已有账号时留空密码表示保留。角色或密码变更时撤销该账号的自动登录。</summary>
|
||||
public void SaveUser(string name, string password, UserRole role)
|
||||
{
|
||||
RequireAdministrator();
|
||||
name = name.Trim();
|
||||
var existing = _accounts.FirstOrDefault(a => string.Equals(a.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
var replacement = existing is not null && password.Length == 0 ? existing with { Role = role } : Create(name, password, role);
|
||||
var replacement = existing is not null && password.Length == 0
|
||||
? existing with { Role = role, AutoLogin = existing.Role == role && existing.AutoLogin }
|
||||
: Create(name, password, role);
|
||||
if (!Enum.IsDefined(role)) throw new ArgumentException("无效角色");
|
||||
var next = _accounts.Where(a => a != existing).Append(replacement).ToList();
|
||||
EnsureAdministrator(next);
|
||||
@ -148,8 +165,8 @@ public sealed class UserAccess : BindableBase
|
||||
return new(name, role, Convert.ToBase64String(salt), Convert.ToBase64String(
|
||||
Rfc2898DeriveBytes.Pbkdf2(password, salt, 210000, HashAlgorithmName.SHA256, 32)));
|
||||
}
|
||||
private void RequireAdministrator()
|
||||
{ if (!IsAdministrator) throw new UnauthorizedAccessException("仅管理员可以管理人员"); }
|
||||
private void RequireAdministrator(string operation = "管理人员")
|
||||
{ if (!IsAdministrator) throw new UnauthorizedAccessException($"仅管理员可以{operation}"); }
|
||||
private static void EnsureAdministrator(List<Account> accounts)
|
||||
{ if (!accounts.Any(a => a.Role == UserRole.Administrator)) throw new InvalidOperationException("至少保留一名管理员"); }
|
||||
|
||||
@ -161,6 +178,7 @@ public sealed class UserAccess : BindableBase
|
||||
try { File.WriteAllText(temp, JsonSerializer.Serialize(accounts, new JsonSerializerOptions { WriteIndented = true })); File.Move(temp, _path, true); }
|
||||
finally { if (File.Exists(temp)) File.Delete(temp); }
|
||||
_accounts = accounts;
|
||||
AccountsChanged?.Invoke();
|
||||
}
|
||||
private void SetSession(UserSummary? user)
|
||||
{
|
||||
|
||||
@ -3,6 +3,19 @@
|
||||
<StackPanel Margin="10" MaxWidth="760" HorizontalAlignment="Stretch" Spacing="12">
|
||||
<TextBlock Text="运行设置" Classes="Title" />
|
||||
<TextBlock Text="配置相机、配方和手部采集参数,运行期间不可修改。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<!-- 自动登录由管理员保存,下拉框在开关打开后显示,配置在下次启动时读取。 -->
|
||||
<Border Classes="panel" IsVisible="{Binding Access.IsAdministrator}" IsEnabled="{Binding CanChangeModels}">
|
||||
<StackPanel Spacing="8">
|
||||
<ToggleSwitch x:Name="AutoLoginToggle" Content="自动登录" OnContent="开" OffContent="关" />
|
||||
<Grid ColumnDefinitions="Auto,*" IsVisible="{Binding #AutoLoginToggle.IsChecked}">
|
||||
<TextBlock Text="自动登录用户" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<ComboBox x:Name="AutoLoginUserInput" Grid.Column="1" PlaceholderText="请选择用户" />
|
||||
</Grid>
|
||||
<Button x:Name="SaveAutoLoginButton" Content="保存自动登录设置" Click="SaveAutoLogin" HorizontalAlignment="Left" />
|
||||
<TextBlock Text="保存后,下次启动时使用所选账号直接登录。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<TextBlock x:Name="AutoLoginStatus" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="panel">
|
||||
<StackPanel>
|
||||
<TextBlock Text="相机与配方" Classes="Title" />
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 运行设置视图:提供抽帧、自动复位、djev 启动档位和请求超时等全局参数的编辑入口。
|
||||
// 运行设置视图:提供自动登录、相机与配方、djev 启动档位等全局配置的编辑入口。
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using SopHelper.Core.Prism;
|
||||
using SopHelper.VVMs.SopPage;
|
||||
|
||||
@ -9,10 +10,25 @@ namespace SopHelper.VVMs.RuntimeSettings;
|
||||
[NavigationPage(ViewName = nameof(RuntimeSettings), DisplayName = "设置", Index = 1)]
|
||||
public partial class RuntimeSettings : UserControl
|
||||
{
|
||||
private readonly SopPageViewModel _model;
|
||||
|
||||
public RuntimeSettings(SopPageViewModel model)
|
||||
{
|
||||
InitializeComponent();
|
||||
_model = model;
|
||||
DataContext = model;
|
||||
// 仅在视图挂载期间跟踪账号变化;切换会话时丢弃尚未保存的选择。
|
||||
AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
model.Access.AccountsChanged += RefreshAutoLogin;
|
||||
model.Access.SessionChanged += RefreshAutoLogin;
|
||||
RefreshAutoLogin();
|
||||
};
|
||||
DetachedFromVisualTree += (_, _) =>
|
||||
{
|
||||
model.Access.AccountsChanged -= RefreshAutoLogin;
|
||||
model.Access.SessionChanged -= RefreshAutoLogin;
|
||||
};
|
||||
model.ConfirmDeleteRecipeAsync = async name =>
|
||||
{
|
||||
if (TopLevel.GetTopLevel(this) is not Window owner) return false;
|
||||
@ -26,4 +42,38 @@ public partial class RuntimeSettings : UserControl
|
||||
return await new ImportRecipeConflictDialog(conflict).ShowDialog<SopPageViewModel.ImportConflictChoice>(owner);
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>按持久化配置还原开关和用户名,并从当前账号列表重新生成下拉选项。</summary>
|
||||
private void RefreshAutoLogin()
|
||||
{
|
||||
var userName = _model.Access.AutoLoginUserName;
|
||||
AutoLoginUserInput.ItemsSource = _model.Access.LoginUserNames();
|
||||
AutoLoginUserInput.SelectedItem = userName;
|
||||
AutoLoginToggle.IsChecked = userName is not null;
|
||||
AutoLoginStatus.Text = "";
|
||||
}
|
||||
|
||||
/// <summary>开启时要求选择账号,关闭时清除配置;写盘失败则保留编辑状态供重试。</summary>
|
||||
private void SaveAutoLogin(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!_model.CanChangeModels) return;
|
||||
|
||||
var enabled = AutoLoginToggle.IsChecked == true;
|
||||
var userName = AutoLoginUserInput.SelectedItem as string;
|
||||
if (enabled && userName is null)
|
||||
{
|
||||
AutoLoginStatus.Text = "请选择自动登录用户。";
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_model.Access.SaveAutoLogin(enabled ? userName : null);
|
||||
AutoLoginStatus.Text = "已保存,下次启动时生效。";
|
||||
}
|
||||
catch (Exception error) when (error is ArgumentException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
AutoLoginStatus.Text = "保存自动登录设置失败:" + error.Message;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -78,6 +78,7 @@ internal static class Smoke
|
||||
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4");
|
||||
try
|
||||
{
|
||||
if (args.Contains("--auto-login-only")) PrepareAutoLogin(dataRoot);
|
||||
AppBuilder.Configure(()=>new App(Camera, Licensing.Service)).UseSkia()
|
||||
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing=false })
|
||||
.LogToTrace(Avalonia.Logging.LogEventLevel.Warning)
|
||||
@ -113,6 +114,8 @@ internal static class Smoke
|
||||
{ await Licensing.Run(app, lifetime); _exit = 0; return; }
|
||||
if (Environment.GetCommandLineArgs().Contains("--login-users-only"))
|
||||
{ await CheckLoginUserSelection(window); _exit = 0; return; }
|
||||
if (Environment.GetCommandLineArgs().Contains("--auto-login-only"))
|
||||
{ await CheckAutoLogin(app); _exit = 0; return; }
|
||||
if (Environment.GetCommandLineArgs().Contains("--permissions-only"))
|
||||
{ await CheckPermissions(app, window); await CheckOwnPasswords(window); _exit = 0; return; }
|
||||
// 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。
|
||||
@ -1551,6 +1554,80 @@ internal static class Smoke
|
||||
Check(!lifetime.Windows.Contains(modal)&&before.SequenceEqual(File.ReadAllBytes(store.ConfigPath(config.Sop.Name))),
|
||||
"Prism右上角关闭确认不保存后释放资源并保留原文件");
|
||||
}
|
||||
/// <summary>在应用启动前准备隔离的账号文件,覆盖已有安装从默认关闭到启用的持久化。</summary>
|
||||
private static void PrepareAutoLogin(string root)
|
||||
{
|
||||
var path = Path.Combine(root, "workspace", "users.json");
|
||||
var access = new UserAccess(path);
|
||||
access.Setup("auto-admin", "AdminPassword123");
|
||||
access.SaveUser("auto-operator", "OperatorPassword123", UserRole.Operator);
|
||||
Check(new UserAccess(path).AutoLoginUserName is null, "已有账号且未配置时默认关闭自动登录");
|
||||
access.SaveAutoLogin("auto-operator");
|
||||
}
|
||||
|
||||
/// <summary>通过真实启动和设置视图验证自动登录角色、手动退出、表单校验及撤销配置。</summary>
|
||||
private static async Task CheckAutoLogin(App app)
|
||||
{
|
||||
var access = UserAccess.Current;
|
||||
var path = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!, "workspace", "users.json");
|
||||
Check(access.User is { Name: "auto-operator", Role: UserRole.Operator }, "应用启动时使用所选操作员及其权限");
|
||||
try
|
||||
{
|
||||
access.SaveAutoLogin("auto-admin");
|
||||
throw new Exception("操作员修改了自动登录配置");
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
Check(access.AutoLoginUserName == "auto-operator", "操作员不能直接修改自动登录配置");
|
||||
}
|
||||
|
||||
access.Logout();
|
||||
Check(!access.IsAuthenticated && access.AutoLoginUserName == "auto-operator", "手动退出清除当前会话并保留下次启动配置");
|
||||
Check(access.Login("auto-admin", "AdminPassword123"), "管理员可以手动切换身份");
|
||||
var view = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(app.Container.Resolve<SopPageViewModel>());
|
||||
var window = new Window { Content = view, Width = 900, Height = 900 };
|
||||
window.Show();
|
||||
try
|
||||
{
|
||||
await Task.Delay(60);
|
||||
var toggle = view.FindControl<ToggleSwitch>("AutoLoginToggle")!;
|
||||
var users = view.FindControl<ComboBox>("AutoLoginUserInput")!;
|
||||
var save = view.FindControl<Button>("SaveAutoLoginButton")!;
|
||||
void Save() => save.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
|
||||
Check(toggle.IsChecked == true && users.IsEffectivelyVisible && Equals(users.SelectedItem, "auto-operator"),
|
||||
"设置页还原开关与已选用户");
|
||||
toggle.IsChecked = false;
|
||||
await Task.Delay(40);
|
||||
Check(!users.IsEffectivelyVisible, "关闭开关后隐藏用户下拉框");
|
||||
Save();
|
||||
Check(new UserAccess(path).AutoLoginUserName is null, "保存关闭后清除持久化配置");
|
||||
|
||||
toggle.IsChecked = true;
|
||||
await Task.Delay(40);
|
||||
Check(users.IsEffectivelyVisible && users.Items.Cast<string>().SequenceEqual(new[] { "auto-admin", "auto-operator" }),
|
||||
"打开开关后可从现有账号中选择");
|
||||
Save();
|
||||
Check(view.FindControl<TextBlock>("AutoLoginStatus")!.Text == "请选择自动登录用户。"
|
||||
&& new UserAccess(path).AutoLoginUserName is null, "开启时必须选择用户才能保存");
|
||||
users.SelectedItem = "auto-operator";
|
||||
Save();
|
||||
Check(new UserAccess(path).AutoLoginUserName == "auto-operator" && access.IsAdministrator,
|
||||
"设置页保存所选用户,当前会话保持管理员身份");
|
||||
|
||||
access.SaveUser("auto-operator", "", UserRole.Engineer);
|
||||
Check(new UserAccess(path).AutoLoginUserName is null && toggle.IsChecked == false, "变更角色时撤销旧的自动登录并刷新界面");
|
||||
access.SaveAutoLogin("auto-operator");
|
||||
access.SaveUser("auto-operator", "ResetPassword123", UserRole.Engineer);
|
||||
Check(new UserAccess(path).AutoLoginUserName is null, "重置密码时撤销自动登录");
|
||||
access.SaveAutoLogin("auto-operator");
|
||||
access.DeleteUser("auto-operator");
|
||||
access.SaveUser("auto-operator", "OperatorPassword123", UserRole.Operator);
|
||||
Check(new UserAccess(path).AutoLoginUserName is null, "删除后重建同名账号不会继承自动登录");
|
||||
}
|
||||
finally { window.Close(); }
|
||||
}
|
||||
|
||||
/// <summary>验证角色矩阵、持久化及绕过 CanExecute 的直接调用;仅操作隔离的测试工作区。</summary>
|
||||
private static async Task CheckPermissions(App app, Window window)
|
||||
{
|
||||
|
||||
Loading…
Reference in New Issue
Block a user