using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Nirvana.Common;
using System.Threading.Tasks;
using YBDevice.NApi.Application.BusinessClient.AccountInfo;

namespace YBDevice.NApi.Handler
{
    /// <summary>
    /// JWT 授权自定义处理程序
    /// </summary>
    public class JwtHandler : AppAuthorizeHandler
    {
        /// <summary>
        /// 重写 Handler 添加自动刷新收取逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task HandleAsync(AuthorizationHandlerContext context)
        {
            // 自动刷新 token
            if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext()))
            {
                await AuthorizeHandleAsync(context);
            }
            else context.Fail();    // 授权失败
        }
        public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) 
            {
                var user = httpContext.User;
                if (user == null)
                {
                    return false;
                }
                var userid = user.FindFirst("UserId").Value;
                if (string.IsNullOrEmpty(userid))
                {
                    return true;
                }
                else
                {
                    var service = App.GetService<IBusinessService>();
                    var id = userid.ToInt();
                    return await service.CheckUserAsync(id);
                }
            }
            return false;
        }


    }
}
