using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;

namespace YBDevice.Web.Handler
{
    /// <summary>
    /// JWT 授权自定义处理程序
    /// </summary>
    public class JwtHandler : AppAuthorizeHandler
    {
        /// <summary>
        /// 重写 Handler 添加自动刷新收取逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task HandleAsync(AuthorizationHandlerContext context)
        {
            // 常规授权（可以判断是不是第三方）
            // var isAuthenticated = context.User.Identity.IsAuthenticated;
            // 获取当前数据库上下文
            var httpContext = context.GetCurrentHttpContext();
            // 自动刷新 token
            if (httpContext !=null && JWTEncryption.AutoRefreshToken(context, httpContext))
            {
                await AuthorizeHandleAsync(context);
            }
            else context.Fail();    // 授权失败
        }
        public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) return Task.FromResult(true);

            return Task.FromResult(true);
        }


    }
}
