public void Validate()
 {
     ValidateHelper.ValidateObject(this);
 }
Exemplo n.º 2
0
 /// <summary>
 /// 数字或者字母
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static bool IsNUMBER_OR_CHAR(this string s)
 {
     return(ValidateHelper.IsNUMBER_OR_CHAR(s));
 }
Exemplo n.º 3
0
 /// <summary>
 /// 是否是邮箱
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static bool IsEmail(this string s)
 {
     return(ValidateHelper.IsEmail(s));
 }
Exemplo n.º 4
0
        /// <summary>
        /// 登录
        /// </summary>
        public ActionResult Login()
        {
            string returnUrl = WebHelper.GetQueryString("returnUrl");

            if (returnUrl.Length == 0)
            {
                returnUrl = "/";
            }

            if (WorkContext.MallConfig.LoginType == "")
            {
                return(PromptView(returnUrl, "商城目前已经关闭登录功能!"));
            }
            if (WorkContext.Uid > 0)
            {
                return(PromptView(returnUrl, "您已经登录,无须重复登录!"));
            }
            if (WorkContext.MallConfig.LoginFailTimes != 0 && LoginFailLogs.GetLoginFailTimesByIp(WorkContext.IP) >= WorkContext.MallConfig.LoginFailTimes)
            {
                return(PromptView(returnUrl, "您已经输入错误" + WorkContext.MallConfig.LoginFailTimes + "次密码,请15分钟后再登录!"));
            }

            //get请求
            if (WebHelper.IsGet())
            {
                //登陆方法的思路是 get请求和ajax请求写在一起 根据 WebHelper 中的 IsGet方法返回的值确定是否是get请求如果是 get 请求则创建一个登陆模型类
                LoginModel model = new LoginModel();
                //这里给登陆模型类赋值
                model.ReturnUrl       = returnUrl;
                model.ShadowName      = WorkContext.MallConfig.ShadowName;
                model.IsRemember      = WorkContext.MallConfig.IsRemember == 1;
                model.IsVerifyCode    = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages);
                model.OAuthPluginList = Plugins.GetOAuthPluginList();
                //返回强类型视图以下ajax请求将不会调用
                return(View(model));
            }

            //ajax请求  获取用户点击登陆后表单中的值
            string accountName = WebHelper.GetFormString(WorkContext.MallConfig.ShadowName);
            string password    = WebHelper.GetFormString("password");
            string verifyCode  = WebHelper.GetFormString("verifyCode");
            int    isRemember  = WebHelper.GetFormInt("isRemember");
            //创建一个 StringBuilder 对象用来保存登陆失败信息
            StringBuilder errorList = new StringBuilder("[");

            //验证账户名
            if (string.IsNullOrWhiteSpace(accountName))
            {
                //将登陆失败信息添加到 StringBuilder 对象中
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不能为空", "}");
            }
            else if (accountName.Length < 4 || accountName.Length > 50)     //如果输入的用户名长度小于4或大于50
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名必须大于3且不大于50个字符", "}");
            }
            else if ((!SecureHelper.IsSafeSqlString(accountName, false)))   //使用 IsSafeSqlString()方法获取用户输入的用户名是否存在 SQL 注入的风险
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不存在", "}");
            }

            //验证密码
            if (string.IsNullOrWhiteSpace(password))    //如果密码为空
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不能为空", "}");
            }
            else if (password.Length < 4 || password.Length > 32)       //如果密码长度小于4或者是密码长度大于32
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码必须大于3且不大于32个字符", "}");
            }

            //验证验证码
            if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages))
            {
                if (string.IsNullOrWhiteSpace(verifyCode))  //如果验证码为空
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不能为空", "}");
                }
                else if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode"))
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不正确", "}");
                }
            }

            //当以上验证全部通过时
            PartUserInfo partUserInfo = null;            //创建部分用户信息对象

            if (errorList.Length == 1)                   //如果错误信息长度为1
            {
                if (ValidateHelper.IsEmail(accountName)) //邮箱登录
                {
                    if (!BMAConfig.MallConfig.LoginType.Contains("2"))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用邮箱登录", "}");
                    }
                    else
                    {
                        partUserInfo = Users.GetPartUserByEmail(accountName);
                        if (partUserInfo == null)
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱不存在", "}");
                        }
                    }
                }
                else if (ValidateHelper.IsMobile(accountName))//手机登录
                {
                    if (!BMAConfig.MallConfig.LoginType.Contains("3"))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用手机登录", "}");
                    }
                    else
                    {
                        partUserInfo = Users.GetPartUserByMobile(accountName);
                        if (partUserInfo == null)
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机不存在", "}");
                        }
                    }
                }
                else //用户名登录
                {
                    if (!BMAConfig.MallConfig.LoginType.Contains("1"))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用用户名登录", "}");
                    }
                    else
                    {
                        partUserInfo = Users.GetPartUserByName(accountName);
                        if (partUserInfo == null)
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名不存在", "}");
                        }
                    }
                }

                if (partUserInfo != null)
                {
                    if (Users.CreateUserPassword(password, partUserInfo.Salt) != partUserInfo.Password) //判断密码是否正确
                    {
                        LoginFailLogs.AddLoginFailTimes(WorkContext.IP, DateTime.Now);                  //增加登录失败次数
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不正确", "}");
                    }
                    else if (partUserInfo.UserRid == 1)              //当用户等级是禁止访问等级时
                    {
                        if (partUserInfo.LiftBanTime > DateTime.Now) //达到解禁时间
                        {
                            UserRankInfo userRankInfo = UserRanks.GetUserRankByCredits(partUserInfo.PayCredits);
                            Users.UpdateUserRankByUid(partUserInfo.Uid, userRankInfo.UserRid);
                            partUserInfo.UserRid = userRankInfo.UserRid;
                        }
                        else
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "您的账号当前被锁定,不能访问", "}");
                        }
                    }
                }
            }

            if (errorList.Length > 1)//验证失败时
            {
                return(AjaxResult("error", errorList.Remove(errorList.Length - 1, 1).Append("]").ToString(), true));
            }
            else//验证成功时
            {
                //删除登录失败日志
                LoginFailLogs.DeleteLoginFailLogByIP(WorkContext.IP);
                //更新用户最后访问
                Users.UpdateUserLastVisit(partUserInfo.Uid, DateTime.Now, WorkContext.IP, WorkContext.RegionId);
                //更新购物车中用户id
                Carts.UpdateCartUidBySid(partUserInfo.Uid, WorkContext.Sid);
                //将用户信息写入cookie中
                MallUtils.SetUserCookie(partUserInfo, (WorkContext.MallConfig.IsRemember == 1 && isRemember == 1) ? 30 : -1);

                return(AjaxResult("success", "登录成功"));
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// 判断是否是中文字符串
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static bool IsChineaseStr(this string s)
 {
     return(ValidateHelper.IsChineaseStr(s));
 }
Exemplo n.º 6
0
 private void CheckedParamter(string key)
 {
     ValidateHelper.Begin().NotNullOrEmpty(key, "缓存键");
 }
Exemplo n.º 7
0
        public virtual async Task <_ <LoginUserInfo> > GetLoginUserInfoByTokenAsync(string client_id, string access_token)
        {
            var data = new _ <LoginUserInfo>();

            var func = $"{nameof(AuthApiServiceFromDB)}.{nameof(GetLoginUserInfoByTokenAsync)}";
            var p    = new { client_id, access_token }.ToJson();

            if (!ValidateHelper.IsAllPlumpString(access_token, client_id))
            {
                $"验证token异常|参数为空|{func}|{p}".AddBusinessInfoLog();

                data.SetErrorMsg("参数为空");
                return(data);
            }

            var cache_expire = TimeSpan.FromMinutes(10);

            var hit_status = CacheHitStatusEnum.Hit;
            var cache_key  = this.AuthTokenCacheKey(access_token);

            //查找token
            var token = await this._cache.GetOrSetAsync(cache_key, async() =>
            {
                hit_status = CacheHitStatusEnum.NotHit;

                return(await this.FindTokenAsync(client_id, access_token));
            }, cache_expire);

            //统计缓存命中
            await this.CacheHitLog(cache_key, hit_status);

            if (token == null)
            {
                $"token不存在|{func}|{p}".AddBusinessInfoLog();

                data.SetErrorMsg("token不存在");
                return(data);
            }

            hit_status = CacheHitStatusEnum.Hit;
            cache_key  = this.AuthUserInfoCacheKey(token.UserUID);
            //查找用户
            var loginuser = await this._cache.GetOrSetAsync(cache_key, async() =>
            {
                hit_status = CacheHitStatusEnum.NotHit;

                var user = await this._loginService.GetLoginUserInfoByUserUID(token.UserUID);

                return(user);
            }, cache_expire);

            //统计缓存命中
            await this.CacheHitLog(cache_key, hit_status);

            if (loginuser == null)
            {
                $"用户不存在|{func}|{p}".AddBusinessInfoLog();

                data.SetErrorMsg("用户不存在");
                return(data);
            }

            loginuser.LoginToken   = token.UID;
            loginuser.RefreshToken = token.RefreshToken;
            loginuser.TokenExpire  = token.ExpiryTime;
            loginuser.Scopes       = token.ScopesInfoJson?.JsonToEntity <ScopeInfoModel[]>(throwIfException: false)?.Select(x => x.name).ToList();

            data.SetSuccessData(loginuser);

            return(data);
        }
Exemplo n.º 8
0
        private void btnValidate_Click(object sender, EventArgs e)
        {
            try
            {
                lblCorrectCount.Text = "0";
                lblErrorCount.Text   = "0";
                lblWarningCount.Text = "0";

                //int t1 = Environment.TickCount;

                ProgressMessage("載入資料檢查規則…");
                CourseRowValidatorFactory crv       = new CourseRowValidatorFactory(Context);
                ValidateHelper            validator = new ValidateHelper(Context, crv);
                SheetHelper sheet  = new SheetHelper(Context.SourceFile);
                TipStyles   styles = new TipStyles(sheet);

                //Console.WriteLine("載入驗證規則時間:{0}", Environment.TickCount - t1);

                validator.ProgressChanged += new ProgressChangedEventHandler(Validator_ProgressChanged);
                pgValidProgress.Value      = 0;

                //t1 = Environment.TickCount;
                ProgressMessage("驗證資料中…");
                lnkCancelValid.Visible = true;
                _cancel_validate       = false;
                cellManager            = validator.Validate(sheet);
                lnkCancelValid.Visible = false;

                //Console.WriteLine("驗證時間:{0}", Environment.TickCount - t1);

                validator.ProgressChanged -= new ProgressChangedEventHandler(Validator_ProgressChanged);

                if (_cancel_validate)
                {
                    wpValidation.NextButtonEnabled = eWizardButtonState.False;
                    ProgressMessage("資料驗證已由使用者取消…");
                    return;
                }
                else
                {
                    wpValidation.NextButtonEnabled = eWizardButtonState.True;
                }

                //t1 = Environment.TickCount;
                SummaryValidateInfo(cellManager);
                //Console.WriteLine("Summary 時間:{0}", Environment.TickCount - t1);

                //t1 = Environment.TickCount;
                sheet.ClearComments();
                sheet.SetAllStyle(styles.Default);
                foreach (CellComment each in cellManager)
                {
                    CommentItem item = each.BestComment;
                    int         row, column;
                    row    = each.RowIndex;
                    column = each.ColumnIndex;

                    if (item is CorrectComment)
                    {
                        sheet.SetComment(row, column, item.Comment);
                        sheet.SetStyle(row, column, styles.Correct);
                        sheet.SetValue(row, column, (item as CorrectComment).NewValue);
                    }

                    if (item is ErrorComment)
                    {
                        sheet.SetComment(row, column, item.Comment);
                        sheet.SetStyle(row, column, styles.Error);
                    }

                    if (item is WarningComment)
                    {
                        sheet.SetComment(row, column, item.Comment);
                        sheet.SetStyle(row, column, styles.Warning);
                    }
                }
                //Console.WriteLine("Output Errors 時間:{0}", Environment.TickCount - t1);

                sheet.SetFieldsStyle(Context.SelectedFields, styles.Header);
                sheet.Save(Context.SourceFile);
            }
            catch (Exception ex)
            {
                FISCA.Presentation.Controls.MsgBox.Show(ex.Message);
                wpValidation.NextButtonEnabled = eWizardButtonState.False;
            }
        }
Exemplo n.º 9
0
        public string ApiPath(params string[] paths)
        {
            var path = "/".Join_(paths.Where(x => ValidateHelper.IsPlumpString(x)));

            return(ServerUrl.EnsureTrailingSlash() + path);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 保存上传的商品图片
        /// </summary>
        /// <param name="storeId">店铺id</param>
        /// <param name="productImage">商品图片</param>
        /// <returns></returns>
        public static string SaveUplaodProductImage(int storeId, HttpPostedFileBase productImage)
        {
            if (productImage == null)
            {
                return("-1");
            }

            MallConfigInfo mallConfig = BMAConfig.MallConfig;

            string fileName  = productImage.FileName;
            string extension = Path.GetExtension(fileName);

            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, mallConfig.UploadImgType))
            {
                return("-2");
            }

            int fileSize = productImage.ContentLength;

            if (fileSize > mallConfig.UploadImgSize)
            {
                return("-3");
            }

            string dirPath     = IOHelper.GetMapPath(string.Format("/upload/store/{0}/product/show/", storeId));
            string name        = "ps_" + DateTime.Now.ToString("yyMMddHHmmssfffffff");
            string newFileName = name + extension;

            string[] sizeList = StringHelper.SplitString(mallConfig.ProductShowThumbSize);

            string sourceDirPath = string.Format("{0}source/", dirPath);

            if (!Directory.Exists(sourceDirPath))
            {
                Directory.CreateDirectory(sourceDirPath);
            }
            string sourcePath = sourceDirPath + newFileName;

            productImage.SaveAs(sourcePath);

            if (mallConfig.WatermarkType == 1)//文字水印
            {
                string path = string.Format("{0}{1}_text{2}", sourceDirPath, name, extension);
                IOHelper.GenerateTextWatermark(sourcePath, path, mallConfig.WatermarkText, mallConfig.WatermarkTextSize, mallConfig.WatermarkTextFont, mallConfig.WatermarkPosition, mallConfig.WatermarkQuality);
                sourcePath = path;
            }
            else if (mallConfig.WatermarkType == 2)//图片水印
            {
                string path          = string.Format("{0}{1}_img{2}", sourceDirPath, name, extension);
                string watermarkPath = IOHelper.GetMapPath("/watermarks/" + mallConfig.WatermarkImg);
                IOHelper.GenerateImageWatermark(sourcePath, watermarkPath, path, mallConfig.WatermarkPosition, mallConfig.WatermarkImgOpacity, mallConfig.WatermarkQuality);
                sourcePath = path;
            }

            foreach (string size in sizeList)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, size);
                if (!Directory.Exists(thumbDirPath))
                {
                    Directory.CreateDirectory(thumbDirPath);
                }
                string[] widthAndHeight = StringHelper.SplitString(size, "_");
                IOHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + newFileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "H");
            }
            return(newFileName);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 获取类似/home/index的url
        /// </summary>
        public static string ActionUrl(this RouteData route)
        {
            var data = route.GetA_C_A();
            var sp = new string[] { data.area, data.controller, data.action }.Where(x => ValidateHelper.IsPlumpString(x)).ToList();

            if (!ValidateHelper.IsPlumpList(sp))
            {
                throw new Exception("无法获取action访问路径");
            }
            return("/" + "/".Join_(sp));
        }
