コード例 #1
0
        /// <summary>
        /// 注册激活
        /// </summary>
        /// <returns></returns>
        public ActionResult RegActivate()
        {
            string v = WebHelper.GetQueryString("v");
            //解密字符串
            string realV;

            try
            {
                realV = ShopUtils.AESDecrypt(v);
            }
            catch
            {
                //如果v来自邮件,那么需要url解码
                realV = ShopUtils.AESDecrypt(WebHelper.UrlDecode(v));
            }

            //数组第一项为uid,第二项为动作,第三项为验证时间,第四项为随机值
            string[] result = StringHelper.SplitString(realV);
            if (result.Length != 4)
            {
                return(HttpNotFound());
            }

            int      uid    = TypeHelper.StringToInt(result[0]);
            string   action = result[1];
            DateTime time   = TypeHelper.StringToDateTime(result[2]);

            //判断验证时间是否失效
            if (DateTime.Now.AddMinutes(-30) > time)
            {
                return(PromptView("此链接已经失效,请重新验证"));
            }

            UserInfo userInfo = Users.GetUserById(uid);

            if (userInfo == null)
            {
                return(PromptView("用户不存在,请重新注册"));
            }

            if (userInfo.VerifyEmail.Equals(1))
            {
                return(PromptView("用户已激活,不需要重复激活"));
            }

            //更新邮箱激活状态
            Users.UpdateUserVerityEmailByUid(uid);
            userInfo.VerifyEmail = 1;

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

            return(View());
        }
コード例 #2
0
        /// <summary>
        /// 登录
        /// </summary>
        public ActionResult Login()
        {
            string returnUrl = WebHelper.GetQueryString("returnUrl");

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

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

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

                model.ReturnUrl       = returnUrl;
                model.ShadowName      = WorkContext.ShopConfig.ShadowName;
                model.IsRemember      = WorkContext.ShopConfig.IsRemember == 1;
                model.IsVerifyCode    = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.ShopConfig.VerifyPages);
                model.OAuthPluginList = Plugins.GetOAuthPluginList();

                return(View(model));
            }

            //ajax请求
            string accountName = WebHelper.GetFormString(WorkContext.ShopConfig.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.ShopConfig.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 (BSPConfig.ShopConfig.LoginType.Contains("2") && ValidateHelper.IsEmail(accountName))//邮箱登陆
                {
                    partUserInfo = Users.GetPartUserByEmail(accountName);
                    if (partUserInfo == null)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱不存在", "}");
                    }
                }
                else if (BSPConfig.ShopConfig.LoginType.Contains("3") && ValidateHelper.IsMobile(accountName))//手机登陆
                {
                    partUserInfo = Users.GetPartUserByMobile(accountName);
                    if (partUserInfo == null)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机不存在", "}");
                    }
                }
                else if (BSPConfig.ShopConfig.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", "密码不正确", "}");
                    //}
                    if (password != 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);
                WorkContext.Uid        = partUserInfo.Uid;
                WorkContext.UserName   = partUserInfo.UserName;
                WorkContext.UserEmail  = partUserInfo.Email;
                WorkContext.UserMobile = partUserInfo.Mobile;
                WorkContext.NickName   = partUserInfo.NickName;
                //将用户信息写入cookie中
                ShopUtils.SetUserCookie(partUserInfo, (WorkContext.ShopConfig.IsRemember == 1 && isRemember == 1) ? 30 : -1, "web");

                return(AjaxResult("success", "登录成功"));
            }
        }
