新增管理员、工艺师和操作员账号权限系统
This commit is contained in:
parent
8085cf1608
commit
0963e61a68
@ -23,6 +23,11 @@ public class NavigationModel : ModelBase
|
||||
: base(container, ea)
|
||||
{
|
||||
_regionManager = regionManager;
|
||||
UserAccess.Current.SessionChanged += () =>
|
||||
{
|
||||
// 降权后立即离开设置页面,避免保留可交互的旧入口。
|
||||
if (!UserAccess.Current.CanConfigure && Target?.ViewName != "SopPage") { Navigate("SopPage"); SelectedIndex = 0; }
|
||||
};
|
||||
}
|
||||
|
||||
private ObservableCollection<NavigateItem> _pages = [];
|
||||
@ -68,6 +73,7 @@ public class NavigationModel : ModelBase
|
||||
public void Navigate(string viewName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(viewName)) return;
|
||||
if (viewName != "SopPage" && !UserAccess.Current.CanConfigure) { Navigate("SopPage"); SelectedIndex = 0; return; }
|
||||
|
||||
Target = Pages.FirstOrDefault(n => n.ViewName == viewName);
|
||||
if (Target is null) return;
|
||||
|
||||
128
src/SopHelper.Avalonia/Models/UserAccess.cs
Normal file
128
src/SopHelper.Avalonia/Models/UserAccess.cs
Normal file
@ -0,0 +1,128 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Prism.Mvvm;
|
||||
using SopHelper.Presentation;
|
||||
|
||||
namespace SopHelper.Models;
|
||||
|
||||
/// <summary>本机账号角色;权限集中由 UserAccess 解释,避免页面各自定义规则。</summary>
|
||||
public enum UserRole { Administrator, Engineer, Operator }
|
||||
|
||||
/// <summary>界面使用的账号摘要,不包含密码校验材料。</summary>
|
||||
public sealed record UserSummary(string Name, UserRole Role)
|
||||
{
|
||||
public override string ToString() => $"{Name}({UserAccess.RoleName(Role)})";
|
||||
}
|
||||
|
||||
/// <summary>管理本地账号、密码校验及当前会话。密码使用独立随机盐的 PBKDF2,不保存明文。</summary>
|
||||
public sealed class UserAccess : BindableBase
|
||||
{
|
||||
private sealed record Account(string Name, UserRole Role, string Salt, string Hash);
|
||||
private readonly string _path;
|
||||
private List<Account> _accounts;
|
||||
private UserSummary? _user;
|
||||
public static UserAccess Current { get; } = new(Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "users.json"));
|
||||
public UserSummary? User => _user;
|
||||
public bool IsAuthenticated => _user is not null;
|
||||
public bool CanConfigure => _user?.Role is UserRole.Administrator or UserRole.Engineer;
|
||||
public bool IsAdministrator => _user?.Role == UserRole.Administrator;
|
||||
public bool NeedsSetup => _accounts.Count == 0;
|
||||
public string DisplayName => _user?.ToString() ?? "未登录";
|
||||
public event Action? SessionChanged;
|
||||
|
||||
/// <summary>读取账号文件;损坏时报告错误,禁止静默重建管理员。</summary>
|
||||
public UserAccess(string path)
|
||||
{
|
||||
_path = path;
|
||||
_accounts = File.Exists(path) ? JsonSerializer.Deserialize<List<Account>>(File.ReadAllText(path))
|
||||
?? throw new InvalidDataException("账号文件为空") : [];
|
||||
if (_accounts.Count > 0 && !_accounts.Any(a => a.Role == UserRole.Administrator))
|
||||
throw new InvalidDataException("账号文件缺少管理员");
|
||||
}
|
||||
|
||||
public static string RoleName(UserRole role) => role switch
|
||||
{ UserRole.Administrator => "管理员", UserRole.Engineer => "工艺师", _ => "操作员" };
|
||||
|
||||
/// <summary>仅在没有账号时创建首个管理员并登录,无内置默认口令。</summary>
|
||||
public void Setup(string name, string password)
|
||||
{
|
||||
if (!NeedsSetup) throw new InvalidOperationException("已经完成初始化");
|
||||
var account = Create(name, password, UserRole.Administrator);
|
||||
Persist([account]);
|
||||
SetSession(new(account.Name, account.Role));
|
||||
}
|
||||
|
||||
/// <summary>密码错误时保持原会话,成功后切换当前身份。</summary>
|
||||
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;
|
||||
SetSession(new(account.Name, account.Role));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>退出当前会话,通知命令与设置界面立即收回权限。</summary>
|
||||
public void Logout() => SetSession(null);
|
||||
|
||||
/// <summary>人员列表只对管理员开放。</summary>
|
||||
public IReadOnlyList<UserSummary> Users()
|
||||
{
|
||||
RequireAdministrator();
|
||||
return _accounts.Select(a => new UserSummary(a.Name, a.Role)).ToArray();
|
||||
}
|
||||
|
||||
/// <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);
|
||||
if (!Enum.IsDefined(role)) throw new ArgumentException("无效角色");
|
||||
var next = _accounts.Where(a => a != existing).Append(replacement).ToList();
|
||||
EnsureAdministrator(next);
|
||||
Persist(next);
|
||||
if (existing?.Name == _user?.Name) SetSession(new(replacement.Name, replacement.Role));
|
||||
}
|
||||
|
||||
/// <summary>删除账号时保留至少一名管理员,且不能删除当前登录账号。</summary>
|
||||
public void DeleteUser(string name)
|
||||
{
|
||||
RequireAdministrator();
|
||||
if (string.Equals(name, _user!.Name, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("不能删除当前登录账号");
|
||||
var next = _accounts.Where(a => !string.Equals(a.Name, name, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
EnsureAdministrator(next);
|
||||
Persist(next);
|
||||
}
|
||||
|
||||
private static Account Create(string name, string password, UserRole role)
|
||||
{
|
||||
name = name.Trim();
|
||||
if (name.Length is < 1 or > 64) throw new ArgumentException("用户名长度为 1–64 个字符");
|
||||
if (password.Length < 8) throw new ArgumentException("密码至少需要 8 个字符");
|
||||
var salt = RandomNumberGenerator.GetBytes(16);
|
||||
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 static void EnsureAdministrator(List<Account> accounts)
|
||||
{ if (!accounts.Any(a => a.Role == UserRole.Administrator)) throw new InvalidOperationException("至少保留一名管理员"); }
|
||||
|
||||
// 先原子替换文件,再更新内存;写盘失败时账号和当前会话都保持原状。
|
||||
private void Persist(List<Account> accounts)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(_path))!);
|
||||
var temp = _path + ".tmp";
|
||||
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;
|
||||
}
|
||||
private void SetSession(UserSummary? user)
|
||||
{
|
||||
_user = user;
|
||||
foreach (var property in new[] { nameof(User), nameof(IsAuthenticated), nameof(CanConfigure), nameof(IsAdministrator), nameof(NeedsSetup), nameof(DisplayName) }) RaisePropertyChanged(property);
|
||||
SessionChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
64
src/SopHelper.Avalonia/VVMs/MainWindow/AccountWindow.cs
Normal file
64
src/SopHelper.Avalonia/VVMs/MainWindow/AccountWindow.cs
Normal file
@ -0,0 +1,64 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using SopHelper.Models;
|
||||
|
||||
namespace SopHelper.VVMs.MainWindow;
|
||||
|
||||
/// <summary>登录、首次管理员初始化和人员维护窗口;敏感操作由账号服务再次校验。</summary>
|
||||
public sealed class AccountWindow : Window
|
||||
{
|
||||
public AccountWindow(bool manage = false)
|
||||
{
|
||||
var access = UserAccess.Current;
|
||||
Title = manage ? "人员管理" : access.NeedsSetup ? "创建首个管理员" : "用户登录";
|
||||
Width = 440; Height = manage ? 560 : 340;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
CanResize = false;
|
||||
var panel = new StackPanel { Margin = new Thickness(24), Spacing = 12 };
|
||||
Content = panel;
|
||||
panel.Children.Add(new TextBlock { Text = Title, FontSize = 20 });
|
||||
var users = new ComboBox { HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Stretch };
|
||||
var name = new TextBox { PlaceholderText = "用户名" };
|
||||
var password = new TextBox { PlaceholderText = "密码(至少 8 个字符)", PasswordChar = '●' };
|
||||
var roles = Enum.GetValues<UserRole>();
|
||||
var role = new ComboBox { ItemsSource = roles.Select(UserAccess.RoleName).ToArray(), SelectedIndex = 2 };
|
||||
var status = new TextBlock { TextWrapping = Avalonia.Media.TextWrapping.Wrap };
|
||||
if (manage)
|
||||
{
|
||||
users.ItemsSource = access.Users();
|
||||
panel.Children.Add(users);
|
||||
users.SelectionChanged += (_, _) =>
|
||||
{
|
||||
if (users.SelectedItem is not UserSummary selected) return;
|
||||
name.Text = selected.Name; role.SelectedIndex = Array.IndexOf(roles, selected.Role); password.Text = "";
|
||||
};
|
||||
}
|
||||
panel.Children.Add(name); panel.Children.Add(password);
|
||||
if (manage)
|
||||
{
|
||||
panel.Children.Add(role);
|
||||
panel.Children.Add(new TextBlock { Text = "新增账号请填写密码;修改已有账号时密码留空表示保留。", TextWrapping = Avalonia.Media.TextWrapping.Wrap });
|
||||
}
|
||||
var submit = new Button { Content = manage ? "新增 / 保存" : access.NeedsSetup ? "创建并登录" : "登录" };
|
||||
panel.Children.Add(submit); panel.Children.Add(status);
|
||||
submit.Click += (_, _) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (manage) { access.SaveUser(name.Text ?? "", password.Text ?? "", roles[role.SelectedIndex]); users.ItemsSource = access.Users(); password.Text = ""; status.Text = "已保存"; }
|
||||
else { if (access.NeedsSetup) access.Setup(name.Text ?? "", password.Text ?? ""); else if (!access.Login(name.Text ?? "", password.Text ?? "")) { status.Text = "用户名或密码错误"; return; } Close(); }
|
||||
}
|
||||
catch (Exception error) { status.Text = error.Message; }
|
||||
};
|
||||
if (manage)
|
||||
{
|
||||
var delete = new Button { Content = "删除选中账号" };
|
||||
panel.Children.Add(delete);
|
||||
delete.Click += (_, _) =>
|
||||
{
|
||||
try { if (users.SelectedItem is UserSummary selected) { access.DeleteUser(selected.Name); users.ItemsSource = access.Users(); status.Text = "已删除"; } }
|
||||
catch (Exception error) { status.Text = error.Message; }
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -64,6 +64,13 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
<!-- 账号切换在停机后进行,避免运行中失去操作身份。 -->
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="10" Margin="0,8,0,10">
|
||||
<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="ManageUsers" IsEnabled="{Binding CanChangeAccount}" IsVisible="{Binding Access.IsAdministrator}" />
|
||||
</StackPanel>
|
||||
<ContentControl Grid.Row="1" Grid.Column="1" prism:RegionManager.RegionName="ContentRegion" />
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
@ -1,6 +1,13 @@
|
||||
// 主窗口视图:初始化 XAML;导航与业务状态交由 Prism 解析的视图模型管理。
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using SopHelper.Models;
|
||||
namespace SopHelper.VVMs.MainWindow;
|
||||
/// <summary>主窗口承载账号对话框;运行期间保持登录身份不变。</summary>
|
||||
public partial class MainWindow : Window
|
||||
{ public MainWindow() { InitializeComponent(); } }
|
||||
{
|
||||
public MainWindow() { InitializeComponent(); }
|
||||
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(); }
|
||||
private async void ManageUsers(object? sender, RoutedEventArgs e) { if (CanChange && UserAccess.Current.IsAdministrator) await new AccountWindow(true).ShowDialog(this); }
|
||||
}
|
||||
|
||||
@ -21,6 +21,7 @@ public class MainWindowViewModel : BindableBase
|
||||
{
|
||||
_navigation = navigation;
|
||||
Sop = sop;
|
||||
sop.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(sop.IsRunning)) RaisePropertyChanged(nameof(CanChangeAccount)); };
|
||||
}
|
||||
|
||||
private string _title = "SopHelper";
|
||||
@ -40,6 +41,9 @@ public class MainWindowViewModel : BindableBase
|
||||
public NavigationModel Navigation => _navigation;
|
||||
|
||||
public SopPageViewModel Sop { get; }
|
||||
/// <summary>主窗口显示共享身份,并禁止运行时切换账号。</summary>
|
||||
public UserAccess Access => UserAccess.Current;
|
||||
public bool CanChangeAccount => !Sop.IsRunning;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -448,7 +448,7 @@
|
||||
<Button Grid.Column="1" Content="选择视频…" Command="{Binding BrowseAgentVideoCommand}" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<Expander x:Name="AgentSettingsExpander" Grid.Row="1" Header="模型设置" IsExpanded="False" Margin="0,8,0,0" IsEnabled="{Binding AgentIsIdle}">
|
||||
<Expander x:Name="AgentSettingsExpander" Grid.Row="1" Header="模型设置" IsExpanded="False" Margin="0,8,0,0" IsEnabled="{Binding CanChangeAgentModels}">
|
||||
<StackPanel Spacing="6">
|
||||
<Grid ColumnDefinitions="70,*">
|
||||
<TextBlock Text="接口地址" VerticalAlignment="Center" />
|
||||
|
||||
@ -27,11 +27,15 @@ public partial class RecipeEditorViewModel
|
||||
public Func<Task<AgentRecipeApplyChoice>>? ChooseAgentApplyAsync { get; set; }
|
||||
public Func<string, Task>? ShowAgentApplyCompletedAsync { get; set; }
|
||||
private bool _agentSettingsLoaded;
|
||||
// 只允许同步读取配置期间绕过角色校验,未打开编辑器本身不授予写权限。
|
||||
private bool _loadingAgentSettings;
|
||||
/// <summary>工艺师可使用助手,模型连接及推理参数只允许管理员修改。</summary>
|
||||
public bool CanChangeAgentModels => SopHelper.Models.UserAccess.Current.IsAdministrator && AgentIsIdle;
|
||||
public bool AgentUseForSequence { get => false; set { /* 旧配置兼容:禁止Agent参与判定。 */ } }
|
||||
private bool? _agentSequenceEnableThinking;
|
||||
private bool? _agentEnableThinking;
|
||||
public bool? AgentEnableThinking { get => _agentEnableThinking; set { if (SetProperty(ref _agentEnableThinking, value)) SaveAgentSettings(); } }
|
||||
public bool? AgentSequenceEnableThinking { get => _agentSequenceEnableThinking; set { if (SetProperty(ref _agentSequenceEnableThinking, value)) SaveAgentSettings(); } }
|
||||
public bool? AgentEnableThinking { get => _agentEnableThinking; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentEnableThinking, value)) SaveAgentSettings(); } }
|
||||
public bool? AgentSequenceEnableThinking { get => _agentSequenceEnableThinking; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentSequenceEnableThinking, value)) SaveAgentSettings(); } }
|
||||
private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = "";
|
||||
private string _agentStatus = "", _agentSummary = "";
|
||||
private int _agentMaxFrames = 3;
|
||||
@ -50,17 +54,17 @@ public partial class RecipeEditorViewModel
|
||||
}
|
||||
public string AgentApplyLabel => _agentAppliedNodes.Count == 0 ? "添加到配方" : "更新配方";
|
||||
public ObservableCollection<string> AgentModels { get; } = [];
|
||||
public int AgentContextLength { get => _agentContextLength; set { if (SetProperty(ref _agentContextLength, value)) SaveAgentSettings(); } }
|
||||
public int AgentMaxTokens { get => _agentMaxTokens; set { if (SetProperty(ref _agentMaxTokens, value)) SaveAgentSettings(); } }
|
||||
public int AgentTimeoutSeconds { get => _agentTimeoutSeconds; set { if (SetProperty(ref _agentTimeoutSeconds, value)) SaveAgentSettings(); } }
|
||||
public double AgentTemperature { get => _agentTemperature; set { if (SetProperty(ref _agentTemperature, value)) SaveAgentSettings(); } }
|
||||
public double AgentTopP { get => _agentTopP; set { if (SetProperty(ref _agentTopP, value)) SaveAgentSettings(); } }
|
||||
public int AgentContextLength { get => _agentContextLength; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentContextLength, value)) SaveAgentSettings(); } }
|
||||
public int AgentMaxTokens { get => _agentMaxTokens; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentMaxTokens, value)) SaveAgentSettings(); } }
|
||||
public int AgentTimeoutSeconds { get => _agentTimeoutSeconds; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentTimeoutSeconds, value)) SaveAgentSettings(); } }
|
||||
public double AgentTemperature { get => _agentTemperature; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentTemperature, value)) SaveAgentSettings(); } }
|
||||
public double AgentTopP { get => _agentTopP; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentTopP, value)) SaveAgentSettings(); } }
|
||||
public ObservableCollection<AgentDraftRow> AgentDraftSteps { get; } = [];
|
||||
public string AgentEndpoint { get => _agentEndpoint; set { if (SetProperty(ref _agentEndpoint, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||||
public string AgentModel { get => _agentModel; set { if (SetProperty(ref _agentModel, value)) SaveAgentSettings(); } }
|
||||
public string AgentApiKey { get => _agentApiKey; set { if (SetProperty(ref _agentApiKey, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||||
public string AgentEndpoint { get => _agentEndpoint; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentEndpoint, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||||
public string AgentModel { get => _agentModel; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentModel, value)) SaveAgentSettings(); } }
|
||||
public string AgentApiKey { get => _agentApiKey; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentApiKey, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||||
public string AgentInstructions { get => _agentInstructions; set => SetProperty(ref _agentInstructions, value); }
|
||||
public int AgentMaxFrames { get => _agentMaxFrames; set { if (SetProperty(ref _agentMaxFrames, value)) SaveAgentSettings(); } }
|
||||
public int AgentMaxFrames { get => _agentMaxFrames; set { if (!_loadingAgentSettings && !CanChangeAgentModels) return; if (SetProperty(ref _agentMaxFrames, value)) SaveAgentSettings(); } }
|
||||
public string AgentVideoPath
|
||||
{
|
||||
get => _agentVideoPath;
|
||||
@ -77,6 +81,7 @@ public partial class RecipeEditorViewModel
|
||||
{
|
||||
if (!SetProperty(ref _isAgentBusy, value)) return;
|
||||
RaisePropertyChanged(nameof(AgentIsIdle));
|
||||
RaisePropertyChanged(nameof(CanChangeAgentModels));
|
||||
RaisePropertyChanged(nameof(AgentCanEditDraft));
|
||||
OptimizeStepsCommand.RaiseCanExecuteChanged();
|
||||
GenerateStepsCommand.RaiseCanExecuteChanged(); CancelAgentCommand.RaiseCanExecuteChanged();
|
||||
@ -115,6 +120,7 @@ public partial class RecipeEditorViewModel
|
||||
private void LoadAgentSettings()
|
||||
{
|
||||
_agentSettingsLoaded = false;
|
||||
_loadingAgentSettings = true;
|
||||
try
|
||||
{
|
||||
if (File.Exists(AgentSettingsPath))
|
||||
@ -139,6 +145,7 @@ public partial class RecipeEditorViewModel
|
||||
AgentEndpoint = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_ENDPOINT") ?? AgentEndpoint;
|
||||
AgentModel = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_MODEL") ?? AgentModel;
|
||||
AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? AgentApiKey;
|
||||
_loadingAgentSettings = false;
|
||||
_agentSettingsLoaded = true;
|
||||
UpdateAgentDefaultVideo();
|
||||
ScheduleModelDiscovery();
|
||||
@ -146,7 +153,7 @@ public partial class RecipeEditorViewModel
|
||||
|
||||
private void SaveAgentSettings()
|
||||
{
|
||||
if (!_agentSettingsLoaded) return;
|
||||
if (!_agentSettingsLoaded || !SopHelper.Models.UserAccess.Current.IsAdministrator) return;
|
||||
var temporary = AgentSettingsPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||||
try
|
||||
{
|
||||
@ -191,7 +198,7 @@ public partial class RecipeEditorViewModel
|
||||
var models = await new SopVideoDraftClient(AgentHttp).GetModelsAsync(endpoint, key, cancellation.Token);
|
||||
cancellation.Token.ThrowIfCancellationRequested();
|
||||
foreach (var model in models) AgentModels.Add(model);
|
||||
if (string.IsNullOrWhiteSpace(AgentModel) && models.Count > 0) AgentModel = models[0];
|
||||
if (SopHelper.Models.UserAccess.Current.IsAdministrator && string.IsNullOrWhiteSpace(AgentModel) && models.Count > 0) AgentModel = models[0];
|
||||
if (!IsAgentBusy) AgentStatus = models.Count == 0 ? "没有可用模型。" : $"已获取 {models.Count} 个模型。";
|
||||
}
|
||||
catch (OperationCanceledException) { ReportDiscoveryError("获取模型超时。"); }
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="相机" Width="40" />
|
||||
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanSelectCamera}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 USB(UVC)相机">
|
||||
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanChangeSettings}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 USB(UVC)相机">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Name}" />
|
||||
@ -34,7 +34,7 @@
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="配方" Width="40" />
|
||||
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" IsEnabled="{Binding CanSelectCamera}" ItemsSource="{Binding Recipes}" SelectedItem="{Binding SelectedRecipe, Converter={StaticResource SelectionConverter}}" />
|
||||
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" IsEnabled="{Binding CanChangeSettings}" ItemsSource="{Binding Recipes}" SelectedItem="{Binding SelectedRecipe, Converter={StaticResource SelectionConverter}}" />
|
||||
<Button Grid.Column="2" Content="编辑" Margin="6,0,0,0" Padding="10,4" Command="{Binding EditRecipeCommand}" />
|
||||
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4" Command="{Binding NewRecipeCommand}" />
|
||||
<Button Grid.Column="4" Content="应用" Margin="6,0,0,0" Padding="10,4" Command="{Binding ApplyRecipeCommand}" />
|
||||
@ -48,14 +48,14 @@
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="抽帧" Width="40" />
|
||||
<Slider IsEnabled="{Binding CanSelectCamera}" Grid.Column="1" Minimum="1" Maximum="10" TickFrequency="1" IsSnapToTickEnabled="True" Value="{Binding FrameStride}" VerticalAlignment="Center" />
|
||||
<Slider IsEnabled="{Binding CanChangeSettings}" Grid.Column="1" Minimum="1" Maximum="10" TickFrequency="1" IsSnapToTickEnabled="True" Value="{Binding FrameStride}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="2" Text="{Binding FrameStride}" HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
|
||||
</Grid>
|
||||
<CheckBox x:Name="AutoResetCheckBox" Content="完成后自动复位" IsChecked="{Binding AutoResetOnComplete}" IsEnabled="{Binding CanSelectCamera}" Margin="0,10,0,0" />
|
||||
<CheckBox x:Name="AutoResetCheckBox" Content="完成后自动复位" IsChecked="{Binding AutoResetOnComplete}" IsEnabled="{Binding CanChangeSettings}" Margin="0,10,0,0" />
|
||||
<Grid ColumnDefinitions="Auto,*" Margin="0,8,0,0">
|
||||
<TextBlock Text="复位延时(秒)" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<NumericUpDown x:Name="ResetDelayInput" Grid.Column="1" Value="{Binding ResetDelaySec}" Minimum="1" Maximum="3600" Increment="1"
|
||||
IsEnabled="{Binding CanSelectCamera}" HorizontalAlignment="Left" Width="120" />
|
||||
IsEnabled="{Binding CanChangeSettings}" HorizontalAlignment="Left" Width="120" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
@ -66,14 +66,14 @@
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Text="启动档位" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<ComboBox x:Name="DjevTierInput" Grid.Column="1" ItemsSource="{Binding DjevTiers}" SelectedItem="{Binding DjevTier, Mode=TwoWay}"
|
||||
IsEnabled="{Binding CanSelectCamera}" HorizontalAlignment="Left" Width="120" />
|
||||
IsEnabled="{Binding CanChangeModels}" HorizontalAlignment="Left" Width="120" />
|
||||
<Button x:Name="SaveDjevTierButton" Grid.Column="2" Content="保存启动配置" Command="{Binding SaveDjevSelectionCommand}" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanSelectCamera}">
|
||||
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanChangeModels}">
|
||||
<TextBlock Text="lite 模型目录" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<TextBox Grid.Column="1" Text="{Binding DjevLiteRoot, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanSelectCamera}">
|
||||
<Grid ColumnDefinitions="Auto,*" IsEnabled="{Binding CanChangeModels}">
|
||||
<TextBlock Text="nano 模型目录" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<TextBox Grid.Column="1" Text="{Binding DjevNanoRoot, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
@ -82,7 +82,7 @@
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<TextBlock Text="判定超时(ms)" VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<NumericUpDown x:Name="DjevTimeoutInput" Grid.Column="1" Value="{Binding DjevTimeoutMs}" Minimum="1" Maximum="1000" Increment="1"
|
||||
IsEnabled="{Binding CanSelectCamera}" HorizontalAlignment="Left" Width="120" />
|
||||
IsEnabled="{Binding CanChangeSettings}" HorizontalAlignment="Left" Width="120" />
|
||||
</Grid>
|
||||
<TextBlock Text="全局生效,独立保存,不随配方切换。范围1–1000 ms,默认300 ms;只计算请求发给djev后等待响应的时间。修改后在下次判定或开始运行时生效。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
@ -135,24 +135,25 @@ public class SopPageViewModel : ViewModelBase
|
||||
|
||||
LoadRecipes();
|
||||
|
||||
Access.SessionChanged += AccessChanged;
|
||||
// 命令接线(DelegateCommand 的可用条件都挂在这里)
|
||||
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null);
|
||||
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
|
||||
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
|
||||
ResetCountsCommand = new DelegateCommand(ResetCounts, () => StepCards.Count > 0);
|
||||
PlayStandardSopCommand = new DelegateCommand(PlayStandardSop, () => StandardSopVideoPath is { } path && File.Exists(path));
|
||||
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
|
||||
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
|
||||
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
|
||||
NewRecipeCommand = new DelegateCommand(NewRecipe, () => CanSelectCamera);
|
||||
DeleteRecipeCommand = new DelegateCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe);
|
||||
OpenRecipeFolderCommand = new DelegateCommand(() =>
|
||||
ConfigureCameraCommand = ConfigurationCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null);
|
||||
RefreshCamerasCommand = ConfigurationCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
|
||||
StartStopCommand = new DelegateCommand(async () => { if (Access.IsAuthenticated) await StartStopAsync(); }, () => Access.IsAuthenticated && CanStart());
|
||||
ResetCountsCommand = ConfigurationCommand(ResetCounts, () => StepCards.Count > 0);
|
||||
PlayStandardSopCommand = ConfigurationCommand(PlayStandardSop, () => StandardSopVideoPath is { } path && File.Exists(path));
|
||||
ApplyRecipeCommand = ConfigurationCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
|
||||
SnapshotCommand = ConfigurationCommand(Snapshot, () => _lastFrame is not null);
|
||||
EditRecipeCommand = ConfigurationCommand(EditRecipe, CanEditRecipe);
|
||||
NewRecipeCommand = ConfigurationCommand(NewRecipe, () => CanSelectCamera);
|
||||
DeleteRecipeCommand = ConfigurationCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe);
|
||||
OpenRecipeFolderCommand = ConfigurationCommand(() =>
|
||||
{
|
||||
try { DesktopPlatform.Reveal(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(SelectedRecipe!))); }
|
||||
catch (Exception error) { Log("warn", "打开配方目录失败:" + error.Message); }
|
||||
}, () => !string.IsNullOrWhiteSpace(SelectedRecipe));
|
||||
|
||||
SaveDjevSelectionCommand = new DelegateCommand(SaveDjevSelection, () => CanSelectCamera && _djevSelectionStore is not null);
|
||||
SaveDjevSelectionCommand = ConfigurationCommand(SaveDjevSelection, () => CanSelectCamera && _djevSelectionStore is not null, true);
|
||||
LoadDjevSelection();
|
||||
|
||||
StatusText = "就绪,请确认运行设置后开始";
|
||||
@ -168,6 +169,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
Log("warn", "自动应用配方失败:" + error.Message);
|
||||
}
|
||||
RefreshStatistics();
|
||||
_accessReady = true;
|
||||
}
|
||||
|
||||
/// <summary>可用相机</summary>
|
||||
@ -194,6 +196,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
get { return _selectedCamera; }
|
||||
set
|
||||
{
|
||||
if (_accessReady && !_isCameraBusy && !CanChangeSettings) return;
|
||||
var previous = _selectedCamera;
|
||||
if (!SetProperty(ref _selectedCamera, value)) return;
|
||||
// 枚举时清空、恢复列表不释放已连接的设备;只有实际选择变化才释放旧设备。
|
||||
@ -213,6 +216,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
get { return _selectedRecipe; }
|
||||
set
|
||||
{
|
||||
if (_accessReady && !_refreshingRecipes && !CanChangeSettings) return;
|
||||
if (!SetProperty(ref _selectedRecipe, value)) return;
|
||||
if (!_refreshingRecipes) RememberRecipe(value);
|
||||
RaiseCommands();
|
||||
@ -274,12 +278,30 @@ public class SopPageViewModel : ViewModelBase
|
||||
{
|
||||
if (!SetProperty(ref _isRunning, value)) return;
|
||||
if (!value) { HandResult = null; _engine.Stop(); }
|
||||
RaisePropertyChanged(nameof(CanSelectCamera));
|
||||
RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels));
|
||||
RaiseCommands();
|
||||
RefreshStatistics();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>共享身份与设置权限;后台恢复设备和配方仍可在登录前完成。</summary>
|
||||
public SopHelper.Models.UserAccess Access => SopHelper.Models.UserAccess.Current;
|
||||
public bool CanChangeSettings => Access.CanConfigure && CanSelectCamera;
|
||||
public bool CanChangeModels => Access.IsAdministrator && CanSelectCamera;
|
||||
|
||||
// 即使调用方绕过按钮的 CanExecute,执行委托仍重新验证角色。
|
||||
private DelegateCommand ConfigurationCommand(Action action, Func<bool> available, bool administrator = false)
|
||||
{
|
||||
bool Allowed() => (administrator ? Access.IsAdministrator : Access.CanConfigure) && available();
|
||||
return new DelegateCommand(() => { if (Allowed()) action(); }, Allowed);
|
||||
}
|
||||
private void AccessChanged()
|
||||
{
|
||||
RaisePropertyChanged(nameof(CanChangeSettings));
|
||||
RaisePropertyChanged(nameof(CanChangeModels));
|
||||
RaiseCommands();
|
||||
}
|
||||
|
||||
/// <summary>连接、枚举、采集期间不切换设备。</summary>
|
||||
public bool CanSelectCamera => !IsRunning && !_isCameraBusy && !_deletingRecipe;
|
||||
|
||||
@ -323,30 +345,31 @@ public class SopPageViewModel : ViewModelBase
|
||||
public int FrameStride
|
||||
{
|
||||
get => _runtimeOptions.FrameStride;
|
||||
set { if (!CanSelectCamera || value == FrameStride) return; _runtimeOptions.FrameStride = Math.Clamp(value, 1, 10); SaveRuntimeOptions(); }
|
||||
set { if (!CanChangeSettings || value == FrameStride) return; _runtimeOptions.FrameStride = Math.Clamp(value, 1, 10); SaveRuntimeOptions(); }
|
||||
}
|
||||
public bool AutoResetOnComplete
|
||||
{
|
||||
get => _runtimeOptions.AutoResetOnComplete;
|
||||
set { if (!CanSelectCamera || value == AutoResetOnComplete) return; _runtimeOptions.AutoResetOnComplete = value; SaveRuntimeOptions(); }
|
||||
set { if (!CanChangeSettings || value == AutoResetOnComplete) return; _runtimeOptions.AutoResetOnComplete = value; SaveRuntimeOptions(); }
|
||||
}
|
||||
public int ResetDelaySec
|
||||
{
|
||||
get => _runtimeOptions.ResetDelaySec;
|
||||
set { if (!CanSelectCamera || value == ResetDelaySec) return; _runtimeOptions.ResetDelaySec = Math.Max(1, value); SaveRuntimeOptions(); }
|
||||
set { if (!CanChangeSettings || value == ResetDelaySec) return; _runtimeOptions.ResetDelaySec = Math.Max(1, value); SaveRuntimeOptions(); }
|
||||
}
|
||||
public int DjevTimeoutMs
|
||||
{
|
||||
get => _runtimeOptions.DjevTimeoutMs;
|
||||
set { if (!CanSelectCamera || value == DjevTimeoutMs) return; _runtimeOptions.DjevTimeoutMs = value; SaveRuntimeOptions(); }
|
||||
set { if (!CanChangeSettings || value == DjevTimeoutMs) return; _runtimeOptions.DjevTimeoutMs = value; SaveRuntimeOptions(); }
|
||||
}
|
||||
|
||||
private bool _accessReady;
|
||||
private DjevSelectionStore? _djevSelectionStore;
|
||||
private string _djevTier = "lite", _djevLiteRoot = "", _djevNanoRoot = "", _djevSelectionStatus = "";
|
||||
public IReadOnlyList<string> DjevTiers { get; } = new[] { "lite", "nano" };
|
||||
public string DjevTier { get => _djevTier; set => SetProperty(ref _djevTier, value); }
|
||||
public string DjevLiteRoot { get => _djevLiteRoot; set => SetProperty(ref _djevLiteRoot, value); }
|
||||
public string DjevNanoRoot { get => _djevNanoRoot; set => SetProperty(ref _djevNanoRoot, value); }
|
||||
public string DjevTier { get => _djevTier; set { if (CanChangeModels) SetProperty(ref _djevTier, value); } }
|
||||
public string DjevLiteRoot { get => _djevLiteRoot; set { if (CanChangeModels) SetProperty(ref _djevLiteRoot, value); } }
|
||||
public string DjevNanoRoot { get => _djevNanoRoot; set { if (CanChangeModels) SetProperty(ref _djevNanoRoot, value); } }
|
||||
public string DjevSelectionStatus { get => _djevSelectionStatus; private set => SetProperty(ref _djevSelectionStatus, value); }
|
||||
public DelegateCommand SaveDjevSelectionCommand { get; private set; } = null!;
|
||||
|
||||
@ -363,7 +386,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
}
|
||||
_djevSelectionStore = new(options.Root, options.Endpoint.Port);
|
||||
var selection = _djevSelectionStore.Read();
|
||||
DjevTier = selection.Tier; DjevLiteRoot = selection.LiteRoot; DjevNanoRoot = selection.NanoRoot;
|
||||
_djevTier = selection.Tier; _djevLiteRoot = selection.LiteRoot; _djevNanoRoot = selection.NanoRoot;
|
||||
DjevSelectionStatus = "启动配置:" + _djevSelectionStore.FilePath;
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException or ArgumentException)
|
||||
@ -374,7 +397,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
/// <summary>明确保存下次启动选择,保持当前服务运行;保存失败不显示成功或覆盖旧文件。</summary>
|
||||
private void SaveDjevSelection()
|
||||
{
|
||||
if (!CanSelectCamera || _djevSelectionStore is null) return;
|
||||
if (!CanChangeModels || _djevSelectionStore is null) return;
|
||||
try
|
||||
{
|
||||
_djevSelectionStore.Save(new(DjevTier, DjevLiteRoot, DjevNanoRoot));
|
||||
@ -436,7 +459,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
private void SetCameraBusy(bool busy)
|
||||
{
|
||||
_isCameraBusy = busy;
|
||||
RaisePropertyChanged(nameof(CanSelectCamera));
|
||||
RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels));
|
||||
RaiseCommands();
|
||||
}
|
||||
|
||||
@ -514,6 +537,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
/// <remarks>停止界面定时刷新并解除事件订阅,回收预览及流程显示资源。</remarks>
|
||||
public override void Destroy()
|
||||
{
|
||||
Access.SessionChanged -= AccessChanged;
|
||||
_statisticsTimer.Stop();
|
||||
_standardSopWindow?.Close();
|
||||
_engine.Stop();
|
||||
@ -611,7 +635,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
{
|
||||
if (!CanDeleteRecipe() || SelectedRecipe is not { } fileName) return;
|
||||
if (ConfirmDeleteRecipeAsync is null) { StatusText = "请在运行设置中确认删除配方"; return; }
|
||||
_deletingRecipe = true; RaisePropertyChanged(nameof(CanSelectCamera)); RaiseCommands();
|
||||
_deletingRecipe = true; RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels)); RaiseCommands();
|
||||
var wasActive = false;
|
||||
try
|
||||
{
|
||||
@ -642,7 +666,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
LoadRecipes(SelectedRecipe);
|
||||
StatusText = "删除配方失败:" + error.Message; Log("warn", StatusText);
|
||||
}
|
||||
finally { _deletingRecipe = false; RaisePropertyChanged(nameof(CanSelectCamera)); RaiseCommands(); }
|
||||
finally { _deletingRecipe = false; RaisePropertyChanged(nameof(CanSelectCamera)); RaisePropertyChanged(nameof(CanChangeSettings)); RaisePropertyChanged(nameof(CanChangeModels)); RaiseCommands(); }
|
||||
}
|
||||
|
||||
private void ClearActiveRecipe()
|
||||
|
||||
@ -107,6 +107,10 @@ internal static class Smoke
|
||||
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
|
||||
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; }
|
||||
// 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。
|
||||
UserAccess.Current.Setup("smoke-admin", "SmokePassword123");
|
||||
if(Environment.GetCommandLineArgs().Contains("--djev-shutdown-only"))
|
||||
{
|
||||
// 注入尚未完成的启动任务,验证关闭必须先取消并等待,且重复点击不会提前销毁窗口。
|
||||
@ -1573,6 +1577,95 @@ internal static class Smoke
|
||||
Check(!lifetime.Windows.Contains(modal)&&before.SequenceEqual(File.ReadAllBytes(store.ConfigPath(config.Sop.Name))),
|
||||
"Prism右上角关闭确认不保存后释放资源并保留原文件");
|
||||
}
|
||||
/// <summary>验证角色矩阵、持久化及绕过 CanExecute 的直接调用;仅操作隔离的测试工作区。</summary>
|
||||
private static async Task CheckPermissions(App app, Window window)
|
||||
{
|
||||
var access = UserAccess.Current;
|
||||
var model = app.Container.Resolve<SopPageViewModel>();
|
||||
var navigation = app.Container.Resolve<NavigationModel>();
|
||||
void Denied(Action action, string message)
|
||||
{
|
||||
try { action(); throw new Exception("未拦截:" + message); }
|
||||
catch (Exception error) when (error is UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
||||
{ Check(true, message); }
|
||||
}
|
||||
Check(!access.IsAuthenticated && !model.StartStopCommand.CanExecute(), "未登录不能启动");
|
||||
access.Setup("admin", "AdminPassword123");
|
||||
access.SaveUser("engineer", "EngineerPassword123", UserRole.Engineer);
|
||||
access.SaveUser("operator", "OperatorPassword123", UserRole.Operator);
|
||||
Check(access.Users().Count == 3 && access.IsAdministrator && model.NewRecipeCommand.CanExecute(), "管理员创建三类账号并可编辑配方");
|
||||
Denied(() => access.SaveUser("admin", "", UserRole.Operator), "不能降级最后一名管理员");
|
||||
Denied(() => access.DeleteUser("admin"), "不能删除当前账号");
|
||||
var usersPath = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!, "workspace", "users.json");
|
||||
Check(!File.ReadAllText(usersPath).Contains("AdminPassword123"), "账号文件不保存明文密码");
|
||||
var restored = new UserAccess(usersPath);
|
||||
Check(!restored.Login("admin", "wrong") && restored.Login("ADMIN", "AdminPassword123"), "持久化账号正确验证密码并支持用户名大小写");
|
||||
Check(access.Login("engineer", "EngineerPassword123") && access.CanConfigure && !access.IsAdministrator, "工艺师具有设置权限且没有管理员权限");
|
||||
navigation.Navigate("RuntimeSettings");
|
||||
Check(navigation.Target?.ViewName == "RuntimeSettings" && model.NewRecipeCommand.CanExecute(), "工艺师可访问设置与编辑配方");
|
||||
var settings = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model);
|
||||
var dialog = new Window { Content = settings, Width = 900, Height = 900 };
|
||||
dialog.Show(); await Task.Delay(60);
|
||||
Check(!settings.FindControl<ComboBox>("DjevTierInput")!.IsEffectivelyEnabled
|
||||
&& settings.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEffectivelyEnabled, "工艺师禁用模型档位但可修改运行超时");
|
||||
var tier = model.DjevTier; model.DjevTier = tier == "lite" ? "nano" : "lite";
|
||||
Check(model.DjevTier == tier && !model.SaveDjevSelectionCommand.CanExecute(), "工艺师不能通过属性或命令修改模型档位");
|
||||
Denied(() => access.SaveUser("illegal", "Password123", UserRole.Administrator), "工艺师不能管理人员");
|
||||
var editor = new RecipeEditorViewModel();
|
||||
editor.OnDialogOpened(new DialogParameters { { "new", true } });
|
||||
var agentModel = editor.AgentModel; editor.AgentModel = "forbidden-model";
|
||||
Check(editor.AgentModel == agentModel && !editor.CanChangeAgentModels, "工艺师不能修改 Agent 模型设置");
|
||||
var stride = model.FrameStride; model.FrameStride = stride == 1 ? 2 : 1;
|
||||
Check(model.FrameStride != stride, "工艺师可以保存运行设置");
|
||||
access.Login("operator", "OperatorPassword123"); await Task.Delay(50);
|
||||
Check(!access.CanConfigure && navigation.Target?.ViewName == "SopPage", "切换操作员后立即返回运行页");
|
||||
navigation.Navigate("RuntimeSettings");
|
||||
Check(navigation.Target?.ViewName == "SopPage", "操作员不能进入设置页");
|
||||
Check(!model.NewRecipeCommand.CanExecute() && !model.EditRecipeCommand.CanExecute()
|
||||
&& !model.ApplyRecipeCommand.CanExecute() && !model.ResetCountsCommand.CanExecute()
|
||||
&& !model.PlayStandardSopCommand.CanExecute(), "操作员仅保留开始停止操作");
|
||||
Check(model.StartStopCommand.CanExecute(), "操作员可启动已配置的流程");
|
||||
model.IsRunning = true;
|
||||
Check(model.StartStopCommand.CanExecute() && !((SopHelper.VVMs.MainWindow.MainWindowViewModel)window.DataContext!).CanChangeAccount,
|
||||
"运行中操作员可以停止,且主窗口禁止切换身份");
|
||||
model.IsRunning = false;
|
||||
var previousStride = model.FrameStride;
|
||||
var previousRecipe = model.SelectedRecipe;
|
||||
model.FrameStride = previousStride == 1 ? 2 : 1; model.SelectedRecipe = "forbidden.yaml";
|
||||
model.NewRecipeCommand.Execute(); model.EditRecipeCommand.Execute(); model.ApplyRecipeCommand.Execute();
|
||||
Check(model.FrameStride == previousStride && model.SelectedRecipe == previousRecipe, "直接调用和属性写入不能绕过操作员限制");
|
||||
Check(!settings.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEffectivelyEnabled, "已打开的运行设置同步禁用");
|
||||
Denied(() => access.Users(), "操作员不能读取人员管理列表");
|
||||
access.Logout();
|
||||
Check(!model.StartStopCommand.CanExecute() && !model.NewRecipeCommand.CanExecute(), "退出登录立即收回权限");
|
||||
model.StartStopCommand.Execute();
|
||||
Check(!model.IsRunning, "未登录直接执行启动命令也被拦截");
|
||||
access.Login("admin", "AdminPassword123");
|
||||
var adminEditor = new RecipeEditorViewModel();
|
||||
adminEditor.OnDialogOpened(new DialogParameters { { "new", true } });
|
||||
adminEditor.AgentModel = "admin-model";
|
||||
Check(adminEditor.AgentModel == "admin-model" && adminEditor.CanChangeAgentModels, "管理员可以保存 Agent 模型设置");
|
||||
access.SaveUser("operator", "ResetPassword123", UserRole.Operator);
|
||||
Check(!restored.Login("operator", "ResetPassword123") && new UserAccess(usersPath).Login("operator", "ResetPassword123"), "重置密码持久化并使用新密码登录");
|
||||
access.DeleteUser("operator");
|
||||
Check(!new UserAccess(usersPath).Login("operator", "ResetPassword123"), "删除账号后不能重新登录");
|
||||
dialog.Close();
|
||||
await Task.Delay(60);
|
||||
var accountDialog = new SopHelper.VVMs.MainWindow.AccountWindow(true);
|
||||
accountDialog.Show(window); await Task.Delay(60);
|
||||
using (var accountImage = new RenderTargetBitmap(new PixelSize(440,560)))
|
||||
{
|
||||
accountImage.Render(accountDialog);
|
||||
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
|
||||
accountImage.Save(Path.Combine(output, "user-management.png"));
|
||||
}
|
||||
accountDialog.Close();
|
||||
using var rendered = new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width, (int)window.Bounds.Height));
|
||||
rendered.Render(window);
|
||||
var screenshots = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(screenshots);
|
||||
rendered.Save(Path.Combine(screenshots, "user-permissions.png"));
|
||||
}
|
||||
|
||||
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