Exemplo n.º 12
0
        protected void Application_Start()
        {
            try
            {
                Action <long, string> logger = (ms, name) =>
                {
                    $"{nameof(Application_Start)}|耗时:{ms}毫秒".AddBusinessInfoLog();
                };
                using (var timer = new CpuTimeLogger(logger))
                {
                    /*
                     * if (!("config_1.json", "config_2.json").SameJsonStructure())
                     * {
                     *  throw new Exception("正式机和测试机配置文件结构不相同");
                     * }*/

                    //添加依赖注入
                    AutofacIocContext.Instance.AddExtraRegistrar(new CommonDependencyRegister());
                    AutofacIocContext.Instance.AddExtraRegistrar(new FullDependencyRegistrar());
                    AutofacIocContext.Instance.OnContainerBuilding += (ref ContainerBuilder builder) =>
                    {
                        Func <LoginStatus> _ = () => new LoginStatus($"auth_user_uid", $"auth_user_token", $"auth_user_session");

                        var server_host = string.Empty;
                        if (ValidateHelper.IsPlumpString(server_host))
                        {
                            builder.AuthBasicServerConfig(() => new AuthServerConfig(server_host), _);
                        }
                        else
                        {
                            builder.AuthBasicConfig <AuthApiProvider>(_);
                        }
                    };

                    //disable "X-AspNetMvc-Version" header name
                    MvcHandler.DisableMvcResponseHeader = true;
                    AreaRegistration.RegisterAllAreas();
                    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                    RouteConfig.RegisterRoutes(RouteTable.Routes);
                    //用AutoFac接管控制器生成,从而实现依赖注入
                    //ControllerBuilder.Current.SetControllerFactory(typeof(AutoFacControllerFactory));
                    //使用autofac生成控制器
                    DependencyResolver.SetResolver(AutofacIocContext.Instance.Container.AutofacDependencyResolver_());

                    try
                    {
                        //断网的情况下这里不会抛异常,会长时间等待
                        Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic).Execute(() =>
                        {
                            //加速首次启动EF
                            EFManager.FastStart <EntityDB>();
                            EFManager.FastStart <EpcEntityDB>();
                        });
                    }
                    catch (Exception err)
                    {
                        throw new Exception("设置EF快速启动失败", err);
                    }

#if DEBUG
                    //安装数据库
                    this.InstallDatabase();
#endif

                    //启动后台服务
                    TaskManager.Start();
                }
            }
            catch (Exception e)
            {
                e.AddErrorLog("网站启动异常");
                throw e;
            }
        }