コード例 #3
0
        /// <summary>
        /// 注册
        /// </summary>
        public ActionResult Register()
        {
            string returnUrl = WebHelper.GetQueryString("returnUrl");

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

            if (WorkContext.ShopConfig.RegType.Length == 0)
            {
                return(PromptView(returnUrl, "目前已经关闭注册功能!"));
            }
            if (WorkContext.Uid > 0)
            {
                return(Redirect("/Home/Index"));
            }
            if (WorkContext.ShopConfig.RegTimeSpan > 0)
            {
                DateTime registerTime = Users.GetRegisterTimeByRegisterIP(WorkContext.IP);
                if ((DateTime.Now - registerTime).Minutes <= WorkContext.ShopConfig.RegTimeSpan)
                {
                    return(PromptView(returnUrl, "你注册太频繁,请间隔一定时间后再注册!"));
                }
            }

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

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

                return(View(model));
            }

            //ajax请求
            string phone       = string.Empty;
            string accountName = phone = WebHelper.GetFormString(WorkContext.ShopConfig.ShadowName).Trim().ToLower(); //手机
            string loginname   = WebHelper.GetFormString("loginname");                                                //用户名
            string password    = WebHelper.GetFormString("password");
            string confirmPwd  = WebHelper.GetFormString("confirmPwd");
            string verifyCode  = WebHelper.GetFormString("verifyCode");
            int    invitecode  = -1;

            if (WebHelper.GetFormString("pid", "") != "")
            {
                invitecode = int.Parse(WebHelper.GetFormString("pid")); //介绍用户标识号
            }
            StringBuilder errorList = new StringBuilder("[");


            if (!ValidateHelper.IsMobile(accountName))
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机号码格式错误", "}");
            }
            accountName = loginname;

            #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", "账户名必须大于5且不大于15个字符", "}");
            }
            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.ShopConfig.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", "密码必须大于6且不大于16个字符", "}");
            }
            else if (password != confirmPwd)
            {
                errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "两次输入的密码不一样", "}");
            }

            //验证码验证
            if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.ShopConfig.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 (WorkContext.ShopConfig.RegType.Contains("2") && ValidateHelper.IsEmail(accountName))//验证邮箱
                {
                    string emailProvider = CommonHelper.GetEmailProvider(accountName);
                    if (WorkContext.ShopConfig.AllowEmailProvider.Length != 0 && (!CommonHelper.IsInArray(emailProvider, WorkContext.ShopConfig.AllowEmailProvider, "\n")))
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}");
                    }
                    else if (CommonHelper.IsInArray(emailProvider, WorkContext.ShopConfig.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 (WorkContext.ShopConfig.RegType.Contains("3") && ValidateHelper.IsMobile(accountName))//验证手机
                {
                    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.ShopConfig.RegType.Contains("1"))//验证用户名
                {
                    if (accountName.Length > 15)
                    {
                        errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名长度不能超过15个字符", "}");
                    }
                    else if (OWZX.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   = phone;
                    }
                }
            }

            #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 = password; // Users.CreateUserPassword(password, userInfo.Salt);
                userInfo.UserRid  = UserRanks.GetLowestUserRank().UserRid;
                userInfo.AdminGid = 1;        //非管理员组
                if (nickName.Length > 0)
                {
                    userInfo.NickName = WebHelper.HtmlEncode(nickName);
                }
                else
                {
                    userInfo.NickName = "ow" + Randoms.CreateRandomValue(7);
                }
                userInfo.Avatar        = "";
                userInfo.PayCredits    = 0;
                userInfo.RankCredits   = 0;
                userInfo.VerifyEmail   = 0;
                userInfo.VerifyMobile  = 0;
                userInfo.UserId        = Randoms.CreateRandomValue(8);
                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"));
                userInfo.InviteCode = invitecode;
                #endregion

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

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


                //将用户信息写入cookie
                ShopUtils.SetUserCookie(userInfo, 0, "web");

                ////发送注册欢迎信息
                //if (WorkContext.ShopConfig.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", "注册成功"));
            }
        }
