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
using Bootstrap.Security.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Razor.TagHelpers;
 
namespace Bootstrap.Security.Mvc.TagHelpers
{
    /// <summary>
    /// 网页控件授权帮助类
    /// </summary>
    [HtmlTargetElement(Attributes = "asp-auth", TagStructure = TagStructure.NormalOrSelfClosing)]
    public class AuthorizateTagHelper : TagHelper
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="authorization">IButtonAuthorization 实例</param>
        /// <param name="httpContextAccessor">IHttpContextAccessor 实例</param>
        public AuthorizateTagHelper(IButtonAuthorization authorization, IHttpContextAccessor httpContextAccessor)
        {
            AuthorizationServices = authorization;
            HttpContext = httpContextAccessor.HttpContext;
        }
 
        /// <summary>
        /// 获得 按钮授权服务
        /// </summary>
        public IButtonAuthorization AuthorizationServices { get; private set; }
 
        /// <summary>
        /// 获得 请求上线文
        /// </summary>
        public HttpContext HttpContext { get; private set; }
 
        /// <summary>
        /// 获得/设置 授权键值
        /// </summary>
        [HtmlAttributeName("asp-auth")]
        public string AuthKey { get; set; } = "";
 
        /// <summary>
        /// HTML处理方法
        /// </summary>
        /// <param name="context">HTML Tag 上下文</param>
        /// <param name="output">Tag 内容流</param>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (AuthorizationServices.Authorizate(HttpContext.User, $"~{HttpContext.Request.Path}", AuthKey))
            {
                // 授权通过生成相对应的 HTML 到上下文中
                base.Process(context, output);
                return;
            }
 
            // 授权未通过时不生成相对应的 HTML
            output.SuppressOutput();
        }
    }
}