Exemplo n.º 13
0
        private QueryContainer BuildQuery(SearchParamModel model)
        {
            var temp = new ProductListV2();
            var qc   = new QueryContainer();
            {
                var traderlist = new List <string>();
                if (!ValidateHelper.IsPlumpString(model.province))
                {
                    throw new Exception("缺少区域信息");
                }
                if (ValidateHelper.IsPlumpString(model.trader))
                {
                    if (traderlist.Contains(model.trader))
                    {
                        traderlist.Clear();
                        traderlist.Add(model.trader);
                    }
                    else
                    {
                        traderlist.Clear();
                    }
                }
                if (!ValidateHelper.IsPlumpList(traderlist))
                {
                    traderlist = new List <string>()
                    {
                        "构造一个不可能存在的值"
                    };
                }
                qc = qc && new TermsQuery()
                {
                    Field = nameof(temp.TraderId), Terms = traderlist
                };
            }
            var idlist = new string[] { };

            if (!new string[] { "2", "4" }.Contains(model.CustomerType))
            {
                qc = qc && (!new TermsQuery()
                {
                    Field = nameof(temp.UKey), Terms = idlist
                });
            }
            else
            {
                qc = qc && (!new TermsQuery()
                {
                    Field = nameof(temp.UKey), Terms = idlist
                });
            }
            if (ValidateHelper.IsPlumpString(model.brand))
            {
                var brand_sp = ConvertHelper.GetString(model.brand).Split(',').Where(x => ValidateHelper.IsPlumpString(x)).ToArray();
                qc = qc && new TermsQuery()
                {
                    Field = nameof(temp.BrandId), Terms = brand_sp
                };
            }
            if (ValidateHelper.IsPlumpString(model.catalog))
            {
                qc = qc && (new TermQuery()
                {
                    Field = nameof(temp.PlatformCatalogId), Value = model.catalog
                } ||
                            new TermsQuery()
                {
                    Field = nameof(temp.PlatformCatalogIdList), Terms = new object[] { model.catalog }
                } ||
                            new TermsQuery()
                {
                    Field = nameof(temp.ShowCatalogIdList), Terms = new object[] { model.catalog }
                });
            }
            if (model.min_price >= 0)
            {
                qc = qc && new NumericRangeQuery()
                {
                    Field = nameof(temp.SalesPrice), GreaterThanOrEqualTo = (double)model.min_price
                };
            }
            if (model.max_price >= 0)
            {
                qc = qc && new NumericRangeQuery()
                {
                    Field = nameof(temp.SalesPrice), LessThanOrEqualTo = (double)model.max_price
                };
            }

            new GeoDistanceQuery()
            {
            };
            qc = qc && new GeoDistanceRangeQuery()
            {
                Field             = "Location",
                Location          = new GeoLocation(32, 43),
                LessThanOrEqualTo = Distance.Kilometers(1)
            };

            try
            {
                if (!ValidateHelper.IsPlumpString(model.attr))
                {
                    model.attr = "[]";
                }
                var attr_list = model.attr.JsonToEntity <List <AttrParam> >();

                /*
                 * if (ValidateHelper.IsPlumpList(attr_list))
                 * {
                 *  var attr_query = new QueryContainer();
                 *  foreach (var attr in attr_list)
                 *  {
                 *      attr_query = attr_query || new TermQuery() { Field = $"{nameof(template.ProductAttributes)}.{attr.UID}", Value = attr.value };
                 *  }
                 *  qc = qc && new NestedQuery() { Path = nameof(template.ProductAttributes), Query = attr_query };
                 * }
                 */
                if (ValidateHelper.IsPlumpList(attr_list))
                {
                    //qc = qc && new TermsQuery() { Field = nameof(temp.ProductAttributes), Terms = attr_list.Select(attr => $"{attr.UID}@$@{attr.value}") };
                    foreach (var attr_key in attr_list.Select(x => x.UID).Distinct())
                    {
                        qc = qc && new TermsQuery()
                        {
                            Field = nameof(temp.ProductAttributes), Terms = attr_list.Where(x => x.UID == attr_key).Select(attr => $"{attr.UID}@$@{attr.value}")
                        };
                    }
                }
            }
            catch { }
            if (model.isGroup)
            {
                qc = qc && new TermQuery()
                {
                    Field = nameof(temp.IsGroup), Value = 1
                };
            }
            if (ValidateHelper.IsPlumpString(model.qs))
            {
                qc = qc && (new MatchQuery()
                {
                    Field = nameof(temp.ShopName), Query = model.qs, Operator = Operator.Or, MinimumShouldMatch = "100%"
                } ||
                            new MatchQuery()
                {
                    Field = nameof(temp.SeachTitle), Query = model.qs, Operator = Operator.Or, MinimumShouldMatch = "100%"
                });
            }

            qc = qc && new TermQuery()
            {
                Field = nameof(temp.PAvailability), Value = 1
            };
            qc = qc && new TermQuery()
            {
                Field = nameof(temp.UpAvailability), Value = 1
            };
            qc = qc && new TermQuery()
            {
                Field = nameof(temp.PIsRemove), Value = 0
            };
            qc = qc && new TermQuery()
            {
                Field = nameof(temp.UpIsRemove), Value = 0
            };
            qc = qc && new NumericRangeQuery()
            {
                Field = nameof(temp.SalesPrice), GreaterThan = 0
            };

            return(qc);
        }