コード例 #4
0
        /// <summary>
        /// 回调
        /// </summary>
        public ActionResult CallBack()
        {
            //返回url
            string returnUrl = WebHelper.GetQueryString("returnUrl");

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

            if (WorkContext.ShopConfig.LoginType == "")
            {
                return(PromptView(returnUrl, "商城目前已经关闭登录功能!"));
            }
            if (WorkContext.Uid > 0)
            {
                return(PromptView(returnUrl, "您已经登录,无须重复登录!"));
            }

            //返回的随机值
            string backSalt = WebHelper.GetQueryString("state");
            //Authorization Code
            string code = WebHelper.GetQueryString("code");
            //保存在session中随机值
            string salt = Sessions.GetValueString(WorkContext.Sid, "qqAuthLoginSalt");

            if (backSalt.Length > 0 && code.Length > 0 && salt.Length > 0 && backSalt == salt)
            {
                //清空session中随机值
                Sessions.SetItem(WorkContext.Sid, "qqAuthLoginSalt", null);

                PluginSetInfo pluginSetInfo = PluginUtils.GetPluginSet();

                //构建获取Access Token的参数
                string postData = string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri=http://{3}{4}",
                                                code, pluginSetInfo.AppKey, pluginSetInfo.AppSecret, BSPConfig.ShopConfig.SiteUrl, Url.Action("CallBack"));
                //发送获得Access Token的请求
                string result = WebHelper.GetRequestData(pluginSetInfo.AuthUrl + "/oauth2.0/token", postData);
                //将返回结果解析成参数列表
                NameValueCollection parmList = WebHelper.GetParmList(result);
                //Access Token值
                string access_token = parmList["access_token"];

                //通过上一步获取的Access Token,构建获得对应用户身份的OpenID的url
                string url = string.Format("{0}/oauth2.0/me?access_token={1}", pluginSetInfo.AuthUrl, access_token);
                //发送获得OpenID的请求
                result = WebHelper.GetRequestData(url, "get", null);
                //移除返回结果开头的“callback(”和结尾的“);”字符串
                string json = StringHelper.TrimEnd(StringHelper.TrimStart(result, "callback("), ");");
                //OpenID值
                string openId = JsonConvert.DeserializeObject <PartOAuthUser>(json).OpenId;


                //判断此用户是否已经存在
                int uid = OAuths.GetUidByOpenIdAndServer(openId, pluginSetInfo.Server);
                if (uid > 0)//存在时
                {
                    PartUserInfo partUserInfo = Users.GetPartUserById(uid);
                    //更新用户最后访问
                    Users.UpdateUserLastVisit(partUserInfo.Uid, DateTime.Now, WorkContext.IP, WorkContext.RegionId);
                    //更新购物车中用户id
                    Carts.UpdateCartUidBySid(partUserInfo.Uid, WorkContext.Sid);
                    ShopUtils.SetUserCookie(partUserInfo, -1);

                    return(Redirect("/"));
                }
                else
                {
                    //获取用户信息的url
                    url = string.Format("{0}/user/get_user_info?access_token={1}&oauth_consumer_key={2}&openid={3}",
                                        pluginSetInfo.AuthUrl, access_token, pluginSetInfo.AppKey, openId);
                    //发送获取用户信息的请求
                    result = WebHelper.GetRequestData(url, "get", null);
                    //将返回结果序列化为对象
                    OAuthUser oAuthUser = JsonConvert.DeserializeObject <OAuthUser>(result);
                    if (oAuthUser.Ret == 0)//当没有错误时
                    {
                        UserInfo userInfo = OAuths.CreateOAuthUser(oAuthUser.Nickname, pluginSetInfo.UNamePrefix, openId, pluginSetInfo.Server, WorkContext.RegionId);
                        if (userInfo != null)
                        {
                            //发放注册积分
                            Credits.SendRegisterCredits(ref userInfo, DateTime.Now);
                            //更新购物车中用户id
                            Carts.UpdateCartUidBySid(userInfo.Uid, WorkContext.Sid);
                            ShopUtils.SetUserCookie(userInfo, -1);
                            return(Redirect("/"));
                        }
                        else
                        {
                            return(PartialView("用户创建失败"));
                        }
                    }
                    else
                    {
                        return(PartialView("QQ授权登录失败"));
                    }
                }
            }
            else
            {
                return(Redirect("/"));
            }
        }
コード例 #5
0
        public virtual async Task <JsonResult> Login(LoginViewModel loginModel, string returnUrl = "")
        {
            returnUrl = NormalizeReturnUrl(returnUrl);

            UserDto userDto = null;

            if (ValidateHelper.IsEmail(loginModel.UsernameOrEmailAddress))            //邮箱登录
            {
                if (!BSPConfig.ShopConfig.LoginType.Contains("2"))
                {
                    throw new UserFriendlyException("暂时不支持邮箱登录");
                }
                else
                {
                    userDto = await _userAppService.GetUserByEmailAsync(loginModel.UsernameOrEmailAddress);

                    if (userDto == null)
                    {
                        throw new UserFriendlyException("邮箱不存在");
                    }
                }
            }
            else if (ValidateHelper.IsMobile(loginModel.UsernameOrEmailAddress))
            {
                if (!BSPConfig.ShopConfig.LoginType.Contains("3"))
                {
                    throw new UserFriendlyException("暂时不支持手机登录");
                }
                else
                {
                    userDto = await _userAppService.GetUserByMobileAsync(loginModel.UsernameOrEmailAddress);

                    if (userDto == null)
                    {
                        throw new UserFriendlyException("手机不存在");
                    }
                }
            }
            else
            {
                if (!BSPConfig.ShopConfig.LoginType.Contains("1"))
                {
                    throw new UserFriendlyException("暂时不支持用户名登录");
                }
                else
                {
                    userDto = await _userAppService.GetUserByNameAsync(loginModel.UsernameOrEmailAddress);

                    if (userDto == null)
                    {
                        throw new UserFriendlyException("用户名不存在");
                    }
                }
            }

            if (userDto != null)
            {
                if (SecureHelper.MD5(loginModel.Password + userDto.Salt) != userDto.Password)
                {
                    _loginFailLogAppService.AddLoginFailTimes(WorkContext.IP, DateTime.Now);
                    throw new UserFriendlyException("密码不正确");
                }
                else if (userDto.UserRankId == 1)                //当用户等级是禁止访问等级时
                {
                    if (userDto.LiftBanTime > DateTime.Now)      //达到解禁时间
                    {
                        UserRankDto userRankDto = await _userRankAppService.GetUserRankByCredits(userDto.PayCredits);

                        UpdateUserRankByUserIdInput input = new UpdateUserRankByUserIdInput()
                        {
                            Id = userDto.Id, UserRankId = userRankDto.Id
                        };
                        await _userAppService.UpdateUserRankByUserIdAsync(input);

                        userDto.UserRankId = userRankDto.Id;
                    }
                    else
                    {
                        throw new UserFriendlyException("您的账号当前被锁定,不能访问");
                    }
                }
            }

            //删除登录失败日志
            await _loginFailLogAppService.DeleteLoginFailLogByIPAsync(CommonHelper.ConvertIPToLong(WorkContext.IP));

            //获取区域信息
            var getIPInput = new GetIPInput();

            getIPInput.IP        = WorkContext.IP;
            WorkContext.Region   = ObjectMapper.Map <Region>(await _regionAppService.GetRegionByIPAsync(getIPInput));
            WorkContext.RegionId = WorkContext.Region.Id;

            //更新用户最后访问
            UpdateUserLastVisitInput updateUserLastVisitInput = new UpdateUserLastVisitInput();

            updateUserLastVisitInput.UserId    = userDto.Id;
            updateUserLastVisitInput.VisitTime = DateTime.Now;
            updateUserLastVisitInput.IP        = WorkContext.IP;
            updateUserLastVisitInput.RegionId  = WorkContext.RegionId;
            await _userDetailAppService.UpdateUserLastVisit(updateUserLastVisitInput);

            ////更新购物车中用户id
            //Carts.UpdateCartUidBySid(partUserInfo.Uid, WorkContext.Sid);

            WorkContext.User = ObjectMapper.Map <User>(userDto);
            //将用户信息写入cookie中
            ShopUtils.SetUserCookie(WorkContext.User, (WorkContext.ShopConfig.IsRemember == 1) ? 30 : -1);

            return(Json(new AjaxResponse {
                TargetUrl = returnUrl
            }));
        }
