using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nirvana.Common.ApiBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Api.DBServices;

namespace YBDevice.Api
{
    /// <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 Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (_ignore)
            {
                return Task.CompletedTask;
            }
            var token = context.HttpContext.Request.Headers["token"].ToString();
            if (!string.IsNullOrEmpty(token))
            {
                string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
                if (BaseApp.DecodeToken(token, ip))
                {
                    return Task.CompletedTask;
                }
            }
            var result = new ResultInfo { code = ResultState.NOAUTH, message = "没有访问权限" };
            context.Result = new JsonResult(result);
            return Task.CompletedTask;
        }
    }
}