Exemplo n.º 14
0
        public PagerData <CommentEs> QueryCommentFromEs(
            string user_product_id = null, string user_uid = null, string q = null, int page = 1, int pagesize = 10)
        {
            var data     = new PagerData <CommentEs>();
            var client   = ElasticsearchClientManager.Instance.DefaultClient.CreateClient();
            var temp     = new CommentEs();
            var tag_temp = new TagEs();

            var sd = new SearchDescriptor <CommentEs>();

            sd = sd.Index(INDEX_NAME);

            #region where
            var query = new QueryContainer();
            if (ValidateHelper.IsPlumpString(user_product_id))
            {
                query &= new TermQuery()
                {
                    Field = nameof(temp.UserProductUID), Value = user_product_id
                };
            }
            if (ValidateHelper.IsPlumpString(user_uid))
            {
                query &= new TermQuery()
                {
                    Field = nameof(temp.UserUID), Value = user_uid
                };
            }
            if (ValidateHelper.IsPlumpString(q))
            {
                query &= new MatchQuery()
                {
                    Field = nameof(temp.Comment), Query = q, Operator = Operator.Or, MinimumShouldMatch = "100%"
                };
            }
            sd = sd.Query(_ => query);
            #endregion

            #region order
            var sort = new SortDescriptor <CommentEs>();
            sort = sort.Descending(x => x.CreateTime);
            sd   = sd.Sort(_ => sort);
            #endregion

            #region aggs
            sd = sd.Aggregations(x => x
                                 .Terms("tags", av => av.Field($"{nameof(temp.Tags)}.{nameof(tag_temp.TagName)}").Size(10))
                                 .Terms("shops", av => av.Field(f => f.TraderUID).Size(10))
                                 .Average("score", av => av.Field(f => f.Score)));
            #endregion

            #region pager
            sd = sd.QueryPage_(page, pagesize);
            #endregion

            var response = client.Search <CommentEs>(_ => sd);
            response.ThrowIfException();

            data.ItemCount = (int)response.Total;
            data.DataList  = response.Documents.ToList();

            var tags_agg  = response.Aggs.Terms("tags");
            var shops_agg = response.Aggs.Terms("shops");
            var score_agg = response.Aggs.Average("score");

            return(data);
        }
Exemplo n.º 15
0
        /// <summary>
        ///   Valida las fechas ingresadas
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <history>
        ///   [vku] 28/Jul/2016 Created
        /// </history>
        private void dgrDates_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (e.EditAction == DataGridEditAction.Cancel)
            {
                isCancel = true;
            }
            else
            {
                isCancel       = false;
                changedTextBox = e.EditingElement as TextBox;
                if (changedTextBox.Text.ToString() != "")
                {
                    if (ValidateHelper.IsDate(changedTextBox.Text.ToString()))
                    {
                        string   ssd    = changedTextBox.Text.ToString();
                        DateTime ssDate = Convert.ToDateTime(ssd);
                        if (ssDate.Year == _year.Year)
                        {
                            ValidateRangeDates(ssDate, e.Column.SortMemberPath.ToString(), e.Row.IsNewItem, Convert.ToInt32(e.Row.GetIndex().ToString()));
                            if (!isCancel)
                            {
                                List <RangeDatesTraslape> lstRangeDates     = new List <RangeDatesTraslape>();
                                RangeDatesTraslape        lstRangeTranslape = new RangeDatesTraslape();
                                if (isEdit)
                                {
                                    lstRangeDates     = BRSeasons.GetRangeDatesForValidateTraslapeIsEdit(ssDate, season.ssID);
                                    lstRangeTranslape = lstRangeDates.Cast <RangeDatesTraslape>().FirstOrDefault();
                                }
                                else
                                {
                                    lstRangeDates     = BRSeasons.GetRangeDatesForValidateTraslape(ssDate);
                                    lstRangeTranslape = lstRangeDates.Cast <RangeDatesTraslape>().FirstOrDefault();
                                }
                                if (lstRangeDates.Count > 0)
                                {
                                    isCancel = true;

                                    UIHelper.ShowMessage("The date is in the range of dates " + "(" + lstRangeTranslape.sdStartD.ToShortDateString() + " to " + lstRangeTranslape.sdEndD.ToShortDateString() + ")" + " of season " + "'" + lstRangeTranslape.ssN + "'" + ". " + "Specify another date.");
                                    SeasonDate data = e.Row.DataContext as SeasonDate;
                                    if (isEdit)
                                    {
                                        string strColumn = e.Column.SortMemberPath.ToString();
                                        switch (strColumn)
                                        {
                                        case "sdStartD":
                                            changedTextBox.Text = data.sdStartD.ToShortDateString();
                                            break;

                                        case "sdEndD":
                                            changedTextBox.Text = data.sdEndD.ToShortDateString();
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        changedTextBox.Text = string.Empty;
                                    }
                                }
                                else
                                {
                                    GridHelper.UpdateSourceFromARow(sender as DataGrid);
                                }
                            }
                        }
                        else
                        {
                            isCancel = true;
                            UIHelper.ShowMessage("The date does not belong to the year being edited " + _year.Year, MessageBoxImage.Exclamation, "IM.Administrator");
                            changedTextBox.Text = string.Empty;
                        }
                    }
                    else
                    {
                        isCancel = true;
                        UIHelper.ShowMessage("Invalid Date", MessageBoxImage.Error, "IM.Administrator");
                        changedTextBox.Text = string.Empty;
                    }
                }
                else
                {
                    if (e.Column.SortMemberPath == "sdEndD")
                    {
                        UIHelper.ShowMessage("Specify a Date", MessageBoxImage.Error, "IM.Administrator");
                        e.Cancel = true;
                    }
                    else
                    {
                        isCancel = true;
                    }
                }
            }
        }
Exemplo n.º 16
0
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            //不能应用在子方法上
            if (filterContext.IsChildAction)
            {
                return;
            }

            //商城已经关闭
            if (WorkContext.MallConfig.IsClosed == 1 && WorkContext.MallAGid == 1 && WorkContext.PageKey != Url.Action("login", "account") && WorkContext.PageKey != Url.Action("logout", "account"))
            {
                WorkContext.SystemState    = "closemall";
                WorkContext.SystemStateMsg = WorkContext.MallConfig.CloseReason;
                return;
            }

            //当前时间为禁止访问时间
            if (ValidateHelper.BetweenPeriod(WorkContext.MallConfig.BanAccessTime) && WorkContext.MallAGid == 1 && WorkContext.PageKey != Url.Action("login", "account") && WorkContext.PageKey != Url.Action("logout", "account"))
            {
                WorkContext.SystemState    = "banaccesstime";
                WorkContext.SystemStateMsg = "当前时间不能访问本商城";
                return;
            }

            //当用户ip在被禁止的ip列表时
            if (ValidateHelper.InIPList(WorkContext.IP, WorkContext.MallConfig.BanAccessIP))
            {
                WorkContext.SystemState    = "banaccessip";
                WorkContext.SystemStateMsg = "您的IP被禁止访问本商城";
                return;
            }

            //当用户ip不在允许的ip列表时
            if (!string.IsNullOrEmpty(WorkContext.MallConfig.AllowAccessIP) && !ValidateHelper.InIPList(WorkContext.IP, WorkContext.MallConfig.AllowAccessIP))
            {
                WorkContext.SystemState    = "banaccessip";
                WorkContext.SystemStateMsg = "您的IP被禁止访问本商城";
                return;
            }

            //当用户IP被禁止时
            if (BannedIPs.CheckIP(WorkContext.IP))
            {
                WorkContext.SystemState    = "banaccessip";
                WorkContext.SystemStateMsg = "您的IP被禁止访问本商城";
                return;
            }

            //当用户等级是禁止访问等级时
            if (WorkContext.UserRid == 1)
            {
                WorkContext.SystemState    = "banuserrank";
                WorkContext.SystemStateMsg = "您的账号当前被锁定,不能访问";
                return;
            }

            //判断目前访问人数是否达到允许的最大人数
            if (WorkContext.OnlineUserCount > WorkContext.MallConfig.MaxOnlineCount && WorkContext.MallAGid == 1 && (WorkContext.Controller != "account" && (WorkContext.Action != "login" || WorkContext.Action != "logout")))
            {
                WorkContext.SystemState    = "maxonlinecount";
                WorkContext.SystemStateMsg = "商城人数达到访问上限, 请稍等一会再访问";
                return;
            }
        }