コード例 #6
0
        /// <summary>
        /// 回调
        /// </summary>
        public ActionResult CallBack()
        {
            //返回url
            string returnUrl = WebHelper.GetQueryString("returnUrl");

            if (returnUrl.Length == 0)
            {
                returnUrl = "/";
            }
            string[] rtval = Request.QueryString.AllKeys;
            if (Array.IndexOf <string>(rtval, "code") == -1)
            {
                return(PartialView("您未授权微信登录,请重新扫描登陆"));
            }

            if (WorkContext.ShopConfig.LoginType == "")
            {
                return(PromptView(returnUrl, "目前已经关闭登陆功能!"));
            }
            if (WorkContext.Uid > 0)
            {
                return(PromptView(returnUrl, "您已经登录,无须重复登录!"));
            }
            //返回的随机值
            string backSalt = WebHelper.GetQueryString("state");
            //Authorization Code
            string code = WebHelper.GetQueryString("code");

            //获取access_token
            string tokenurl = WeiXinOAuth.GetWeiXinRqUrl(pluginSetInfo.AppID, pluginSetInfo.AppSecret, "", code, "", "", "access_token");
            WeiXinAccessTokenResult token = WeiXinOAuth.GetAccessToken(tokenurl, pluginSetInfo.AppID, pluginSetInfo.AppSecret);

            if (token.ErrorResult.errcode == 40029)
            {
                return(PartialView("获取微信授权码错误,请重新扫描登陆"));
            }


            //判断此用户是否已经存在
            int uid = OAuths.GetUidByOpenIdAndServer(token.SuccessResult.openid, pluginSetInfo.Server);

            if (uid > 0)//存在时
            {
                PartUserInfo partUserInfo = Users.GetPartUserById(uid);
                //更新用户最后访问
                Users.UpdateUserLastVisit(partUserInfo.Uid, DateTime.Now, WorkContext.IP, WorkContext.RegionId);

                ShopUtils.SetUserCookie(partUserInfo, -1, "web");

                return(Redirect("/"));
            }
            else
            {
                //获取用户信息
                string userurl = WeiXinOAuth.GetWeiXinRqUrl("", "", "", "", token.SuccessResult.openid, token.SuccessResult.access_token, "openid");
                WeiXinUserInfoResult userinfo = WeiXinOAuth.GetWeiXinUserInfo(userurl);
                if (userinfo.ErrorMsg.errcode == 40003)
                {
                    return(PartialView("获取用户信息失败,请重新扫描登陆"));
                }


                UserInfo userInfo = OAuths.CreateOAuthUser(userinfo.UserInfo.nickname, pluginSetInfo.UNamePrefix, token.SuccessResult.openid,
                                                           pluginSetInfo.Server, WorkContext.RegionId, userinfo.UserInfo.unionid);
                if (userInfo != null)
                {
                    ShopUtils.SetUserCookie(userInfo, -1, "web");
                    return(Redirect("/"));
                }
                else
                {
                    return(PartialView("用户创建失败"));
                }
            }
        }