Ejemplo n.º 1
0
        public async Task <IActionResult> LoginJson(string userName, string password, string captchaCode)
        {
            TData obj = new TData();

            if (string.IsNullOrEmpty(captchaCode))
            {
                obj.Message = "验证码不能为空";
                return(Json(obj));
            }
            if (captchaCode != new SessionHelper().GetSession("CaptchaCode").ParseToString())
            {
                obj.Message = "验证码错误,请重新输入";
                return(Json(obj));
            }
            TData <UserEntity> userObj = await sysUserBLL.CheckLogin(userName, password, (int)PlatformEnum.Web);

            if (userObj.Tag == 1)
            {
                try
                {
                    await new UserBLL().UpdateUser(userObj.Result);
                    await Operator.Instance.AddCurrent(userObj.Result.WebToken);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            string ip        = NetHelper.Ip;
            string browser   = NetHelper.Browser;
            string os        = NetHelper.GetOSVersion();
            string userAgent = NetHelper.UserAgent;

            Action taskAction = async() =>
            {
                LogLoginEntity logLoginEntity = new LogLoginEntity
                {
                    LogStatus     = userObj.Tag == 1 ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(),
                    Remark        = userObj.Message,
                    IpAddress     = ip,
                    IpLocation    = IpLocationHelper.GetIpLocation(ip),
                    Browser       = browser,
                    OS            = os,
                    ExtraRemark   = userAgent,
                    BaseCreatorId = userObj.Result?.Id
                };

                // 让底层不用获取HttpContext
                logLoginEntity.BaseCreatorId = logLoginEntity.BaseCreatorId ?? 0;

                await new LogLoginBLL().SaveForm(logLoginEntity);
            };

            AsyncTaskHelper.StartTask(taskAction);

            obj.Tag     = userObj.Tag;
            obj.Message = userObj.Message;
            return(Json(obj));
        }
Ejemplo n.º 2
0
        public IActionResult GetServerIpJson()
        {
            TData <string> obj        = new TData <string>();
            string         ip         = NetHelper.GetWanIp();
            string         ipLocation = IpLocationHelper.GetIpLocation(ip);

            obj.Data = string.Format("{0} ({1})", ip, ipLocation);
            obj.Tag  = 1;
            return(Json(obj));
        }
Ejemplo n.º 3
0
        public async Task <TData <List <LogLoginEntity> > > GetList(LogLoginListParam param)
        {
            var obj = new TData <List <LogLoginEntity> >();

            obj.Data = await _logLoginService.GetList(param);

            obj.Data.ForEach(a => a.IpLocation = IpLocationHelper.GetIpLocation(a.IpAddress));
            obj.Tag = 1;
            return(obj);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// 写日志
 /// </summary>
 /// <param name="logEntity">对象</param>
 public async Task <int> WriteLog(LogEntity logEntity)
 {
     logEntity.id               = Guid.NewGuid().ToString();
     logEntity.operate_time     = DateTime.Now;
     logEntity.is_delete        = false;
     logEntity.ip_address       = NetHelper.Ip;
     logEntity.ip_address_city  = IpLocationHelper.GetIpLocation(NetHelper.Ip);
     logEntity.browser          = NetHelper.Browser;
     logEntity.operating_system = NetHelper.GetOSVersion();
     return(await _service.BaseInsert(logEntity));
 }
Ejemplo n.º 5
0
        public async Task <TData <List <LogApiEntity> > > GetPageList(LogApiListParam param, Pagination pagination)
        {
            var obj = new TData <List <LogApiEntity> >();

            obj.Data = await _logApiService.GetPageList(param, pagination);

            obj.Data.ForEach(a => a.IpLocation = IpLocationHelper.GetIpLocation(a.IpAddress));

            obj.Total = pagination.TotalCount;
            obj.Tag   = 1;
            return(obj);
        }
Ejemplo n.º 6
0
        private IQueryable <LogApiEntity> ListFilter(LogApiListParam param)
        {
            var query = from a in _logApiEntityDB.AsQueryable()
                        join b in _userEntityDB.AsQueryable() on a.CreatorId equals b.Id
                        into ab
                        from res in ab.DefaultIfEmpty()
                        select new LogApiEntity
            {
                Id            = a.Id,
                Remark        = a.Remark,
                UserName      = res.UserName,
                ExecuteParam  = a.ExecuteParam,
                ExecuteResult = a.ExecuteResult,
                ExecuteTime   = a.ExecuteTime,
                ExecuteUrl    = a.ExecuteUrl,
                LogStatus     = a.LogStatus,
                IpAddress     = a.IpAddress,
                IpLocation    = IpLocationHelper.GetIpLocation(a.IpAddress),
                CreateTime    = a.CreateTime
            };

            if (!string.IsNullOrEmpty(param.UserName))
            {
                query = query.Where(p => p.UserName.Contains(param.UserName));
            }

            if (param.LogStatus > -1)
            {
                query = query.Where(p => p.LogStatus == param.LogStatus);
            }

            if (!string.IsNullOrEmpty(param.IpAddress))
            {
                query = query.Where(p => p.IpAddress.Contains(param.IpAddress));
            }

            if (param.StartTime.HasValue)
            {
                query = query.Where(p => p.CreateTime >= param.StartTime);
            }

            if (param.EndTime.HasValue)
            {
                query = query.Where(p => p.CreateTime <= param.EndTime.Value.AddDays(1));
            }

            return(query);
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> LoginJson(string userName, string password, string captchaCode)
        {
            TData obj = new TData();
            TData <UserEntity> userObj = await userBLL.CheckLogin(userName, password, (int)PlatformEnum.Web);

            if (userObj.Tag == 1)
            {
                await new UserBLL().UpdateUser(userObj.Data);
                await Operator.Instance.AddCurrent(userObj.Data.WebToken);
            }

            string ip        = NetHelper.Ip;
            string browser   = NetHelper.Browser;
            string os        = NetHelper.GetOSVersion();
            string userAgent = NetHelper.UserAgent;

            Action taskAction = async() =>
            {
                LogLoginEntity logLoginEntity = new LogLoginEntity
                {
                    LogStatus     = userObj.Tag == 1 ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(),
                    Remark        = userObj.Message,
                    IpAddress     = ip,
                    IpLocation    = IpLocationHelper.GetIpLocation(ip),
                    Browser       = browser,
                    OS            = os,
                    ExtraRemark   = userAgent,
                    BaseCreatorId = userObj.Data?.Id
                };

                // 让底层不用获取HttpContext
                logLoginEntity.BaseCreatorId = logLoginEntity.BaseCreatorId ?? 0;

                await logLoginBLL.SaveForm(logLoginEntity);
            };

            AsyncTaskHelper.StartTask(taskAction);

            obj.Tag     = userObj.Tag;
            obj.Message = userObj.Message;
            return(Json(obj));
        }
Ejemplo n.º 8
0
        public TData <object> GetServerInfo()
        {
            var ip                   = NetHelper.GetWanIp();                         // 服务器外网IP
            var ipLocation           = IpLocationHelper.GetIpLocation(ip);           // IP位置
            var serviceName          = Environment.MachineName;                      // 服务器名称
            var systemOs             = RuntimeInformation.OSDescription;             // 服务器系统
            var lanIp                = NetHelper.GetLanIp();                         // 局域网IP
            var osArchitecture       = RuntimeInformation.OSArchitecture.ToString(); // 系统架构
            var processorCount       = Environment.ProcessorCount.ToString();        // CPU核心数
            var frameworkDescription = RuntimeInformation.FrameworkDescription;      // .net core版本
            var ramUse               = ((double)Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB";
            var startTime            = Process.GetCurrentProcess().StartTime.ToString("yyyy-MM-dd HH:mm");

            var obj = new TData <object>();

            obj.Data = new
            {
                ip, ipLocation, serviceName, systemOs, lanIp, osArchitecture, processorCount, frameworkDescription,
                ramUse, startTime
            };
            obj.Tag = 1;
            return(obj);
        }
Ejemplo n.º 9
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            string       action = context.RouteData.Values["Action"].ParseToString();
            OperatorInfo user   = await Operator.Instance.Current();

            if (GlobalContext.SystemConfig.Demo)
            {
                if (context.HttpContext.Request.Method.ToUpper() == "POST")
                {
                    if (action.ToUpper() != "LoginJson".ToUpper() && action.ToUpper() != "CodePreviewJson".ToUpper())
                    {
                        TData obj = new TData();
                        obj.Message    = "演示模式,不允许操作";
                        context.Result = new CustomJsonResult {
                            Value = obj
                        };
                        return;
                    }
                }
            }

            var resultContext = await next();

            sw.Stop();
            string           ip            = NetHelper.Ip;
            LogOperateEntity operateEntity = new LogOperateEntity();
            var    areaName       = context.RouteData.DataTokens["area"] + "/";
            var    controllerName = context.RouteData.Values["controller"] + "/";
            string currentUrl     = "/" + areaName + controllerName + action;

            if (action.ParseToString().ToLower() != "GetServerJson".ToLower() && action.ParseToString().ToLower() != "Error".ToLower())
            {
                #region 获取请求参数
                switch (context.HttpContext.Request.Method.ToUpper())
                {
                case "GET":
                    operateEntity.ExecuteParam = context.HttpContext.Request.QueryString.Value.ParseToString();
                    break;

                case "POST":
                    Dictionary <string, string> param = new Dictionary <string, string>();
                    foreach (var item in context.ActionDescriptor.Parameters)
                    {
                        var itemType = item.ParameterType;
                        if (itemType.IsClass && itemType.Name != "String")
                        {
                            PropertyInfo[] infos = itemType.GetProperties();
                            foreach (PropertyInfo info in infos)
                            {
                                if (info.CanRead)
                                {
                                    var propertyValue = context.HttpContext.Request.Form[info.Name];
                                    if (!param.ContainsKey(info.Name))
                                    {
                                        if (!string.IsNullOrEmpty(propertyValue))
                                        {
                                            param.Add(info.Name, propertyValue);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (param.Count > 0)
                    {
                        operateEntity.ExecuteUrl  += context.HttpContext.Request.QueryString.Value.ParseToString();
                        operateEntity.ExecuteParam = TextHelper.GetSubString(JsonConvert.SerializeObject(param), 8000);
                    }
                    else
                    {
                        operateEntity.ExecuteParam = context.HttpContext.Request.QueryString.Value.ParseToString();
                    }
                    break;
                }
                #endregion

                #region 异常获取
                StringBuilder sbException = new StringBuilder();
                if (resultContext.Exception != null)
                {
                    Exception exception = resultContext.Exception;
                    sbException.AppendLine(exception.Message);
                    while (exception.InnerException != null)
                    {
                        sbException.AppendLine(exception.InnerException.Message);
                        exception = exception.InnerException;
                    }
                    sbException.AppendLine(resultContext.Exception.StackTrace);
                    operateEntity.LogStatus = OperateStatusEnum.Fail.ParseToInt();
                }
                else
                {
                    operateEntity.LogStatus = OperateStatusEnum.Success.ParseToInt();
                }
                #endregion

                #region 日志实体
                if (user != null)
                {
                    operateEntity.BaseCreatorId = user.UserId;
                }

                operateEntity.ExecuteTime   = sw.ElapsedMilliseconds.ParseToInt();
                operateEntity.IpAddress     = ip;
                operateEntity.ExecuteUrl    = currentUrl.Replace("//", "/");
                operateEntity.ExecuteResult = TextHelper.GetSubString(sbException.ToString(), 4000);
                #endregion

                Action taskAction = async() =>
                {
                    // 让底层不用获取HttpContext
                    operateEntity.BaseCreatorId = operateEntity.BaseCreatorId ?? 0;

                    // 耗时的任务异步完成
                    operateEntity.IpLocation = IpLocationHelper.GetIpLocation(ip);
                    await new LogOperateBLL().SaveForm(operateEntity);
                };
                AsyncTaskHelper.StartTask(taskAction);
            }
        }
Ejemplo n.º 10
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            string       action = context.RouteData.Values["Action"].ParseToString();
            OperatorInfo user   = await Operator.Instance.Current();

            if (GlobalContext.SystemConfig.Demo)
            {
                if (context.HttpContext.Request.Method.ToUpper() == "POST")
                {
                    string[] allowAction = new string[] { "LoginJson", "ExportUserJson", "CodePreviewJson" };
                    if (!allowAction.Select(p => p.ToUpper()).Contains(action.ToUpper()))
                    {
                        TData obj = new TData();
                        obj.Message    = "演示模式,不允许操作";
                        context.Result = new JsonResult(obj);
                        return;
                    }
                }
            }

            var resultContext = await next();

            sw.Stop();
            string           ip            = NetHelper.Ip;
            LogOperateEntity operateEntity = new LogOperateEntity();
            var    areaName       = context.RouteData.DataTokens["area"] + "/";
            var    controllerName = context.RouteData.Values["controller"] + "/";
            string currentUrl     = "/" + areaName + controllerName + action;

            string[] notLogAction = new string[] { "GetServerJson", "Error" };
            if (!notLogAction.Select(p => p.ToUpper()).Contains(action.ToUpper()))
            {
                #region 获取请求参数
                switch (context.HttpContext.Request.Method.ToUpper())
                {
                case "GET":
                    operateEntity.ExecuteParam = context.HttpContext.Request.QueryString.Value.ParseToString();
                    break;

                case "POST":
                    if (context.ActionArguments?.Count > 0)
                    {
                        operateEntity.ExecuteUrl  += context.HttpContext.Request.QueryString.Value.ParseToString();
                        operateEntity.ExecuteParam = TextHelper.GetSubString(JsonConvert.SerializeObject(context.ActionArguments), 8000);
                    }
                    else
                    {
                        operateEntity.ExecuteParam = context.HttpContext.Request.QueryString.Value.ParseToString();
                    }
                    break;
                }
                #endregion

                #region 异常获取
                StringBuilder sbException = new StringBuilder();
                if (resultContext.Exception != null)
                {
                    Exception exception = resultContext.Exception;
                    sbException.AppendLine(exception.Message);
                    while (exception.InnerException != null)
                    {
                        sbException.AppendLine(exception.InnerException.Message);
                        exception = exception.InnerException;
                    }
                    sbException.AppendLine(resultContext.Exception.StackTrace);
                    operateEntity.LogStatus = OperateStatusEnum.Fail.ParseToInt();
                }
                else
                {
                    operateEntity.LogStatus = OperateStatusEnum.Success.ParseToInt();
                }
                #endregion

                #region 日志实体
                if (user != null)
                {
                    operateEntity.BaseCreatorId = user.UserId;
                }

                operateEntity.ExecuteTime   = sw.ElapsedMilliseconds.ParseToInt();
                operateEntity.IpAddress     = ip;
                operateEntity.ExecuteUrl    = currentUrl.Replace("//", "/");
                operateEntity.ExecuteResult = TextHelper.GetSubString(sbException.ToString(), 4000);
                #endregion

                Action taskAction = async() =>
                {
                    // 让底层不用获取HttpContext
                    operateEntity.BaseCreatorId = operateEntity.BaseCreatorId ?? 0;

                    // 耗时的任务异步完成
                    operateEntity.IpLocation = IpLocationHelper.GetIpLocation(ip);
                    await new LogOperateBLL().SaveForm(operateEntity);
                };
                AsyncTaskHelper.StartTask(taskAction);
            }
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> LoginJson(string userName, string password, string captchaCode)
        {
            TData obj = new TData();

            if (string.IsNullOrEmpty(captchaCode))
            {
                obj.Message = "验证码不能为空";
                return(Json(obj));
            }
            if (captchaCode != new SessionHelper().GetSession("CaptchaCode").ParseToString())
            {
                obj.Message = "验证码错误,请重新输入";
                return(Json(obj));
            }
            // TData<UserEntity> userObj = await userBLL.CheckLogin(userName, password, (int)PlatformEnum.Web);
            TData <UserEntity> userObj = await userBLL.CheckLogin(userName, password);

            if (userObj.Tag == 1)
            {
                // await new UserBLL().UpdateUser(userObj.Data);
                // await Operator.Instance.AddCurrent(userObj.Data.WebToken);
            }

            await _operator.AddCurrent(userObj.Data.ApiToken);

            string ip        = NetHelper.Ip;
            string browser   = NetHelper.Browser;
            string os        = NetHelper.GetOSVersion();
            string userAgent = NetHelper.UserAgent;

            Action taskAction = async() =>
            {
                LogLoginEntity logLoginEntity = new LogLoginEntity
                {
                    LogStatus   = userObj.Tag == 1 ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(),
                    Remark      = userObj.Message,
                    IpAddress   = ip,
                    IpLocation  = IpLocationHelper.GetIpLocation(ip),
                    Browser     = browser,
                    OS          = os,
                    ExtraRemark = userAgent,
                    // BaseCreatorId = userObj.Data?.Id
                };

                // 让底层不用获取HttpContext
                // logLoginEntity.BaseCreatorId = logLoginEntity.BaseCreatorId ?? 0;

                await logLoginBLL.SaveForm(logLoginEntity);
            };
            // AsyncTaskHelper.StartTask(taskAction);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userObj.Data.UserName),
                new Claim("ApiToken", userObj.Data.ApiToken),
            };

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties();
            await NetHelper.HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

            obj.Tag     = userObj.Tag;
            obj.Message = userObj.Message;
            return(Json(obj));
        }
Ejemplo n.º 12
0
        public async Task <TData <OperatorInfo> > Login([FromForm] string userName, [FromForm] string password)
        {
            var obj     = new TData <OperatorInfo>();
            var userObj = await _userBLL.CheckLogin(userName, password);

            if (userObj.Tag == 1)
            {
                await _userBLL.UpdateLoginInfo(userObj.Data);

                await _operatorCache.AddCurrent(userObj.Data.ApiToken);

                obj.Data = await _operatorCache.Current(userObj.Data.ApiToken);
            }

            obj.Message = userObj.Message;

            var ip        = NetHelper.Ip;
            var browser   = NetHelper.Browser;
            var os        = NetHelper.GetOSVersion();
            var userAgent = NetHelper.UserAgent;

            var logLoginEntity = new LogLoginEntity
            {
                LogStatus = userObj.Tag == 1
                    ? OperateStatusEnum.Success.ParseToInt()
                    : OperateStatusEnum.Fail.ParseToInt(),
                Remark      = userObj.Message,
                IpAddress   = ip,
                IpLocation  = IpLocationHelper.GetIpLocation(ip),
                Browser     = browser,
                OS          = os,
                ExtraRemark = userAgent,
                CreatorId   = userObj.Data == null ? 0 : userObj.Data.Id,
                CreateTime  = DateTime.Now
            };

            await _logLoginBLL.SaveForm(logLoginEntity);

            if (userObj.Tag == 0)
            {
                return(obj);
            }

            // 生成前端的token
            // 生成 token
            var jwtSettings    = App.GetOptions <JWTSettingsOptions>();
            var datetimeOffset = DateTimeOffset.UtcNow;

            var accessToken = JWTEncryption.Encrypt(jwtSettings.IssuerSigningKey, new Dictionary <string, object>
            {
                { "UserId", userObj.Data.Id.ToString() }, // 存储Id
                { "Account", userObj.Data.UserName },     // 存储用户名
                { "ApiToken", userObj.Data.ApiToken },    // ApiToken
                { JwtRegisteredClaimNames.Iat, datetimeOffset.ToUnixTimeSeconds() },
                { JwtRegisteredClaimNames.Nbf, datetimeOffset.ToUnixTimeSeconds() },
                {
                    JwtRegisteredClaimNames.Exp,
                    DateTimeOffset.UtcNow.AddSeconds(jwtSettings.ExpiredTime.Value * 60).ToUnixTimeSeconds()
                },
                { JwtRegisteredClaimNames.Iss, jwtSettings.ValidIssuer },
                { JwtRegisteredClaimNames.Aud, jwtSettings.ValidAudience }
            });

            // 覆盖apitoken,因为前端需要的是jwt生成的token,而缓存使用的是数据库的apitoken字段
            obj.Data.JwtToken = accessToken;

            obj.Tag = userObj.Tag;

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userObj.Data.UserName),
                new Claim("ApiToken", userObj.Data.ApiToken),
            };

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties();
            await NetHelper.HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

            return(obj);
        }