Exemplo n.º 17
0
 private void CheckedParamter(string key, object value)
 {
     ValidateHelper.Begin().NotNullOrEmpty(key, "缓存键").NotNull(value, "缓存数据");
 }
Exemplo n.º 18
0
        public string UploadFileToLocal()
        {
            APIResult aPIResult = new APIResult();

            try
            {
                int num  = TypeUtil.ObjectToInt(base.Request["op"]);
                int num2 = 0;
                if (num > 0)
                {
                    EnumerationList.UploadFileEnum uploadFileEnum = (EnumerationList.UploadFileEnum)Enum.Parse(typeof(EnumerationList.UploadFileEnum), num.ToString());
                    string text = "";
                    switch (uploadFileEnum)
                    {
                    case EnumerationList.UploadFileEnum.EditImg:
                        text = "/Content/Upload/Editer/";
                        num2 = 0;
                        break;

                    case EnumerationList.UploadFileEnum.MatchImg:
                        num2 = 0;
                        text = "/Content/Upload/Match/";
                        break;

                    case EnumerationList.UploadFileEnum.MobileImg:
                        num2 = 0;
                        text = "/Content/Upload/Mobile/";
                        break;

                    case EnumerationList.UploadFileEnum.PcNewsImg:
                        num2 = 0;
                        text = "/Content/Upload/PC/";
                        break;

                    case EnumerationList.UploadFileEnum.RulesImg:
                        num2 = 0;
                        text = "/Content/Upload/Rules/";
                        break;

                    case EnumerationList.UploadFileEnum.ActivityImg:
                        num2 = 0;
                        text = "/Content/Upload/Activity/";
                        break;

                    case EnumerationList.UploadFileEnum.SiteLogoImg:
                        num2 = 7;
                        text = "/Content/Upload/Site/";
                        break;

                    case EnumerationList.UploadFileEnum.SiteAdminlogoImg:
                        num2 = 8;
                        text = "/Content/Upload/Site/";
                        break;

                    case EnumerationList.UploadFileEnum.SiteMobileLogoImg:
                        num2 = 9;
                        text = "/Content/Upload/Site/";
                        break;

                    case EnumerationList.UploadFileEnum.SiteMobileRegLogoImg:
                        num2 = 10;
                        text = "/Content/Upload/Site/";
                        break;

                    case EnumerationList.UploadFileEnum.OffLinePayQrCodeImg:
                        num2 = 11;
                        text = "/Content/Upload/OffLinePayQrCode/";
                        break;
                    }
                    HttpPostedFileBase httpPostedFileBase = base.Request.Files[0];
                    if (!string.IsNullOrEmpty(text))
                    {
                        string text2 = TypeUtil.GetMapPath(text);
                        string str   = "";
                        bool   flag  = true;
                        if (num2 == 0)
                        {
                            if (!ValidateHelper.IsImgFileName(httpPostedFileBase.FileName))
                            {
                                flag            = false;
                                aPIResult.error = -2;
                                aPIResult.msg   = "上传文件的格式不对!";
                            }
                            if (httpPostedFileBase.ContentLength >= 2097152)
                            {
                                aPIResult.error = -2;
                                aPIResult.msg   = "上传文件的大小不能大于2M!";
                                flag            = false;
                            }
                            str    = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                            text2 += str;
                        }
                        if (num2 == 7)
                        {
                            str    = "logo.png";
                            text2 += str;
                        }
                        if (num2 == 8)
                        {
                            str    = "Adminlogo.png";
                            text2 += str;
                        }
                        if (num2 == 9)
                        {
                            str    = "MobileLogo.png";
                            text2 += str;
                        }
                        if (num2 == 10)
                        {
                            str    = "MobileRegLogo.png";
                            text2 += str;
                        }

                        if (num2 == 11)
                        {
                            str    = DateTime.Now.ToString("yyyyMMddHHmmss") + "_QrCode.png";
                            text2 += str;
                        }
                        if (flag)
                        {
                            string        path          = text2.Substring(0, text2.LastIndexOf("\\"));
                            DirectoryInfo directoryInfo = new DirectoryInfo(path);
                            if (!directoryInfo.Exists)
                            {
                                directoryInfo.Create();
                            }
                            FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write);
                            byte[]     @byte      = TypeUtil.GetByte(httpPostedFileBase.InputStream);
                            fileStream.Write(@byte, 0, @byte.Length);
                            fileStream.Flush();
                            fileStream.Close();
                            aPIResult.error = 0;
                            aPIResult.msg   = "上传成功";
                            aPIResult.url   = text + str;
                        }
                    }
                    else
                    {
                        aPIResult.error = -1;
                        aPIResult.msg   = "路径出错";
                    }
                }
                else
                {
                    aPIResult.error = -2;
                    aPIResult.msg   = "op出错";
                }
            }
            catch (Exception ex)
            {
                aPIResult.error = -2;
                aPIResult.msg   = "上传图片异常";
                LogUtil.WriteError(ex.ToString());
            }
            return(JsonConvert.SerializeObject(aPIResult));
        }
Exemplo n.º 19
0
        public override async Task Invoke(HttpContext context)
        {
            var provider  = context.RequestServices;
            var __context = provider.Resolve_ <IWCloudContext <UserAuthenticationMiddleware> >();

            try
            {
                if (!context.__login_required__())
                {
                    throw new MsgException("不需要登陆");
                }
                var claims     = context.User?.Claims ?? new Claim[] { };
                var subject_id = claims.GetSubjectID();
                var login_type = claims.GetAccountType();
                var login_time = claims.GetCreateTimeUtc(__context.DataSerializer);

                if (ValidateHelper.IsEmpty(subject_id))
                {
                    throw new MsgException("subject id is not found");
                }
                if (login_type != "user")
                {
                    throw new MsgException("account type is not user");
                }
                if (login_time == null)
                {
                    throw new MsgException("login time is not availabe");
                }

                var key = __context.CacheKeyManager.UserLoginInfo(subject_id);

                var data = await __context.CacheProvider.GetOrSetAsync_(key,
                                                                        () => this.__load_login_data__(provider, subject_id, login_time.Value),
                                                                        expire : TimeSpan.FromMinutes(10),
                                                                        cache_when : x => x != null);

                if (data?.User == null)
                {
                    throw new MsgException("缓存读取登录信息不存在");
                }

                var user_model = data.User;

                __context.CurrentUserInfo.UserID   = user_model.Id;
                __context.CurrentUserInfo.NickName = user_model.NickName;
                __context.CurrentUserInfo.UserName = user_model.NickName;
                __context.CurrentUserInfo.UserImg  = user_model.UserImg;

                var selected_org = data.OrgMember;
                if (selected_org != null)
                {
                    __context.CurrentUserInfo.Org ??= new OrgInfo();
                    __context.CurrentUserInfo.Org.Id      = selected_org.OrgUID;
                    __context.CurrentUserInfo.Org.IsOwner = selected_org.IsOwner > 0;
                }
            }
            catch (MsgException e)
            {
#if DEBUG
                __context.Logger.LogDebug(e.Message);
#endif
            }
            catch (Exception e)
            {
                __context.Logger.AddErrorLog("在中间件中加载登陆用户抛出异常", e);
            }
            finally
            {
                //不管是否加载成功都放行
                await this._next.Invoke(context);
            }
        }
