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