BaseController.cs 3.65 KB
using Hh.Mes.Common;
using Hh.Mes.Common.Json;
using Hh.Mes.Pojo.System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text.Json;

namespace Hh.Mes.Api.Controllers
{
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 上下文
        /// </summary>
        public HttpContext context;

        /// <summary>
        /// 获取用户 
        /// 注意配置文件(appsettings)设置【RedisDb】要和中控系统【RedisDb】保持一致,否则取不到用户信息
        /// </summary>
        public UserAuthSession GetUser(HttpContext httpContext)
        {
            try
            {
                var token = GetToken(httpContext);
                if (string.IsNullOrWhiteSpace(token))
                {
                    return null;
                }
                var json = JwtEncryption.Decode(token);
                return JsonSerializer.Deserialize<UserAuthSession>(json);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取 tokens
        /// </summary>
        public string GetToken(HttpContext httpContext)
        {
            var token = httpContext.Request.Query[Program.tokens];
            if (string.IsNullOrEmpty(token)) token = httpContext.Request.Cookies[Program.tokens];
            if (string.IsNullOrEmpty(token)) token = httpContext.Request.Headers[Program.tokens];
            return token;
        }

        public string Serialize(object result)
        {
            return JsonHelper.Instance.Serialize(result);
        }

        /// <summary> 
        /// 获取客户端ip 注意先依赖注入context
        /// </summary>
        /// <returns></returns>
        public string GetIp()
        {
            string ip = context.Connection.RemoteIpAddress.ToString();
            return ip;
        }
    }

    /// <summary>
    /// 用户验证 ,在全局忽略下,做二次保险验证
    /// </summary>
    public class ValidateUserAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                string token = context.HttpContext.Request.Query[Program.tokens];
                if (string.IsNullOrEmpty(token)) token = context.HttpContext.Request.Cookies[Program.tokens];
                if (string.IsNullOrEmpty(token)) token = context.HttpContext.Request.Headers[Program.tokens];
                if (string.IsNullOrWhiteSpace(token))
                {
                    ContextResponse(context);
                    return;
                }
                var json = JwtEncryption.Decode(token);
                var user = JsonSerializer.Deserialize<UserAuthSession>(json);
                // 可以将用户信息存储到 HttpContext.Items 供后续使用
                context.HttpContext.Items["Account"] = user.Account;
            }
            catch (Exception)
            {
                ContextResponse(context);
                return;
            }
            base.OnActionExecuting(context);
        }

        private void ContextResponse(ActionExecutingContext context)
        {
            context.HttpContext.Response.ContentType = "application/json";
            context.Result = new ContentResult
            {
                Content = "{\"code\":401,\"status\":false,\"message\":\"Tokens失效 请重新登入\",\"result\":null}",
                StatusCode = StatusCodes.Status200OK,
                ContentType = "application/json"
            };
        }
    }
}