Exemplo n.º 20
0
        public string SubmitFile(HttpPostedFileBase picFile, string fileName, int op, int height, int wight, string mode, string uploadApi)
        {
            string empty = string.Empty;
            string str   = ConfigurationManager.AppSettings["resourceurl"];

            if (picFile == null)
            {
                return(JsonConvert.SerializeObject(new
                {
                    error = -1,
                    url = "",
                    msg = "上传内容为空!"
                }));
            }
            if (string.IsNullOrEmpty(fileName))
            {
                return(JsonConvert.SerializeObject(new
                {
                    error = -4,
                    url = "",
                    msg = "文件名不能为空!"
                }));
            }
            if (op >= 1)
            {
                EnumerationList.UploadFileEnum uploadFileEnum = (EnumerationList.UploadFileEnum)Enum.Parse(typeof(EnumerationList.UploadFileEnum), op.ToString());
                UploadFileInfo uploadFileInfo = new UploadFileInfo();
                uploadFileInfo.Op       = op;
                uploadFileInfo.FileData = TypeUtil.GetByte(picFile.InputStream);
                APIResult aPIResult = new APIResult();
                try
                {
                    if (mode.ToLower() == "img")
                    {
                        string fileName2 = picFile.FileName;
                        if (!ValidateHelper.IsImgFileName(fileName2))
                        {
                            return(JsonConvert.SerializeObject(new
                            {
                                error = -2,
                                url = "",
                                msg = "上传文件的格式不对!"
                            }));
                        }
                        if (picFile.ContentLength >= 2097152)
                        {
                            return(JsonConvert.SerializeObject(new
                            {
                                error = -2,
                                url = "",
                                msg = "上传文件的大小不能大于2M!"
                            }));
                        }
                        uploadFileInfo.FileName = Path.GetFileName(fileName + ".jpg");
                        string postData = JsonConvert.SerializeObject(uploadFileInfo);
                        aPIResult = JsonConvert.DeserializeObject <APIResult>(WebRequestHelper.WebApiPost(uploadApi, postData));
                    }
                    else
                    {
                        uploadFileInfo.FileName = Path.GetFileName(picFile.FileName);
                        string postData2 = JsonConvert.SerializeObject(uploadFileInfo);
                        aPIResult = JsonConvert.DeserializeObject <APIResult>(WebRequestHelper.WebApiPost(uploadApi, postData2));
                    }
                    if (aPIResult.error == 100)
                    {
                        switch (uploadFileEnum)
                        {
                        case EnumerationList.UploadFileEnum.MatchImg:
                            return(JsonConvert.SerializeObject(new
                            {
                                error = 0,
                                url = str + "editer/" + fileName + ".jpg"
                            }));

                        case EnumerationList.UploadFileEnum.EditImg:
                            return(JsonConvert.SerializeObject(new
                            {
                                error = 0,
                                url = str + "game/" + fileName
                            }));

                        default:
                            return(empty);
                        }
                    }
                    return(JsonConvert.SerializeObject(new
                    {
                        error = -2,
                        url = "",
                        msg = aPIResult.error
                    }));
                }
                catch (Exception ex)
                {
                    LogUtil.WriteError(ex.ToString());
                    return(JsonConvert.SerializeObject(new
                    {
                        error = -2,
                        msg = "上传文件异常",
                        url = ""
                    }));
                }
            }
            return(JsonConvert.SerializeObject(new
            {
                error = -4,
                url = "",
                msg = "op不对!"
            }));
        }
