点击受限操作时弹出无权限提示窗口

This commit is contained in:
tfarcraw 2026-11-23 09:01:57 +08:00
parent 0963e61a68
commit f2c3a73581
9 changed files with 105 additions and 16 deletions

View File

@ -73,7 +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; }
if (viewName != "SopPage" && !UserAccess.Current.CheckPermission(UserAccess.Current.CanConfigure, "修改配方和运行设置")) { Navigate("SopPage"); SelectedIndex = 0; return; }
Target = Pages.FirstOrDefault(n => n.ViewName == viewName);
if (Target is null) return;

View File

@ -29,6 +29,18 @@ 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<string>? PermissionDenied;
/// <summary>操作入口在执行前调用;未授权时发出提示并返回 false。</summary>
public bool CheckPermission(bool allowed, string operation)
{
if (allowed) return true;
PermissionDenied?.Invoke(IsAuthenticated
? $"当前账号无权限{operation},请联系管理员。"
: $"请先登录后再{operation}。");
return false;
}
/// <summary>读取账号文件;损坏时报告错误,禁止静默重建管理员。</summary>
public UserAccess(string path)

View File

@ -69,7 +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="ManageUsers" IsEnabled="{Binding CanChangeAccount}" IsVisible="{Binding Access.IsAdministrator}" />
<Button Content="人员管理" Click="ManageUsers" IsEnabled="{Binding CanChangeAccount}" />
</StackPanel>
<ContentControl Grid.Row="1" Grid.Column="1" prism:RegionManager.RegionName="ContentRegion" />
</Grid>

View File

@ -5,9 +5,23 @@ namespace SopHelper.VVMs.MainWindow;
/// <summary>主窗口承载账号对话框;运行期间保持登录身份不变。</summary>
public partial class MainWindow : Window
{
public MainWindow() { InitializeComponent(); }
// 同一次模态提示显示期间合并重复请求,避免连续点击堆叠窗口。
private bool _permissionPromptOpen;
public MainWindow()
{
InitializeComponent();
UserAccess.Current.PermissionDenied += ShowPermissionDenied;
Closed += (_, _) => UserAccess.Current.PermissionDenied -= ShowPermissionDenied;
}
private async void ShowPermissionDenied(string message)
{
if (_permissionPromptOpen || !IsVisible) return;
_permissionPromptOpen = true;
try { await new PermissionDeniedWindow(message).ShowDialog(OwnedWindows.LastOrDefault(w => w.IsVisible) ?? this); }
finally { _permissionPromptOpen = false; }
}
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); }
private async void ManageUsers(object? sender, RoutedEventArgs e) { if (CanChange && UserAccess.Current.CheckPermission(UserAccess.Current.IsAdministrator, "管理人员")) await new AccountWindow(true).ShowDialog(this); }
}

View File

@ -0,0 +1,24 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
namespace SopHelper.VVMs.MainWindow;
/// <summary>统一的权限拒绝提示;由主窗口模态承载,确认后返回原操作页。</summary>
public sealed class PermissionDeniedWindow : Window
{
public PermissionDeniedWindow(string message)
{
Title = "无权限";
Width = 400; SizeToContent = SizeToContent.Height; CanResize = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var panel = new StackPanel { Margin = new Thickness(24), Spacing = 18 };
panel.Children.Add(new TextBlock { Text = "无权限", FontSize = 20 });
panel.Children.Add(new TextBlock { Name = "PermissionDeniedMessage", Text = message, TextWrapping = TextWrapping.Wrap });
var confirm = new Button { Name = "ConfirmPermissionDeniedButton", Content = "确定", IsDefault = true, IsCancel = true,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right };
confirm.Click += (_, _) => Close();
panel.Children.Add(confirm);
Content = panel;
}
}

View File

@ -448,8 +448,8 @@
<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 CanChangeAgentModels}">
<StackPanel Spacing="6">
<Expander x:Name="AgentSettingsExpander" Grid.Row="1" Header="模型设置" IsExpanded="False" Margin="0,8,0,0" IsEnabled="{Binding AgentIsIdle}" Expanded="AgentSettingsExpanded">
<StackPanel Spacing="6" IsEnabled="{Binding CanChangeAgentModels}">
<Grid ColumnDefinitions="70,*">
<TextBlock Text="接口地址" VerticalAlignment="Center" />
<TextBox x:Name="AgentEndpointBox" Grid.Column="1" Text="{Binding AgentEndpoint, Mode=TwoWay}" PlaceholderText="https://你的服务/v1" />

View File

