public JsonResult ChangePassword(string oldpassword, string password) { if (string.IsNullOrWhiteSpace(oldpassword) || string.IsNullOrWhiteSpace(password)) { Result result = new Result() { success = false, msg = "密码不能为空!" }; return(Json(result)); } UserMemberInfo currentUser = base.CurrentUser; string str = SecureHelper.MD5(string.Concat(SecureHelper.MD5(oldpassword), currentUser.PasswordSalt)); bool flag = false; if (str == currentUser.Password) { flag = true; } if (currentUser.PasswordSalt.StartsWith("o")) { flag = true; } if (!flag) { Result result1 = new Result() { success = false, msg = "旧密码错误" }; return(Json(result1)); } ServiceHelper.Create <IMemberService>().ChangePassWord(currentUser.Id, password); Result result2 = new Result() { success = true, msg = "修改成功" }; return(Json(result2)); }
/// <summary> /// 优惠劵类型列表 /// </summary> /// <param name="couponTypeName">优惠劵类型名称</param> /// <param name="type">类型0代表正在发放,1代表正在使用,-1代表全部</param> /// <param name="pageNumber">当前页数</param> /// <param name="pageSize">每页数</param> /// <returns></returns> public ActionResult CouponTypeList(string couponTypeName, int type = -1, int pageNumber = 1, int pageSize = 15) { if (!SecureHelper.IsSafeSqlString(couponTypeName)) { couponTypeName = ""; } string condition = AdminCoupons.AdminGetCouponTypeListCondition(WorkContext.StoreId, type, couponTypeName); PageModel pageModel = new PageModel(pageSize, pageNumber, AdminCoupons.AdminGetCouponTypeCount(condition)); CouponTypeListModel model = new CouponTypeListModel() { CouponTypeList = AdminCoupons.AdminGetCouponTypeList(pageModel.PageSize, pageModel.PageNumber, condition), PageModel = pageModel, Type = type, CouponTypeName = couponTypeName }; List <SelectListItem> itemList = new List <SelectListItem>(); itemList.Add(new SelectListItem() { Text = "全部", Value = "-1" }); itemList.Add(new SelectListItem() { Text = "正在发放", Value = "0" }); itemList.Add(new SelectListItem() { Text = "正在使用", Value = "1" }); ViewData["typeList"] = itemList; MallUtils.SetAdminRefererCookie(string.Format("{0}?pageNumber={1}&pageSize={2}&CouponTypeName={3}&type={4}", Url.Action("coupontypelist"), pageModel.PageNumber, pageModel.PageSize, couponTypeName, type)); return(View(model)); }
protected override object ChangePayPwdByCertificate(string certificate, string password) { if (string.IsNullOrWhiteSpace(password)) { return(ErrorResult("密码不能为空")); } certificate = SecureHelper.AESDecrypt(certificate, _encryptKey); long userId = long.TryParse(certificate.Split(':')[0], out userId) ? userId : 0; if (userId == 0) { throw new MallException("数据异常"); } var _iMemberCapitalService = ServiceProvider.Instance <IMemberCapitalService> .Create; _iMemberCapitalService.SetPayPwd(userId, password); return(SuccessResult("支付密码修改成功")); }
protected override object ChangePasswordByOldPassword(string oldPassword, string password) { if (string.IsNullOrWhiteSpace(password)) { return(ErrorResult("密码不能为空")); } CheckUserLogin(); var user = CurrentUser; var pwd = SecureHelper.MD5(SecureHelper.MD5(oldPassword) + user.PasswordSalt); if (pwd == user.Password) { ShopBranchApplication.UpdateShopBranchManagerPwd(user.Id, password); return(SuccessResult("密码修改成功")); } return(ErrorResult("旧密码输入不正确")); }
/// <summary> /// CheckUserNameAndPwd /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public async Task <UserModel> IsValidUserCredentials(string userName, string password) { if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { throw new HXException(HXExceptionCode.AUTH_FAILED, "用户名或者密码为空", HXExceptionLevel.Warning); } var user = await userRepository.GetUser(userName); if (user == null) { throw new HXException(HXExceptionCode.USER_NOT_EXISTS, "用户不存在", HXExceptionLevel.Warning); } string encryptedPassword = SecureHelper.MD5(password); //一次MD5加密 string encryptedWithSaltPassword = SecureHelper.MD5AddingSalt(password, user.PasswordSalt); //加盐MD5 if (encryptedWithSaltPassword.ToLower() != user.Password.ToLower()) { throw new HXException(HXExceptionCode.AUTH_FAILED, "密码错误", HXExceptionLevel.Warning); } return(Mapper.Map <UserModel>(user)); }
public void AddSellerManager(ManagerInfo model, string currentSellerName) { if (model.RoleId == 0) { throw new MallException("权限组选择不正确!"); } if (CheckUserNameExist(model.UserName)) { throw new MallException("该用户名已存在!"); } if (model.ShopId == 0) { throw new MallException("没有权限进行该操作!"); } model.PasswordSalt = Guid.NewGuid().ToString(); model.CreateDate = DateTime.Now; var pwd = SecureHelper.MD5(model.Password); model.Password = SecureHelper.MD5(pwd + model.PasswordSalt); DbFactory.Default.Add(model); }
internal static string GetFullFileName(string path, string contentType) { var href = Path.GetFileNameWithoutExtension(path); var category = GetCategoryFromPath(path); var hrefTokenSource = href; if (Uri.IsWellFormedUriString(href, UriKind.Relative)) { hrefTokenSource = (SecureHelper.IsSecure() ? "https" : "http") + href; } var hrefToken = string.Concat(HttpServerUtility.UrlTokenEncode(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(hrefTokenSource)))); if (string.Compare(contentType, "text/css", StringComparison.OrdinalIgnoreCase) == 0) { return(string.Format("/{0}/css/{1}.css", category, hrefToken)); } return(string.Format("/{0}/javascript/{1}.js", category, hrefToken)); }
public static async Task <string> BaiduTranslate(string q, string from, string to) { if (!ValidateHelper.IsAllPlumpString(q)) { return(q); } if (!ValidateHelper.IsAllPlumpString(from, to)) { throw new Exception("from or to is empty"); } var appid = "20160923000029191"; var securityid = "4rjkaBYXiu1IK7QsvBOh"; var salt = Com.GetRandomNumString(10); var md5 = SecureHelper.GetMD5($"{appid}{q}{salt}{securityid}").ToLower(); //q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4 var url = "http://api.fanyi.baidu.com/api/trans/vip/translate"; var trans = string.Empty; var dict = new Dictionary <string, string>(); dict["q"] = EncodingHelper.UrlEncode(q); dict["from"] = from; dict["to"] = to; dict["appid"] = appid; dict["salt"] = salt; dict["sign"] = md5; var urlparam = $"{url}?{dict.ToUrlParam()}"; //trans = await HttpClientHelper.GetAsync(urlparam); trans = await p.ExecuteAsync(async() => await HttpClientHelper.GetAsync(urlparam)); if (!ValidateHelper.IsPlumpString(trans)) { throw new Exception("翻译失败"); } return(trans); }
public bool ChangeSellerManager(ManagerInfo info, UserMemberInfo userInfo) { ManagerInfo roleId = context.ManagerInfo.FindBy((ManagerInfo item) => item.Id == info.Id && item.ShopId == info.ShopId).FirstOrDefault(); UserMemberInfo memberInfo = context.UserMemberInfo.FindById <UserMemberInfo>(userInfo.Id); if (roleId == null || memberInfo == null) { throw new HimallException("该管理员不存在,或者已被删除!"); } if (info.RoleId != 0 && roleId.RoleId != 0) { roleId.RoleId = info.RoleId; } if (!string.IsNullOrWhiteSpace(info.Password)) { string str = SecureHelper.MD5(info.Password); roleId.Password = SecureHelper.MD5(string.Concat(str, roleId.PasswordSalt)); memberInfo.Password = SecureHelper.MD5(string.Concat(userInfo.Password, memberInfo.PasswordSalt)); } roleId.RealName = info.RealName; roleId.Remark = info.Remark; memberInfo.RealName = userInfo.RealName; memberInfo.Remark = userInfo.Remark; if (userInfo.Email != memberInfo.Email) { memberInfo.Email = userInfo.Email; } int i = context.SaveChanges(); Cache.Remove(CacheKeyCollection.Seller(info.Id)); Cache.Remove(CacheKeyCollection.Member(userInfo.Id)); if (i >= 0) { return(true); } else { return(false); } }
public void ChangeSellerManagerPassword(long id, long shopId, string password, long roleId) { var model = Context.ManagerInfo.FindBy(item => item.Id == id && item.ShopId == shopId).FirstOrDefault(); if (model == null) { throw new HimallException("该管理员不存在,或者已被删除!"); } if (roleId != 0 && model.RoleId != 0) { model.RoleId = roleId; } if (!string.IsNullOrWhiteSpace(password)) { var pwd = SecureHelper.MD5(password); model.Password = SecureHelper.MD5(pwd + model.PasswordSalt); } Context.SaveChanges(); string CACHE_MANAGER_KEY = CacheKeyCollection.Seller(id); Core.Cache.Remove(CACHE_MANAGER_KEY); }
public async Task <Response> InsertToCart(Cart cart, Book book, int quantity) { try { var originalID = book.Id.Length < 18 ? book.Id : SecureHelper.GetOriginalInput(book.Id); var checkCartBook = await context.CartBook .Where(x => x.BookId.Equals(originalID) && x.CartId.Equals(cart.Id)) .FirstOrDefaultAsync(); if (checkCartBook is null) { var cartBook = new CartBook { BookId = book.Id.Length < 18 ? book.Id : SecureHelper.GetOriginalInput(book.Id), CartId = cart.Id, PickedDate = DateTime.Now, Quantity = quantity, SubTotal = book.CurrentPrice }; context.CartBook.Add(cartBook); await context.SaveChangesAsync(); return(new Response("Success", true, 1, cartBook)); } else { checkCartBook.Quantity += quantity; checkCartBook.SubTotal += book.CurrentPrice * quantity; context.CartBook.Update(checkCartBook); await context.SaveChangesAsync(); return(new Response("Success", true, 1, checkCartBook)); } } catch (Exception e) { return(Response.CatchError(e.Message)); } }
public void AddSellerManager(ManagerInfo model, string currentSellerName) { if (model.RoleId == 0) { throw new HimallException("权限组选择不正确!"); } if (CheckUserNameExist(model.UserName, false)) { throw new HimallException("该用户名已存在!"); } if (model.ShopId == 0) { throw new HimallException("没有权限进行该操作!"); } model.PasswordSalt = Guid.NewGuid().ToString(); model.CreateDate = DateTime.Now; string str = SecureHelper.MD5(model.Password); model.Password = SecureHelper.MD5(string.Concat(str, model.PasswordSalt)); context.ManagerInfo.Add(model); context.SaveChanges(); }
public void ChangeSellerManager(ManagerInfo info) { ManagerInfo roleId = context.ManagerInfo.FindBy((ManagerInfo item) => item.Id == info.Id && item.ShopId == info.ShopId).FirstOrDefault(); if (roleId == null) { throw new HimallException("该管理员不存在,或者已被删除!"); } if (info.RoleId != 0 && roleId.RoleId != 0) { roleId.RoleId = info.RoleId; } if (!string.IsNullOrWhiteSpace(info.Password)) { string str = SecureHelper.MD5(info.Password); roleId.Password = SecureHelper.MD5(string.Concat(str, roleId.PasswordSalt)); } roleId.RealName = info.RealName; roleId.Remark = info.Remark; context.SaveChanges(); Cache.Remove(CacheKeyCollection.Seller(info.Id)); }
/// <summary> /// 优惠劵列表 /// </summary> /// <param name="sn">编号</param> /// <param name="couponTypeId">优惠劵类型id</param> /// <param name="pageNumber">当前页数</param> /// <param name="pageSize">每页数</param> /// <returns></returns> public ActionResult CouponList(string sn, string accountName, int couponTypeId = -1, int pageNumber = 1, int pageSize = 15) { CouponTypeInfo couponTypeInfo = AdminCoupons.AdminGetCouponTypeById(couponTypeId); if (couponTypeInfo == null) { return(PromptView("优惠劵类型不存在")); } if (couponTypeInfo.StoreId != WorkContext.StoreId) { return(PromptView("不能操作其它店铺的优惠劵类型")); } int uid = AdminUsers.GetUidByAccountName(accountName); if (!SecureHelper.IsSafeSqlString(sn)) { sn = ""; } string condition = AdminCoupons.AdminGetCouponListCondition(sn, uid, couponTypeId); PageModel pageModel = new PageModel(pageSize, pageNumber, AdminCoupons.AdminGetCouponCount(condition)); CouponListModel model = new CouponListModel() { CouponList = AdminCoupons.AdminGetCouponList(pageModel.PageSize, pageModel.PageNumber, condition), PageModel = pageModel, AccountName = accountName, CouponTypeId = couponTypeId, SN = sn }; MallUtils.SetAdminRefererCookie(string.Format("{0}?pageNumber={1}&pageSize={2}&couponTypeId={3}&sn={4}&accountName={5}", Url.Action("couponlist"), pageModel.PageNumber, pageModel.PageSize, couponTypeId, sn, accountName)); return(View(model)); }
public JsonResult Charge(string pluginId, decimal amount) { amount = Math.Round(amount, 2); if (amount <= 0M) { return(base.Json(new { success = false, msg = "请输入正确的金额" })); } Plugin <IPaymentPlugin> plugin = PluginsManagement.GetPlugin <IPaymentPlugin>(pluginId); ChargeDetail model = new ChargeDetail { ChargeAmount = amount, ChargeStatus = ChargeDetailInfo.ChargeDetailStatus.WaitPay, ChargeWay = plugin.PluginInfo.DisplayName, CreateTime = DateTime.Now, MemId = base.CurrentUser.Id }; long num = MemberCapitalApplication.AddChargeApply(model); string cookie = WebHelper.GetCookie("Himall-User_OpenId"); if (!string.IsNullOrWhiteSpace(cookie)) { cookie = SecureHelper.AESDecrypt(cookie, "Mobile"); } else { MemberOpenId id = MemberApplication.GetMemberOpenIdInfoByuserId(base.CurrentUser.Id, MemberOpenIdInfo.AppIdTypeEnum.Payment, ""); if (id != null) { cookie = id.OpenId; } } string str2 = base.Request.Url.Scheme + "://" + base.Request.Url.Authority; string notifyUrl = string.Concat(new object[] { str2, "/m-", base.PlatformType, "/Payment/CapitalChargeNotify/", plugin.PluginInfo.PluginId.Replace(".", "-") }); string returnUrl = string.Concat(new object[] { str2, "/m-", base.PlatformType, "/Capital/Index" }); string str5 = plugin.Biz.GetRequestUrl(returnUrl, notifyUrl, num.ToString(), amount, "会员充值", cookie); return(base.Json(new { href = str5, success = true })); }
public void ChangePlatformManagerPassword(long id, string password, long roleId) { var model = DbFactory.Default.Get <ManagerInfo>().Where(item => item.Id == id && item.ShopId == 0).FirstOrDefault(); if (model == null) { throw new MallException("该管理员不存在,或者已被删除!"); } if (roleId != 0 && model.RoleId != 0) { model.RoleId = roleId; } if (!string.IsNullOrWhiteSpace(password)) { var pwd = SecureHelper.MD5(password); model.Password = SecureHelper.MD5(pwd + model.PasswordSalt); } DbFactory.Default.Update(model); string CACHE_MANAGER_KEY = CacheKeyCollection.Manager(id); Core.Cache.Remove(CACHE_MANAGER_KEY); }
public ActionResult SqlInjection(SecureHelper helper) { string sqlToExecute = "delete from People where Id = @id"; string connectionString = _context.Database.Connection.ConnectionString; int rowsAffected = 0; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(sqlToExecute, connection); command.Parameters.AddWithValue("@id", helper.Statement); connection.Open(); rowsAffected = command.ExecuteNonQuery(); } //Now reload data, set attributes and reload previous view SecureHelper newHelper = new SecureHelper(_context); newHelper.ProcessedStatement = sqlToExecute; newHelper.RowsAffected = rowsAffected; return(View("SqlInjection", newHelper)); }
private string AssembleQueryConfigUrl() { string url = string.Empty; if (_setting.UseServiceDiscovery && _loadBalancerHouse != null) { var _load = _loadBalancerHouse.Get(_setting.ServiceName, "RoundRobin").GetAwaiter().GetResult(); var HostAndPort = _load.Lease().GetAwaiter().GetResult(); url = $"{HostAndPort.ToUri()}"; } else { url = _setting.ServerUrl; } string appId = _setting.AppId; string secret = _setting.AppSercet; var uri = $"{url.TrimEnd('/')}/configs/{_setting.AppId}/{_setting.NamespaceName}"; var query = $"version={_config.Version}"; var sign = $"appId={appId}&appSecret={secret}&namespaceName={_setting.NamespaceName}"; return($"{uri}?{query}&sign=" + SecureHelper.SHA256(sign)); }
/// <summary> /// 根据用户名 密码 获取用户信息 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="msg"></param> /// <returns></returns> public SYS_USER_INFO GetLoginModel(string username, string password, ref string msg) { SYS_USER_INFO model = null; try { //判断admin是否存在 DynamicParameters param = new DynamicParameters(); param.Add("UserName", username); string querysql = @"SELECT * FROM SYS_USER_INFO WHERE UserName=@UserName"; SYS_USER_INFO temp = idal.FindOne <SYS_USER_INFO>(querysql, param, false); if (temp == null) { msg = "用户名不存在"; } else { if (SecureHelper.AESDecrypt(temp.PassWord) == password) { msg = "登录成功"; model = temp; } else { msg = "密码错误"; } } } catch (Exception ex) { Logger.Error(string.Format("【{0}】登录异常,异常信息:{1}", username, ex.ToString())); } return(model); }
public object UpdateShopPassword(StorePasswordInfoModel model, string userKey) { try { long userId = UserCookieEncryptHelper.Decrypt(userKey, CookieKeysCollection.USERROLE_SELLERADMIN); IMemberService iMenberService = ServiceProvider.Instance <IMemberService> .Create; IManagerService iManagerService = ServiceProvider.Instance <IManagerService> .Create; IShopService iShopService = ServiceProvider.Instance <IShopService> .Create; UserMemberInfo memberInfo = iMenberService.GetMember(userId); if (memberInfo != null) { //修改用户账号信息 string encryptedPassword = SecureHelper.MD5(model.password); //一次MD5加密 string encryptedWithSaltPassword = SecureHelper.MD5(encryptedPassword + memberInfo.PasswordSalt); //一次结果加盐后二次加密 memberInfo.Password = encryptedWithSaltPassword; iMenberService.UpdateMemberInfo(memberInfo); //修改商家账号信息 ManagerInfo manager = iManagerService.GetSellerManager(memberInfo.Id); manager.Password = model.password; iManagerService.ChangeSellerManager(manager); //登录 ServiceProvider.Instance <IManagerService> .Create.Login(memberInfo.CellPhone, model.password); return(Json(new { success = true, msg = UserCookieEncryptHelper.Encrypt(manager.Id, CookieKeysCollection.USERROLE_SELLERADMIN) })); } else { return(Json(new { success = false, msg = "修改失败" })); } } catch (Exception ex) { return(Json(new { success = false, msg = ex.ToString() })); } }
/// <summary> /// 商品咨询列表 /// </summary> public ActionResult ProductConsultList() { int pid = WebHelper.GetQueryInt("pid"); int consultTypeId = WebHelper.GetQueryInt("consultTypeId"); string consultMessage = WebHelper.GetQueryString("consultMessage"); int page = WebHelper.GetQueryInt("page"); //判断商品是否存在 PartProductInfo productInfo = Products.GetPartProductById(pid); if (productInfo == null) { return(PromptView("/", "你访问的商品不存在")); } if (!SecureHelper.IsSafeSqlString(consultMessage)) { return(PromptView(WorkContext.UrlReferrer, "您搜索的内容不存在")); } PageModel pageModel = new PageModel(10, page, ProductConsults.GetProductConsultCount(pid, consultTypeId, consultMessage)); ProductConsultListModel model = new ProductConsultListModel() { ProductInfo = productInfo, CategoryInfo = Categories.GetCategoryById(productInfo.CateId), BrandInfo = Brands.GetBrandById(productInfo.BrandId), ConsultTypeId = consultTypeId, ConsultMessage = consultMessage, PageModel = pageModel, ProductConsultList = ProductConsults.GetProductConsultList(pageModel.PageSize, pageModel.PageNumber, pid, consultTypeId, consultMessage), ProductConsultTypeList = ProductConsults.GetProductConsultTypeList(), IsVerifyCode = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.ShopConfig.VerifyPages) }; return(View(model)); }
/// <summary> /// 新闻列表 /// </summary> public ActionResult List() { string newsTitle = WebHelper.GetQueryString("newsTitle"); int newsTypeId = WebHelper.GetQueryInt("newsTypeId"); int page = WebHelper.GetQueryInt("page"); if (!SecureHelper.IsSafeSqlString(newsTitle)) { return(PromptView(WorkContext.UrlReferrer, "您搜索的新闻不存在")); } string condition = News.GetNewsListCondition(newsTypeId, newsTitle); PageModel pageModel = new PageModel(10, page, News.GetNewsCount(condition)); NewsListModel model = new NewsListModel() { PageModel = pageModel, NewsList = News.GetNewsList(pageModel.PageSize, pageModel.PageNumber, condition), NewsTitle = newsTitle, NewsTypeId = newsTypeId, NewsTypeList = News.GetNewsTypeList() }; return(View(model)); }
public void ChangeSellerManager(ManagerInfo info) { var model = DbFactory.Default.Get <ManagerInfo>().Where(item => item.Id == info.Id && item.ShopId == info.ShopId).FirstOrDefault(); if (model == null) { throw new MallException("该管理员不存在,或者已被删除!"); } if (info.RoleId != 0 && model.RoleId != 0) { model.RoleId = info.RoleId; } if (!string.IsNullOrWhiteSpace(info.Password)) { var pwd = SecureHelper.MD5(info.Password); model.Password = SecureHelper.MD5(pwd + model.PasswordSalt); } model.RealName = info.RealName; model.Remark = info.Remark; DbFactory.Default.Update(model); string CACHE_MANAGER_KEY = CacheKeyCollection.Seller(info.Id); Core.Cache.Remove(CACHE_MANAGER_KEY); }
private Uri GetUriShared(string domain, string path) { return(new Uri(string.Format("{0}{1}", SecureHelper.IsSecure(HttpContextAccessor?.HttpContext, Options) ? _cnameSSL : _cname, MakePath(domain, path)))); }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); WorkContext.IsHttpAjax = WebHelper.IsAjax(); WorkContext.IP = WebHelper.GetIP(); WorkContext.RegionInfo = Regions.GetRegionByIP(WorkContext.IP); WorkContext.RegionId = WorkContext.RegionInfo.RegionId; WorkContext.Url = WebHelper.GetUrl(); WorkContext.UrlReferrer = WebHelper.GetUrlReferrer(); //获得用户唯一标示符sid WorkContext.Sid = ShopUtils.GetSidCookie(); if (WorkContext.Sid.Length == 0) { //生成sid WorkContext.Sid = Sessions.GenerateSid(); //将sid保存到cookie中 ShopUtils.SetSidCookie(WorkContext.Sid); } PartUserInfo partUserInfo; //获得用户id int uid = ShopUtils.GetUidCookie(); if (uid < 1)//当用户为游客时 { //创建游客 partUserInfo = Users.CreatePartGuest(); } else//当用户为会员时 { //获得保存在cookie中的密码 string encryptPwd = ShopUtils.GetCookiePassword(); //防止用户密码被篡改为危险字符 if (encryptPwd.Length == 0 || !SecureHelper.IsBase64String(encryptPwd)) { //创建游客 partUserInfo = Users.CreatePartGuest(); encryptPwd = string.Empty; ShopUtils.SetUidCookie(-1); ShopUtils.SetCookiePassword(""); } else { partUserInfo = Users.GetPartUserByUidAndPwd(uid, ShopUtils.DecryptCookiePassword(encryptPwd)); if (partUserInfo != null) { //发放登陆积分 Credits.SendLoginCredits(ref partUserInfo, DateTime.Now); } else//当会员的账号或密码不正确时,将用户置为游客 { partUserInfo = Users.CreatePartGuest(); encryptPwd = string.Empty; ShopUtils.SetUidCookie(-1); ShopUtils.SetCookiePassword(""); } } WorkContext.EncryptPwd = encryptPwd; } //设置用户等级 if (UserRanks.IsBanUserRank(partUserInfo.UserRid) && partUserInfo.LiftBanTime <= DateTime.Now) { UserRankInfo userRankInfo = UserRanks.GetUserRankByCredits(partUserInfo.PayCredits); Users.UpdateUserRankByUid(partUserInfo.Uid, userRankInfo.UserRid); partUserInfo.UserRid = userRankInfo.UserRid; } WorkContext.PartUserInfo = partUserInfo; WorkContext.Uid = partUserInfo.Uid; WorkContext.UserName = partUserInfo.UserName; WorkContext.UserEmail = partUserInfo.Email; WorkContext.UserMobile = partUserInfo.Mobile; WorkContext.Password = partUserInfo.Password; WorkContext.NickName = partUserInfo.NickName; WorkContext.Avatar = partUserInfo.Avatar; WorkContext.UserRid = partUserInfo.UserRid; WorkContext.UserRankInfo = UserRanks.GetUserRankById(partUserInfo.UserRid); WorkContext.UserRTitle = WorkContext.UserRankInfo.Title; //设置用户管理员组 WorkContext.AdminGid = partUserInfo.AdminGid; WorkContext.AdminGroupInfo = AdminGroups.GetAdminGroupById(partUserInfo.AdminGid); WorkContext.AdminGTitle = WorkContext.AdminGroupInfo.Title; //设置当前控制器类名 WorkContext.Controller = RouteData.Values["controller"].ToString().ToLower(); //设置当前动作方法名 WorkContext.Action = RouteData.Values["action"].ToString().ToLower(); WorkContext.PageKey = string.Format("/{0}/{1}", WorkContext.Controller, WorkContext.Action); }
private string GetPasswrodWithTwiceEncode(string password, string salt) { string str = SecureHelper.MD5(password); return(SecureHelper.MD5(string.Concat(str, salt))); }
private Uri GetUriShared(string domain, string path) { return(new Uri(String.Format("{0}{1}", SecureHelper.IsSecure() ? _cnameSSL : _cname, MakePath(domain, path)))); }
/// <summary> /// 创建用户密码 /// </summary> /// <param name="password">真实密码</param> /// <param name="salt">散列盐值</param> /// <returns></returns> public static string CreateUserPassword(string password, string salt) { return(SecureHelper.MD5(password + salt)); }
/// <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 (ModelState.IsValid) { 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)); } }
/// <summary> /// 登录 /// </summary> public ActionResult Login() { string returnUrl = WebHelper.GetQueryString("returnUrl"); if (returnUrl.Length == 0) { returnUrl = Url.Action("index", "home"); } 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()) { 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(); 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 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, false))) { 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个字符", "}"); } //验证验证码 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 (BMAConfig.MallConfig.LoginType.Contains("2") && ValidateHelper.IsEmail(accountName))//邮箱登陆 { partUserInfo = Users.GetPartUserByEmail(accountName); if (partUserInfo == null) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱不存在", "}"); } } else if (BMAConfig.MallConfig.LoginType.Contains("3") && ValidateHelper.IsMobile(accountName))//手机登陆 { partUserInfo = Users.GetPartUserByMobile(accountName); if (partUserInfo == null) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机不存在", "}"); } } else if (BMAConfig.MallConfig.LoginType.Contains("1"))//用户名登陆 { 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", "登录成功")); } }