Exemplo n.º 21
0
        /// <summary>
        /// 注册
        /// </summary>
        public ActionResult Register()
        {
            string returnUrl = WebHelper.GetQueryString("returnUrl");

            if (returnUrl.Length == 0)
            {
                returnUrl = "/";
            }

            if (WorkContext.MallConfig.RegType.Length == 0)
            {
                return(PromptView(returnUrl, "商城目前已经关闭注册功能!"));
            }
            if (WorkContext.Uid > 0)
            {
                return(PromptView(returnUrl, "你已经是本商城的注册用户,无需再注册!"));
            }
            if (WorkContext.MallConfig.RegTimeSpan > 0)
            {
                DateTime registerTime = Users.GetRegisterTimeByRegisterIP(WorkContext.IP);
                if ((DateTime.Now - registerTime).Minutes <= WorkContext.MallConfig.RegTimeSpan)
                {
                    return(PromptView(returnUrl, "你注册太频繁,请间隔一定时间后再注册!"));
                }
            }

            //get请求
            if (WebHelper.IsGet())
            {
                RegisterModel model = new RegisterModel();

                model.ReturnUrl    = returnUrl;
                model.ShadowName   = WorkContext.MallConfig.ShadowName;
                model.IsVerifyCode = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages);

                return(View(model));
            }

            //ajax请求
            string accountName = WebHelper.GetFormString(WorkContext.MallConfig.ShadowName).Trim().ToLower();
            string password    = WebHelper.GetFormString("password");
            string confirmPwd  = WebHelper.GetFormString("confirmPwd");
            string verifyCode  = WebHelper.GetFormString("verifyCode");

            StringBuilder errorList = new StringBuilder("[");

            #region 验证

            //账号验证
            if (string.IsNullOrWhiteSpace(accountName))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不能为空", "}");
            }
            else if (accountName.Length < 4 || accountName.Length > 50)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名必须大于3且不大于50个字符", "}");
            }
            else if (accountName.Contains(" "))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含空格", "}");
            }
            else if (accountName.Contains(":"))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含冒号", "}");
            }
            else if (accountName.Contains("<"))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含'<'符号", "}");
            }
            else if (accountName.Contains(">"))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含'>'符号", "}");
            }
            else if ((!SecureHelper.IsSafeSqlString(accountName, false)))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不符合系统要求", "}");
            }
            else if (CommonHelper.IsInArray(accountName, WorkContext.MallConfig.ReservedName, "\n"))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "此账户名不允许被注册", "}");
            }
            else if (FilterWords.IsContainWords(accountName))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名包含禁止单词", "}");
            }

            //密码验证
            if (string.IsNullOrWhiteSpace(password))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不能为空", "}");
            }
            else if (password.Length < 4 || password.Length > 32)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码必须大于3且不大于32个字符", "}");
            }
            else if (password != confirmPwd)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "两次输入的密码不一样", "}");
            }

            //验证码验证
            if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages))
            {
                if (string.IsNullOrWhiteSpace(verifyCode))
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不能为空", "}");
                }
                else if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode"))
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不正确", "}");
                }
            }

            //其它验证
            int gender = WebHelper.GetFormInt("gender");
            if (gender < 0 || gender > 2)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "gender", "请选择正确的性别", "}");
            }

            string nickName = WebHelper.GetFormString("nickName");
            if (nickName.Length > 10)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "nickName", "昵称的长度不能大于10", "}");
            }
            else if (FilterWords.IsContainWords(nickName))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "nickName", "昵称中包含禁止单词", "}");
            }

            if (WebHelper.GetFormString("realName").Length > 5)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "realName", "真实姓名的长度不能大于5", "}");
            }

            string bday = WebHelper.GetFormString("bday");
            if (bday.Length == 0)
            {
                string bdayY = WebHelper.GetFormString("bdayY");
                string bdayM = WebHelper.GetFormString("bdayM");
                string bdayD = WebHelper.GetFormString("bdayD");
                bday = string.Format("{0}-{1}-{2}", bdayY, bdayM, bdayD);
            }
            if (bday.Length > 0 && bday != "--" && !ValidateHelper.IsDate(bday))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "bday", "请选择正确的日期", "}");
            }

            string idCard = WebHelper.GetFormString("idCard");
            if (idCard.Length > 0 && !ValidateHelper.IsIdCard(idCard))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "idCard", "请输入正确的身份证号", "}");
            }

            int regionId = WebHelper.GetFormInt("regionId");
            if (regionId > 0)
            {
                if (Regions.GetRegionById(regionId) == null)
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "regionId", "请选择正确的地址", "}");
                }
                if (WebHelper.GetFormString("address").Length > 75)
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "address", "详细地址的长度不能大于75", "}");
                }
            }

            if (WebHelper.GetFormString("bio").Length > 150)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "bio", "简介的长度不能大于150", "}");
            }

            //当以上验证都通过时
            UserInfo userInfo = null;
            if (errorList.Length == 1)
            {
                if (ValidateHelper.IsEmail(accountName))//验证邮箱
                {
                    if (!WorkContext.MallConfig.RegType.Contains("2"))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用邮箱注册", "}");
                    }
                    else
                    {
                        string emailProvider = CommonHelper.GetEmailProvider(accountName);
                        if (WorkContext.MallConfig.AllowEmailProvider.Length != 0 && (!CommonHelper.IsInArray(emailProvider, WorkContext.MallConfig.AllowEmailProvider, "\n")))
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}");
                        }
                        else if (CommonHelper.IsInArray(emailProvider, WorkContext.MallConfig.BanEmailProvider, "\n"))
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}");
                        }
                        else if (Users.IsExistEmail(accountName))
                        {
                            errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱已经存在", "}");
                        }
                        else
                        {
                            userInfo          = new UserInfo();
                            userInfo.UserName = string.Empty;
                            userInfo.Email    = accountName;
                            userInfo.Mobile   = string.Empty;
                        }
                    }
                }
                else if (ValidateHelper.IsMobile(accountName))//验证手机
                {
                    if (!WorkContext.MallConfig.RegType.Contains("3"))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用手机注册", "}");
                    }
                    else if (Users.IsExistMobile(accountName))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机号已经存在", "}");
                    }
                    else
                    {
                        userInfo          = new UserInfo();
                        userInfo.UserName = string.Empty;
                        userInfo.Email    = string.Empty;
                        userInfo.Mobile   = accountName;
                    }
                }
                else//验证用户名
                {
                    if (!WorkContext.MallConfig.RegType.Contains("1"))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用用户名注册", "}");
                    }
                    else if (accountName.Length > 20)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名长度不能超过20个字符", "}");
                    }
                    else if (BrnMall.Services.Users.IsExistUserName(accountName))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名已经存在", "}");
                    }
                    else
                    {
                        userInfo          = new UserInfo();
                        userInfo.UserName = accountName;
                        userInfo.Email    = string.Empty;
                        userInfo.Mobile   = string.Empty;
                    }
                }
            }

            #endregion

            if (errorList.Length > 1)//验证失败
            {
                return(AjaxResult("error", errorList.Remove(errorList.Length - 1, 1).Append("]").ToString(), true));
            }
            else//验证成功
            {
                #region 绑定用户信息

                userInfo.Salt     = Randoms.CreateRandomValue(6);
                userInfo.Password = Users.CreateUserPassword(password, userInfo.Salt);
                userInfo.UserRid  = UserRanks.GetLowestUserRank().UserRid;
                userInfo.StoreId  = 0;
                userInfo.MallAGid = 1;//非管理员组
                if (nickName.Length > 0)
                {
                    userInfo.NickName = WebHelper.HtmlEncode(nickName);
                }
                else
                {
                    userInfo.NickName = "bma" + Randoms.CreateRandomValue(7);
                }
                userInfo.Avatar       = "";
                userInfo.PayCredits   = 0;
                userInfo.RankCredits  = 0;
                userInfo.VerifyEmail  = 0;
                userInfo.VerifyMobile = 0;

                userInfo.LastVisitIP   = WorkContext.IP;
                userInfo.LastVisitRgId = WorkContext.RegionId;
                userInfo.LastVisitTime = DateTime.Now;
                userInfo.RegisterIP    = WorkContext.IP;
                userInfo.RegisterRgId  = WorkContext.RegionId;
                userInfo.RegisterTime  = DateTime.Now;

                userInfo.Gender   = WebHelper.GetFormInt("gender");
                userInfo.RealName = WebHelper.HtmlEncode(WebHelper.GetFormString("realName"));
                userInfo.Bday     = bday.Length > 0 ? TypeHelper.StringToDateTime(bday) : new DateTime(1900, 1, 1);
                userInfo.IdCard   = WebHelper.GetFormString("idCard");
                userInfo.RegionId = WebHelper.GetFormInt("regionId");
                userInfo.Address  = WebHelper.HtmlEncode(WebHelper.GetFormString("address"));
                userInfo.Bio      = WebHelper.HtmlEncode(WebHelper.GetFormString("bio"));

                #endregion

                //创建用户
                userInfo.Uid = Users.CreateUser(userInfo);

                //添加用户失败
                if (userInfo.Uid < 1)
                {
                    return(AjaxResult("exception", "创建用户失败,请联系管理员"));
                }

                //发放注册积分
                Credits.SendRegisterCredits(ref userInfo, DateTime.Now);
                //更新购物车中用户id
                Carts.UpdateCartUidBySid(userInfo.Uid, WorkContext.Sid);
                //将用户信息写入cookie
                MallUtils.SetUserCookie(userInfo, 0);

                //发送注册欢迎信息
                if (WorkContext.MallConfig.IsWebcomeMsg == 1)
                {
                    if (userInfo.Email.Length > 0)
                    {
                        Emails.SendWebcomeEmail(userInfo.Email);
                    }
                    if (userInfo.Mobile.Length > 0)
                    {
                        SMSes.SendWebcomeSMS(userInfo.Mobile);
                    }
                }

                //同步上下文
                WorkContext.Uid        = userInfo.Uid;
                WorkContext.UserName   = userInfo.UserName;
                WorkContext.UserEmail  = userInfo.Email;
                WorkContext.UserMobile = userInfo.Mobile;
                WorkContext.NickName   = userInfo.NickName;

                return(AjaxResult("success", "注册成功"));
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// 判断用户是否有角色
 /// </summary>
 /// <param name="loginuser"></param>
 /// <param name="role"></param>
 /// <returns></returns>
 public static bool HasRole(this LoginUserInfo loginuser, string role) =>
 ValidateHelper.IsPlumpList(loginuser.Roles) && loginuser.Roles.Contains(role);
Exemplo n.º 23
0
        /// <summary>
        /// 找回密码
        /// </summary>
        public ActionResult FindPwd()
        {
            //get请求
            if (WebHelper.IsGet())
            {
                FindPwdModel model = new FindPwdModel();

                model.ShadowName   = WorkContext.MallConfig.ShadowName;
                model.IsVerifyCode = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages);

                return(View(model));
            }

            //ajax请求
            string accountName = WebHelper.GetFormString(WorkContext.MallConfig.ShadowName);
            string verifyCode  = WebHelper.GetFormString("verifyCode");

            StringBuilder errorList = new StringBuilder("[");

            //账号验证
            if (string.IsNullOrWhiteSpace(accountName))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不能为空", "}");
            }
            else if (accountName.Length < 4 || accountName.Length > 50)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名必须大于3且不大于50个字符", "}");
            }
            else if ((!SecureHelper.IsSafeSqlString(accountName)))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不存在", "}");
            }

            //验证码验证
            if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages))
            {
                if (string.IsNullOrWhiteSpace(verifyCode))
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不能为空", "}");
                }
                else if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode"))
                {
                    errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不正确", "}");
                }
            }

            //当以上验证都通过时
            PartUserInfo partUserInfo = null;

            if (errorList.Length <= 1)
            {
                if (ValidateHelper.IsEmail(accountName))//验证邮箱
                {
                    partUserInfo = Users.GetPartUserByEmail(accountName);
                    if (partUserInfo == null)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱不存在", "}");
                    }
                }
                else if (ValidateHelper.IsMobile(accountName))//验证手机
                {
                    partUserInfo = Users.GetPartUserByMobile(accountName);
                    if (partUserInfo == null)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机号不存在", "}");
                    }
                }
                else//验证用户名
                {
                    partUserInfo = Users.GetPartUserByName(accountName);
                    if (partUserInfo == null)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名不存在", "}");
                    }
                }
            }

            if (errorList.Length == 1)
            {
                if (partUserInfo.Email.Length == 0 && partUserInfo.Mobile.Length == 0)
                {
                    return(AjaxResult("nocanfind", "由于您没有设置邮箱和手机,所以不能找回此账号的密码"));
                }

                return(AjaxResult("success", Url.Action("selectfindpwdtype", new RouteValueDictionary {
                    { "uid", partUserInfo.Uid }
                })));
            }
            else
            {
                return(AjaxResult("error", errorList.Remove(errorList.Length - 1, 1).Append("]").ToString(), true));
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// 判断用户是否有权限
 /// </summary>
 public static bool HasPermission(this LoginUserInfo loginuser, string permission) =>
 ValidateHelper.IsPlumpList(loginuser.Permissions) && loginuser.Permissions.Contains(permission);
Exemplo n.º 25
0
 /// <summary>
 /// 是否是身份证号
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static bool IsIDCardNo(this string s)
 {
     return(ValidateHelper.IsIDCardNo(s));
 }
Exemplo n.º 26
0
 public bool CheckDestination(string destination)
 {
     return(ValidateHelper.IsMobile(destination));
 }
Exemplo n.º 27
0
 /// <summary>
 /// 是否是数字
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static bool IsNumber(this string s)
 {
     return(ValidateHelper.IsNumber(s));
 }
Exemplo n.º 28
0
        public static SuggestDictionary <T> SuggestSample <T>(IElasticClient client,
                                                              string index,
                                                              Expression <Func <T, object> > targetField, string text, string analyzer = null,
                                                              string highlight_pre = "<em>", string hightlight_post = "</em>", int size = 20)
            where T : class, IElasticSearchIndex
        {
            var sd = new TermSuggesterDescriptor <T>();

            sd = sd.Field(targetField).Text(text);
            if (ValidateHelper.IsPlumpString(analyzer))
            {
                sd = sd.Analyzer(analyzer);
            }
            sd = sd.Size(size);

            new CompletionSuggesterDescriptor <T>();
            new PhraseSuggesterDescriptor <T>();

            var response = client.Search <T>(s => s.Suggest(ss => ss
                                                            .Term("my-term-suggest", t => t
                                                                  .MaxEdits(1)
                                                                  .MaxInspections(2)
                                                                  .MaxTermFrequency(3)
                                                                  .MinDocFrequency(4)
                                                                  .MinWordLength(5)
                                                                  .PrefixLength(6)
                                                                  .SuggestMode(SuggestMode.Always)
                                                                  .Analyzer("standard")
                                                                  .Field("")
                                                                  .ShardSize(7)
                                                                  .Size(8)
                                                                  .Text("hello world")
                                                                  )
                                                            .Completion("my-completion-suggest", c => c
                                                                        .Contexts(ctxs => ctxs
                                                                                  .Context("color",
                                                                                           ctx => ctx.Context("")
                                                                                           )
                                                                                  )
                                                                        .Fuzzy(f => f
                                                                               .Fuzziness(Fuzziness.Auto)
                                                                               .MinLength(1)
                                                                               .PrefixLength(2)
                                                                               .Transpositions()
                                                                               .UnicodeAware(false)
                                                                               )
                                                                        .Analyzer("simple")
                                                                        .Field("")
                                                                        .Size(8)
                                                                        .Prefix("")
                                                                        )
                                                            .Phrase("my-phrase-suggest", ph => ph
                                                                    .Collate(c => c
                                                                             .Query(q => q
                                                                                    .Source("{ \"match\": { \"{{field_name}}\": \"{{suggestion}}\" }}")
                                                                                    )
                                                                             .Params(p => p.Add("field_name", "title"))
                                                                             .Prune()
                                                                             )
                                                                    .Confidence(10.1)
                                                                    .DirectGenerator(d => d
                                                                                     .Field("")
                                                                                     )
                                                                    .GramSize(1)
                                                                    .Field("")
                                                                    .Text("hello world")
                                                                    .RealWordErrorLikelihood(0.5)
                                                                    )
                                                            ));

            response.ThrowIfException();

            return(response.Suggest);
        }
Exemplo n.º 29
0
 /// <summary>
 /// 是否是URL
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static bool IsURL(this string data)
 {
     return(ValidateHelper.IsURL(data));
 }
Exemplo n.º 30
0
        public JsonMessage Insert(string menuName, string parentId, string code, string link, string icon, int sort, string type, string desc, bool isable, bool isend)
        {
            JsonMessage jsonMsg = new JsonMessage(); //返回Json
            int         result  = -1;                //类型(成功 、失败)

            _menuRep.BeginTransaction();
            try
            {
                DataTable dt = _menuRep.GetByCodeOrName(code, menuName);
                if (!ValidateHelper.IsDataTableNotData(dt))
                {
                    throw new CustomException(0, "添加失败,菜单名称或编码已存在");
                }

                SysMenuModel model = new SysMenuModel();
                model.MENU_ID     = GuidHelper.GenerateComb().ToString().ToUpper();
                model.MENU_NAME   = menuName;
                model.PARENT_ID   = parentId;
                model.MENU_CODE   = code;
                model.MENU_PATH   = link;
                model.MENU_ICON   = icon;
                model.MENU_SORT   = sort;
                model.MENU_TYPE   = type;
                model.MENU_DESC   = desc;
                model.IS_ABLED    = isable ? 1 : 0;
                model.IS_END      = isend ? 1 : 0;
                model.CREATE_USER = UserID;
                model.LM_USER     = UserID;

                result = _menuRep.Insert(model);
                if (result == 1)
                {
                    SysMenuOptModel optModel = new SysMenuOptModel();
                    optModel.MO_CODE     = "browse";
                    optModel.MO_NAME     = "浏览";
                    optModel.MENU_ID     = model.MENU_ID;
                    optModel.IS_ABLED    = 1;
                    optModel.MO_DESC     = "请勿删除,默认添加项,误删除请重新添加上";
                    optModel.CREATE_USER = UserID;
                    optModel.LM_USER     = UserID;
                    _menuOptRep.Insert(optModel);
                    _rightRep.InsertSysRight(model.CREATE_USER, model.LM_USER);
                }
                _menuRep.CommitTransaction();

                jsonMsg = ServiceResult.Message(1, "菜单添加成功");
            }
            catch (CustomException ex)
            {
                _menuRep.RollbackTransaction();
                jsonMsg = ServiceResult.Message(ex.ResultFlag, ex.Message);
            }
            catch (Exception ex)
            {
                _menuRep.RollbackTransaction();
                jsonMsg = ServiceResult.Message(-1, ex.Message);
                WriteSystemException(ex, this.GetType(), OPT_MODEL, code + ":添加系统菜单失败");
            }

            //写入log
            WriteSystemLog(jsonMsg, CREATE, OPT_MODEL, code + ":添加系统菜单");

            return(jsonMsg);
        }