@ -29,6 +29,13 @@ public partial class RecipeEditor : UserControl
if (_model is not null) { _model.PropertyChanged -= ModelChanged; _model.AgentChatMessages.CollectionChanged -= ChatChanged; _model.ConfirmCloseAsync = null; _model.ChooseAgentApplyAsync = null; _model.ShowAgentApplyCompletedAsync = null; _ = _model.ShutdownAsync(); }
};
}
/// <summary>模型设置的标题保留点击反馈,拒绝时收起内容并显示统一权限提示。</summary>
private void AgentSettingsExpanded(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (SopHelper.Models.UserAccess.Current.CheckPermission(SopHelper.Models.UserAccess.Current.IsAdministrator, "修改 Agent 模型设置")) return;
if (sender is Expander expander) expander.IsExpanded = false;
}
private void BindModel()
{
if (!ReferenceEquals(_model, DataContext))

View File

@ -139,7 +139,7 @@ public class SopPageViewModel : ViewModelBase
// 命令接线(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());
StartStopCommand = new DelegateCommand(async () => { if (Access.CheckPermission(Access.IsAuthenticated, "启动或停止运行") && CanStart()) 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));
@ -289,11 +289,15 @@ public class SopPageViewModel : ViewModelBase
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);
bool Authorized() => administrator ? Access.IsAdministrator : Access.CanConfigure;
return new DelegateCommand(() =>
{
if (Access.CheckPermission(Authorized(), administrator ? "修改模型配置" : "执行此操作") && available()) action();
}, () => !Authorized() || available());
}
private void AccessChanged()
{

View File

@ -1583,13 +1583,27 @@ internal static class Smoke
var access = UserAccess.Current;
var model = app.Container.Resolve<SopPageViewModel>();
var navigation = app.Container.Resolve<NavigationModel>();
async Task CheckPermissionPrompt(string message)
{
await Task.Delay(40);
var prompts = window.OwnedWindows.OfType<SopHelper.VVMs.MainWindow.PermissionDeniedWindow>().ToArray();
Check(prompts.Length == 1 && prompts[0].IsVisible && prompts[0].Title == "无权限", message);
var prompt = prompts[0];
using var rendered = new RenderTargetBitmap(new PixelSize(400, (int)prompt.Bounds.Height));
rendered.Render(prompt);
var output = Path.GetFullPath("../scratch/screenshots"); Directory.CreateDirectory(output);
rendered.Save(Path.Combine(output, "permission-denied.png"));
prompt.GetVisualDescendants().OfType<Button>().Single(b => b.Name == "ConfirmPermissionDeniedButton").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
await Task.Delay(20);
Check(!prompt.IsVisible, "确定按钮关闭权限提示");
}
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(), "未登录不能启动");
Check(!access.IsAuthenticated && model.StartStopCommand.CanExecute(), "未登录保留启动按钮用于提示登录");
access.Setup("admin", "AdminPassword123");
access.SaveUser("engineer", "EngineerPassword123", UserRole.Engineer);
access.SaveUser("operator", "OperatorPassword123", UserRole.Operator);
@ -1609,21 +1623,33 @@ internal static class Smoke
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(), "工艺师不能通过属性或命令修改模型档位");
Check(model.DjevTier == tier && model.SaveDjevSelectionCommand.CanExecute(), "工艺师不能修改模型档位,保留保存按钮用于权限提示");
model.SaveDjevSelectionCommand.Execute();
await CheckPermissionPrompt("工艺师点击保存模型配置弹出无权限提示");
window.GetVisualDescendants().OfType<Button>().Single(b => Equals(b.Content, "人员管理"))
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
await CheckPermissionPrompt("工艺师点击人员管理弹出无权限提示");
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 editorView = new SopHelper.VVMs.RecipeEditor.RecipeEditor { DataContext = editor };
var modelSettings = editorView.FindControl<Expander>("AgentSettingsExpander")!;
modelSettings.IsExpanded = true;
await Task.Delay(250);
Check(!modelSettings.IsExpanded, "无权限时模型设置保持收起");
await CheckPermissionPrompt("工艺师点击 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(), "操作员仅保留开始停止操作");
await CheckPermissionPrompt("设置入口弹出无权限窗口");
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,
@ -1634,12 +1660,14 @@ internal static class Smoke
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, "直接调用和属性写入不能绕过操作员限制");
await CheckPermissionPrompt("受限配方按钮弹出提示,连续点击只显示一个窗口");
Check(!settings.FindControl<NumericUpDown>("DjevTimeoutInput")!.IsEffectivelyEnabled, "已打开的运行设置同步禁用");
Denied(() => access.Users(), "操作员不能读取人员管理列表");
access.Logout();
Check(!model.StartStopCommand.CanExecute() && !model.NewRecipeCommand.CanExecute(), "退出登录立即收回权限");
Check(model.StartStopCommand.CanExecute() && model.NewRecipeCommand.CanExecute(), "退出登录仍保留按钮点击反馈");
model.StartStopCommand.Execute();
Check(!model.IsRunning, "未登录直接执行启动命令也被拦截");
await CheckPermissionPrompt("未登录启动弹出权限提示");
access.Login("admin", "AdminPassword123");
var adminEditor = new RecipeEditorViewModel();
adminEditor.OnDialogOpened(new DialogParameters { { "new", true } });