zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
commit | author | age
921de2 1 using System;
Z 2 using Bootstrap.Admin.Pages.Extensions;
3 using Bootstrap.Admin.Pages.Shared;
4 using Bootstrap.Security.Authorization;
5 using Microsoft.AspNetCore.Components;
6 using Microsoft.AspNetCore.Components.Rendering;
7
8 namespace Bootstrap.Admin.Pages.Components
9 {
10     /// <summary>
11     /// 条件输出组件
12     /// </summary>
13     public class ConditionComponent : ComponentBase
14     {
15         /// <summary>
16         /// 获得/设置 IButtonAuthoriazation 实例
17         /// </summary>
18         [Inject]
19         protected IButtonAuthorization? ComponentAuthorization { get; set; }
20
21         /// <summary>
22         /// 获得/设置 是否显示 默认 true 显示
23         /// </summary>
24         [Parameter]
25         public bool Inverse { get; set; }
26
27         /// <summary>
28         /// 获得/设置 授权码
29         /// </summary>
30         [Parameter]
31         public string AuthKey { get; set; } = "";
32
33         /// <summary>
34         /// 获得/设置 是否显示
35         /// </summary>
36         [Parameter]
37         public bool? Condition { get; set; }
38
39         /// <summary>
40         /// 获得/设置 子控件
41         /// </summary>
42         [Parameter]
43         public RenderFragment? ChildContent { get; set; }
44
45         /// <summary>
46         /// 获得/设置 默认母版页实例
47         /// </summary>
48         [CascadingParameter(Name = "Default")]
49         public DefaultLayout? RootLayout { get; protected set; }
50
51         /// <summary>
52         /// 渲染组件方法
53         /// </summary>
54         /// <param name="builder"></param>
55         protected override void BuildRenderTree(RenderTreeBuilder builder)
56         {
57             // 授权码赋值时使用 IButtonAuthorization 服务进行判断
58             var render = false;
59             if (!string.IsNullOrEmpty(AuthKey))
60             {
61                 var task = RootLayout?.AuthenticationStateProvider.GetAuthenticationStateAsync();
62                 if (task != null)
63                 {
64                     task.Wait();
65                     var user = task.Result.User;
66                     var url = new UriBuilder(RootLayout?.NavigationManager?.Uri ?? "").Path;
67                     render = ComponentAuthorization?.Authorizate(user, url.ToMvcMenuUrl(), AuthKey) ?? false;
68                 }
69             }
70             else if (Condition.HasValue) render = Condition.Value;
71             else render = RootLayout?.Model.IsDemo ?? false;
72             if (Inverse) render = !render;
73             if (render) builder.AddContent(0, ChildContent);
74         }
75     }
76 }