using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nirvana.Common.ApiBase;
using System;
using System.Threading.Tasks;
using YBDevice.NApi.Application;

namespace YBDevice.NApi
{
    /// <summary>
    /// 接口权限验证
    /// </summary>
    public class ApiAuthorizeFilter : Attribute, IAsyncAuthorizationFilter
    {
        private bool _ignore = false;
        public ApiAuthorizeFilter(bool ignore = false)
        {
            _ignore = ignore;
        }
        /// <summary>
        /// 权限校检
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (_ignore)
            {
                return;
            }
            var token = context.HttpContext.Request.Headers["token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
                if (await BaseService.DecodeTokenAsync(token, ip))
                {
                    return;
                }
            }
            var result = new ResultInfo { code = ResultState.NOAUTH, message = "没有访问权限" };
            context.Result = new JsonResult(result);
            return;
        }
    }
}
