Exemplo n.º 1
0
        /// <summary>
        /// 语言选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void language_SelectedIndexChanged(Object sender, EventArgs e)
        {
            String value = Language.SelectedValue;

            if (sender is Page)
            {
                String cookie = CookieHelper.GetValue("Language");
                if (!String.IsNullOrEmpty(cookie))
                {
                    value = cookie;
                    Language.SelectedValue = value;
                }
            }
            CookieHelper.AddCookie("Language", value);

            var config = SiteParameter.Config;
            var lang   = config.Languages.Find(a => { return(a.language == value); });

            if (lang == null)
            {
                lang = new Language();
            }
            this.SetFormValue(lang);
            this.SetFormValue(config);

            //BadKeywords.Text = String.Join(",", config.BadKeywords);
            BadKeywords.Text      = "";
            ViewState["keywords"] = JsonConvert.SerializeObject(config.BadKeywords);
            ViewState["options"]  = JsonConvert.SerializeObject(config.DataTypeOptions);
        }
Exemplo n.º 2
0
        public ActionResult On(LogOnModel model)
        {
            LogOnModel logger = _logOn.GetLogOnModelByName(model.UserName);

            if (logger == null)
            {
                ModelState.AddModelError(nameof(model.UserName), "* 用户名不存在或输入错误,请检查用户名并重新输入");
                return(View(model));
            }
            if (logger.Password != model.Password.MD5Encrypt())
            {
                ModelState.AddModelError(nameof(model.Password), "* 密码输入错误,请检查密码并重新输入");
                return(View(model));
            }
            if (Session["captcha"] == null)
            {
                throw new Exception();
            }
            if (model.Captcha != Session["captcha"].ToString())
            {
                ModelState.AddModelError(nameof(model.Captcha), "* 验证码输入不正确,请重新输入");
                return(View(model));
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            CookieHelper.AddCookie((int)logger.UserId, model.Password);
            return(View());
        }
Exemplo n.º 3
0
        public OAuthData ProcessLogin(HttpContextBase context)
        {
            if (!Enabled)
            {
                return(null);
            }
            //should have a SamlOAuthClient.oauthTokeyQuerystringKey which corresponds to the current cookie to decrypt
            string tokenKey = HttpContext.Current.Request[oauthTokeyQuerystringKey];

            if (!string.IsNullOrEmpty(tokenKey))
            {
                var samlTokenData = SamlTokenData.GetTokenDataFromDatabase(tokenKey);
                if (samlTokenData == null)
                {
                    throw new ArgumentException("The SAML token was not found in the HttpContext.Current.Request, or could not be extracted.  Please ensure cookies are enabled and try again");
                }

                //Store our token key so we can retrieve it later to raise the SamlUserCreated and SamlAuthenticated events and delete it
                var afterAuthenticatedCookie = new HttpCookie(clientType, tokenKey)
                {
                    HttpOnly = true, Expires = DateTime.Now.AddHours(8)
                };
                CookieHelper.AddCookie(afterAuthenticatedCookie);

                //this object is stored in temporary storage by the oauth handler, its guid is placed into the return url into the "TOKEN" placeholder.
                //the expectation of this processing is the return url at this time is to the login page, and that any login based return url should be double encoded
                return(samlTokenData.GetOAuthData());
            }

            //if this is not a sign-in response, we should probably redirect to login.aspx
            throw new ArgumentException("The SAML token was not found in the HttpContext.Current.Request, please check the configuration and try again");
        }
Exemplo n.º 4
0
        public ActionResult Index(UserModel model)
        {
            if (_service.GetByName(model.UserName) != null)
            {
                ModelState.AddModelError(nameof(model.UserName), "* 用户名已存在,请重新输入");
                return(View(model));
            }
            UserModel inviter = _service.GetByName(model.InviterName);

            if (inviter == null)
            {
                ModelState.AddModelError(nameof(model.InviterName), "* 邀请人不存在,请重新输入");
                return(View(model));
            }
            if (inviter.InvitingCode != model.InvitingCode)
            {
                ModelState.AddModelError(nameof(model.InvitingCode), "* 邀请人对应的邀请码不正确,请重新输入");
                return(View(model));
            }
            if (Session["captcha"] == null)
            {
                throw new Exception();
            }
            if (Session["captcha"].ToString() != model.Captcha)
            {
                ModelState.AddModelError(nameof(model.Captcha), "* 验证码不正确,请重新输入");
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            _service.GetRegisterId(model);
            CookieHelper.AddCookie((int)model.UserId, model.Password);
            return(View(model));
        }
Exemplo n.º 5
0
        public async Task <DataResponse <string> > AuthenticateGoogleToken(TokenModel token, HttpResponse response)
        {
            try
            {
                var payload = await GoogleJsonWebSignature.ValidateAsync(token.tokenId, new GoogleJsonWebSignature.ValidationSettings());

                if (AppSettingsModel.appSettings.ValidEmails.Contains(payload.Email, StringComparer.OrdinalIgnoreCase))
                {
                    var jwt = TokenHelper.GenerateToken(payload.Email, AppSettingsModel.appSettings.JwtSecret, string.Empty);

                    LoggerHelper.Log(payload.ExpirationTimeSeconds.ToString());
                    CookieHelper.AddCookie(response, "Authorization-Token", jwt);
                    CookieHelper.AddCookie(response, "Avatar-Url", payload.Picture);

                    return(new DataResponse <string>()
                    {
                        Success = true,
                        Data = new List <string>()
                        {
                            jwt
                        }
                    });
                }
                else
                {
                    throw new Exception("Google token failed to validate.");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 设置一个加密Cookies
        /// </summary>
        /// <param name="value"></param>
        /// <param name="expireDays"></param>
        private static void SetAuthCookie(string name, string value, DateTime expireDays, HttpResponse response)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, name, DateTime.Now, expireDays, true, value, FormsAuthentication.FormsCookiePath);
            string encryptedTicket           = FormsAuthentication.Encrypt(ticket);

            CookieHelper.AddCookie(FormsAuthentication.FormsCookieName, encryptedTicket, ticket.Expiration, response, true, FormsAuthentication.RequireSSL, FormsAuthentication.FormsCookiePath, FormsAuthentication.CookieDomain);
        }
Exemplo n.º 7
0
        private void Events_AfterUserCreate(UserAfterCreateEventArgs e)
        {
            var afterCreatedCookie = CookieHelper.GetCookie(SamlCookieName);

            if (afterCreatedCookie == null)
            {
                return;
            }

            var samlTokenData = SamlTokenData.GetTokenDataFromDatabase(afterCreatedCookie.Value);

            if (samlTokenData == null)
            {
                return;
            }

            //destroy secure cookie for new user if cookie is still present
            CookieHelper.DeleteCookie(afterCreatedCookie.Value);
            //also cleanup our afterCreatedCookie
            CookieHelper.DeleteCookie(afterCreatedCookie.Name);

            //update the samlTokenData now that we know the user ID and cleanup the cookie used by the login
            samlTokenData.UserId = e.Id.Value;

            //Update the cookie SAMLToken Data to have the UserId now that its an existing user to fire the after authenticated events (which also removes the cookie)
            var tokenKey = samlTokenData.SaveTokenDataToDatabase();
            var afterAuthenticatedCookie = new HttpCookie(clientType, tokenKey)
            {
                Expires  = DateTime.Now.AddHours(8),
                HttpOnly = true
            };

            CookieHelper.AddCookie(afterAuthenticatedCookie);

            if (PersistClaims)
            {
                SqlData.SaveSamlToken(samlTokenData);
            }

            var apiUser = _usersApi.Get(new UsersGetOptions()
            {
                Id = e.Id.Value
            });

            //raise new SamlUserCreated Event
            try
            {
                SamlEvents.Instance.OnAfterUserCreate(apiUser, samlTokenData);
            }
            catch (Exception ex)
            {
                _eventLogApi.Write("SamlOAuthClient Error OnAfterUserCreate: " + ex.Message + " : " + ex.StackTrace, new EventLogEntryWriteOptions()
                {
                    Category = "SAML", EventId = 1, EventType = "Error"
                });
            }
        }
        public Response setToken(string token)
        {
            Response     res    = new Response();
            CookieHelper cookie = new CookieHelper(_accessor.HttpContext);

            cookie.DeleteCookie("userToken");
            cookie.AddCookie("userToken", token, DateTime.Now.AddDays(30));
            return(res);
        }
Exemplo n.º 9
0
        public ActionResult Login(BlogUsers user, bool RememberMe)
        {
            JSData json = new JSData();

            BLL.BlogUsersBLL userBLL    = new BLL.BlogUsersBLL();
            BlogUsers        userResult = userBLL.GetList(t => t.UserName == user.UserName).FirstOrDefault();

            if (userResult == null) //用户不存在
            {
                json.Message = "用户不存在!";
            }
            else if (userResult.UserPass == user.UserPass)     //登录成功
            {
                BLLSession.UserInfoSessioin = userResult;

                if (!string.IsNullOrEmpty(Request.QueryString["href"]))
                {
                    json.JSurl = Request.QueryString["href"];
                }
                else
                {
                    json.JSurl = "/";
                }
                if (RememberMe == true)
                {
                    HttpCookie cookie = CookieHelper.GetCookie("userInfo");
                    if (cookie == null)
                    {
                        cookie = new HttpCookie("userInfo");
                        cookie.Values.Add("userName", user.UserName);
                        cookie.Values.Add("userPass", user.UserPass);
                        cookie.Expires = DateTime.Now.AddMonths(6); //setting the valid time of the cookie  [6 months]
                        CookieHelper.AddCookie(cookie);
                    }
                    else
                    {
                        if (!cookie.Values["userName"].Equals(user.UserName))
                        {
                            CookieHelper.SetCookie("userInfo", "userName", user.UserName, DateTime.Now.AddMonths(6));
                        }
                        if (!cookie.Values["userPass"].Equals(user.UserPass))
                        {
                            CookieHelper.SetCookie("userInfo", "userPass", user.UserPass, DateTime.Now.AddMonths(6));
                        }
                    }
                }
                else
                {
                    CookieHelper.RemoveCookie("userInfo");
                }
            }
            else    //密码错误,登录失败
            {
                json.Message = "密码错误!";
            }
            return(Json(json));
        }
Exemplo n.º 10
0
        public ActionResult Reset(ResetModel model)
        {
            ResetModel RepoModel = _passwordService.GetResteModel();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            RepoModel.UpdatePassword = model.UpdatePassword.MD5Encrypt();
            _passwordService.UISaveResetModel(RepoModel);
            CookieHelper.RemoveCookie();
            CookieHelper.AddCookie((int)RepoModel.Id, model.UpdatePassword);
            return(View());
        }
Exemplo n.º 11
0
        /// <summary>
        /// 获取SessionID
        /// </summary>
        /// <param name="key">SessionId标识符</param>
        /// <returns>HttpCookie值</returns>
        private string GetSessionID()
        {
            var cookie = cookieHelper.GetValue(SessionName);

            if (cookie == null || string.IsNullOrEmpty(cookie))
            {
                string newSessionID = Guid.NewGuid().ToString();
                cookieHelper.AddCookie(SessionName, newSessionID, Timeout);
                return("Session_" + newSessionID);
            }
            else
            {
                return("Session_" + cookie);
            }
        }
Exemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.ContentType = "image/png";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            String code = CheckCode();
            String val  = EncryptHelper.MD5Upper32(code.ToLower() + Utils.GetIp());

            CookieHelper.AddCookie(ISessionKeys.cookie_authcode, val);
            //HttpCookie cookie = new HttpCookie(IKeys.cookie_authcode, val);
            //cookie.Expires = DateTime.Now.AddMinutes(5);
            //Response.Cookies.Add(cookie);

            CreateImage(code);
        }
Exemplo n.º 13
0
        public ActionResult Change(ChangeModel model)//映射太少  破坏数据库的完整性
        {
            ChangeModel RepoModel = _passwordService.GetChangeModelById((int)currentId);

            if (model.PresentPassword.MD5Encrypt() != RepoModel.PresentPassword)
            {
                ModelState.AddModelError(nameof(model.PresentPassword), "* 密码不正确,请检查密码并重新输入");
                return(View(model));
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            RepoModel.UpdatePassword = model.UpdatePassword.MD5Encrypt();
            _passwordService.UISaveChangeModel(RepoModel);//更改密码出现问题cookie里面的密码与更改的密码发生冲突,试试出现添加cookie
            CookieHelper.RemoveCookie();
            CookieHelper.AddCookie((int)RepoModel.Id, model.UpdatePassword);
            return(View());
        }
Exemplo n.º 14
0
        public async Task <dynamic> AuthenticateGoogleToken(TokenModel token, HttpResponse response)
        {
            try
            {
                var payload = await GoogleJsonWebSignature.ValidateAsync(token.tokenId, new GoogleJsonWebSignature.ValidationSettings());

                var jwt = TokenHelper.GenerateToken(payload.Email);

                LoggerHelper.Log(payload.ExpirationTimeSeconds.ToString());
                CookieHelper.AddCookie(response, "User-Email", payload.Email);
                CookieHelper.AddCookie(response, "Authorization-Token", jwt.token);

                return(jwt);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">登录密码</param>
        /// <returns></returns>
        public static void LoginUser(String username, String password, ref IJsonResult result)
        {
            ExecuteObject obj = new ExecuteObject();

            obj.tableName = "T_User";
            obj.cmdtype   = CmdType.SELECT;
            obj.terms.Add("UserName", username);
            obj.terms.Add("UserPass", password);

            T_UserEntity data = db.ExecuteObject <T_UserEntity>(obj);

            if (data.ID > 0)
            {
                if (data.IsLock)
                {
                    result.Text = "当前账号无法登录,请与管理员联系!";
                    T_LogsHelper.Append("尝试登录管理系统.", LogsAction.Login, data);
                }
                else
                {
                    result.Status     = true;
                    data.LastSignTime = DateTime.Now;
                    db.ExecuteCommand <T_UserEntity>(data, CmdType.UPDATE);
                    T_LogsHelper.Append("成功登录管理系统.", LogsAction.Login, data);
                    SetUserData(data);

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "root", DateTime.Now, DateTime.Now.AddMinutes(60), false, data.ID.ToString());
                    String authticket = FormsAuthentication.Encrypt(ticket);

                    CookieHelper.AddCookie(FormsAuthentication.FormsCookieName, authticket);

                    //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authticket);
                    //cookie.Expires = DateTime.Now.AddMinutes(60);
                    //cookie.HttpOnly = false;
                    //cookie.Path = FormsAuthentication.FormsCookiePath;
                    //cookie.Secure = FormsAuthentication.RequireSSL;
                    //cookie.Domain = FormsAuthentication.CookieDomain;
                    //HttpContext.Current.Response.Cookies.Set(cookie);
                    //HttpContext.Current.Response.Redirect("/Developer", true);
                }
            }
        }
Exemplo n.º 16
0
        public static void SetUserCookie(UserView uv, int remb = 0)
        {
            var nameValueCollection = new NameValueCollection
            {
                { "Ck5bACCT", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.Account, DecryptionKey)) },
                { "Ck5bUSD", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.Id.ToString(), DecryptionKey)) },
                { "Ck5bPEWFD", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.Pwd, DecryptionKey)) },
                { "Ck5bPNWFM", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.NickName, DecryptionKey)) },
                { "Ck5bPBWRB", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.BB.ToString(), DecryptionKey)) },
                { "Ck5bSEWFM", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.SubscribeNum.ToString(), DecryptionKey)) },
                { "Ck5bPCNMB", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.Phone, DecryptionKey)) },
                { "Ck5bPCFSB", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.FansCount.ToString(), DecryptionKey)) },
                { "Ck5bRMQE", HttpUtility.UrlEncode(DESEncrypt.Encrypt(remb.ToString(), DecryptionKey)) },
                { "Ck5bSEPIC", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.Picture, DecryptionKey)) },
                { "Ck5bSETFA", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.State.ToString(), DecryptionKey)) }
            };

            if (!string.IsNullOrWhiteSpace(uv.Token))
            {
                nameValueCollection.Add("Ck5bSETKE", HttpUtility.UrlEncode(DESEncrypt.Encrypt(uv.Token, DecryptionKey)));
            }
            CookieHelper.AddCookie("ck5bvv", nameValueCollection, remb == 0 ? 0 : 604800);
        }
Exemplo n.º 17
0
    /// <summary>
    /// 保存Cookie
    /// </summary>
    /// <param name="userInfo">用户信息</param>
    public static void SaveCookie(UserInfo userInfo)
    {
        var nvCookies = new NameValueCollection();

        nvCookies.Add("Code", userInfo.Code);
        nvCookies.Add("CompanyCode", userInfo.CompanyCode);
        nvCookies.Add("CompanyId", userInfo.CompanyId != null ? userInfo.CompanyId.ToString() : "");
        nvCookies.Add("CompanyName", HttpUtility.UrlEncode(userInfo.CompanyName));
        nvCookies.Add("DepartmentCode", userInfo.DepartmentCode);
        nvCookies.Add("Id", userInfo.Id);
        nvCookies.Add("OpenId", userInfo.OpenId);
        nvCookies.Add("RoleName", userInfo.RoleName);
        nvCookies.Add("Password", userInfo.Password);
        nvCookies.Add("IsAdministrator", userInfo.IsAdministrator.ToString());
        CookieHelper.AddCookie(Utils.CookieName, nvCookies);

        SetSession(userInfo);

        /* string password = SecretHelper.AESEncrypt(userInfo.Password);
         * HttpCookie httpCookie = new HttpCookie(Utils.CookieName);
         * httpCookie.Values[Utils.CookieUserName] = HttpUtility.UrlEncode(userInfo.UserName);
         * if (SystemInfo.RememberPassword)
         * {
         *  httpCookie.Values[Utils.CookiePassword] = password;
         * }
         * httpCookie.Values["Code"] = userInfo.Code;
         * httpCookie.Values["CompanyCode"] = userInfo.CompanyCode;
         * if (userInfo.CompanyId != null)
         * {
         *  httpCookie.Values["CompanyId"] = userInfo.CompanyId.ToString();
         * }
         * else
         * {
         *  httpCookie.Values["CompanyId"] = null;
         * }
         * httpCookie.Values["CompanyName"] = HttpUtility.UrlEncode(userInfo.CompanyName);
         * httpCookie.Values["CurrentLanguage"] = userInfo.CurrentLanguage;
         * httpCookie.Values["DepartmentCode"] = userInfo.DepartmentCode;
         * if (userInfo.DepartmentId != null)
         * {
         *  httpCookie.Values["DepartmentId"] = userInfo.DepartmentId.ToString();
         * }
         * else
         * {
         *  httpCookie.Values["DepartmentId"] = null;
         * }
         * httpCookie.Values["DepartmentName"] = HttpUtility.UrlEncode(userInfo.DepartmentName);
         * httpCookie.Values["Id"] = userInfo.Id;
         * httpCookie.Values["IPAddress"] = userInfo.IPAddress;
         * httpCookie.Values["IsAdministrator"] = userInfo.IsAdministrator.ToString();
         * httpCookie.Values["OpenId"] = userInfo.OpenId;
         * httpCookie.Values["RealName"] = HttpUtility.UrlEncode(userInfo.RealName);
         * if (userInfo.RoleId != null)
         * {
         *  httpCookie.Values["RoleId"] = userInfo.RoleId.ToString();
         * }
         * else
         * {
         *  httpCookie.Values["RoleId"] = null;
         * }
         * httpCookie.Values["RoleName"] = HttpUtility.UrlEncode(userInfo.RoleName);
         * httpCookie.Values["SecurityLevel"] = userInfo.SecurityLevel.ToString();
         * httpCookie.Values["ServicePassword"] = userInfo.ServicePassword;
         * httpCookie.Values["ServiceUserName"] = userInfo.ServiceUserName;
         * httpCookie.Values["StaffId"] = userInfo.StaffId;
         * httpCookie.Values["TargetUserId"] = userInfo.TargetUserId;
         * httpCookie.Values["Themes"] = userInfo.Themes;
         * httpCookie.Values["UserName"] = HttpUtility.UrlEncode(userInfo.UserName);
         * httpCookie.Values["WorkgroupCode"] = userInfo.WorkgroupCode;
         * if (userInfo.WorkgroupId != null)
         * {
         *  httpCookie.Values["WorkgroupId"] = userInfo.WorkgroupId.ToString();
         * }
         * else
         * {
         *  httpCookie.Values["WorkgroupId"] = null;
         * }
         * httpCookie.Values["WorkgroupName"] = HttpUtility.UrlEncode(userInfo.WorkgroupName);
         * // 设置过期时间为1天
         * DateTime dateTime = DateTime.Now;
         * httpCookie.Expires = dateTime.AddDays(30);
         * HttpContext.Current.Response.Cookies.Add(httpCookie);
         */
    }
Exemplo n.º 18
0
        private DateTime GMT = DateTime.Parse("1970-1-1 00:00:00");                  //格林时间;
        public void ProcessRequest(HttpContext context)
        {
            LoginJSData          myJson   = new LoginJSData();
            JavaScriptSerializer jsSerial = new JavaScriptSerializer();
            string validateCodeInSession  = (string)context.Session[Constants.ValidateCode];

            string userName        = context.Request.Params["userName"];
            string userPass        = context.Request.Params["userPass"];
            string isRemember      = context.Request.Params["isRemember"];
            string validateCode    = context.Request.Params["verifyTxt"];
            bool   isRequestStatus = context.Request.Params["status"] != null ? true : false;
            bool   isResign        = context.Request.Params["resign"] != null ? true : false;
            string sql             = "";

            if (isResign)
            {
                if (MySession.UserNameSession != null)
                {
                    MySession.UserNameSession = null;
                }
                if (CookieHelper.GetCookie(Constants.UserInfo) != null)
                {
                    CookieHelper.RemoveCookie(Constants.UserInfo);
                }
                context.Response.Write("OK");
                return;
            }

            if (isRequestStatus)
            {
                if (MySession.UserNameSession == null)
                {
                    context.Response.Write("");
                }
                else
                {
                    context.Response.Write(MySession.UserNameSession);
                }
                return;
            }

            //处理验证码是否已过期
            if (context.Session == null)
            {
                myJson.State   = EnumState.验证码错误;
                myJson.Message = "页面停留过长,验证码已失效!";
                context.Response.Write(jsSerial.Serialize(myJson));
                return;
            }
            //处理验证码是否输入正确
            if (!validateCode.Equals(validateCodeInSession, StringComparison.CurrentCultureIgnoreCase))
            {
                myJson.State   = EnumState.验证码错误;
                myJson.Message = "验证码错误!";
                context.Response.Write(jsSerial.Serialize(myJson));
                return;
            }
            //检测用户名是否存在或是否处于锁定状态
            sql = String.Format("select * from Users where UserName='******'", userName);
            if (!SqlHelper.IsRecordExists(sql))
            {
                myJson.State   = EnumState.用户不存在;
                myJson.Message = String.Format("“{0}”用户不存在!", userName);
                context.Response.Write(jsSerial.Serialize(myJson));
                return;
            }
            else
            {
                sql = String.Format("select * from Users where UserName = '******'", userName);
                DataTable dt = SqlHelper.ExcuteTable(sql, new SqlParameter("UserName", userName));//
                if ((bool)dt.Rows[0]["IsLock"])
                {
                    if (dt.Rows[0]["LockTime"] != DBNull.Value)
                    {
                        if ((DateTime.UtcNow - GMT).TotalMinutes - Convert.ToInt32(dt.Rows[0]["LockTime"]) > 30) // 距离上次输入错误大于30分钟 解锁账户
                        {
                            dt.Rows[0].BeginEdit();
                            dt.Rows[0]["IsLock"] = false;
                            dt.Rows[0]["Wrongs"] = 0;
                            dt.Rows[0].EndEdit();
                            SqlHelper.UpdateTable(dt, "Users");
                        }
                        else
                        {
                            myJson.State   = EnumState.用户不存在;
                            myJson.Message = String.Format("用户{0}已被锁定30分钟!", userName);
                            context.Response.Write(jsSerial.Serialize(myJson));
                            return;
                        }
                    }
                }
            }


            DataTable dt1;

            sql = String.Format("select * from Users where UserName = '******'", userName);
            dt1 = SqlHelper.ExcuteTable(sql, new SqlParameter("UserName", userName));

            sql = String.Format("select * from Users where UserName = '******' and UserPass = '******'", userName, Encription.MD5Encrypt(userPass));

            if (!SqlHelper.IsRecordExists(sql))  //输入账户密码不正确
            {
                int wrongNum = 0;
                wrongNum = dt1.Rows[0]["Wrongs"] == DBNull.Value ? 0 : (int)dt1.Rows[0]["Wrongs"];
                wrongNum++;
                dt1.Rows[0].BeginEdit();
                dt1.Rows[0]["Wrongs"] = wrongNum;
                dt1.Rows[0].EndEdit();
                SqlHelper.UpdateTable(dt1, "Users");

                if (wrongNum >= 5)
                {
                    dt1.Rows[0].BeginEdit();
                    dt1.Rows[0]["IsLock"]   = true;
                    dt1.Rows[0]["LockTime"] = (DateTime.UtcNow - GMT).TotalMinutes;
                    dt1.Rows[0].EndEdit();
                    SqlHelper.UpdateTable(dt1, "Users");
                    myJson.State   = EnumState.密码错误;
                    myJson.Message = "密码错误!输入错误已达5次," + userName + "账户已被锁定!";
                    context.Response.Write(jsSerial.Serialize(myJson));
                    return;
                }
                else
                {
                    myJson.State   = EnumState.密码错误;
                    myJson.Message = "密码错误!已累计错误" + wrongNum + "次,输入错误达5次将锁定账户!";
                    context.Response.Write(jsSerial.Serialize(myJson));
                    return;
                }
            }
            else                             //输入账户密码正确
            {
                dt1.Rows[0].BeginEdit();
                dt1.Rows[0]["Wrongs"] = 0;
                dt1.Rows[0].EndEdit();
                SqlHelper.UpdateTable(dt1, "Users");

                //用cookie记住用户信息
                if (isRemember == "true")
                {
                    if (CookieHelper.GetCookie(Constants.UserInfo) == null)
                    {
                        string     pass   = Encription.MD5Encrypt(userName + Encription.MD5Encrypt(userPass));
                        HttpCookie cookie = new HttpCookie(Constants.UserInfo);
                        cookie.Values.Add(Constants.UserName, userName);
                        cookie.Values.Add(Constants.UserPass, pass); //客户端cookie中密码的保密规则:用户名+原密码MD5加密,在对其再一次md5加密
                        cookie.Expires = DateTime.Now.AddMonths(1);
                        CookieHelper.AddCookie(cookie);
                    }
                    else
                    {
                        HttpCookie cookie = CookieHelper.GetCookie(Constants.UserInfo);
                        String     pass   = Encription.MD5Encrypt(userName + Encription.MD5Encrypt(userPass));
                        if (cookie.Values[Constants.UserName] != userName)
                        {
                            CookieHelper.SetCookie(Constants.UserInfo, Constants.UserName, userName, DateTime.Now.AddMonths(1));
                        }
                        if (cookie.Values[Constants.UserPass] != pass)
                        {
                            CookieHelper.SetCookie(Constants.UserInfo, Constants.UserPass, pass, DateTime.Now.AddMonths(1));
                        }
                    }
                }
                else
                {
                    if (CookieHelper.GetCookie(Constants.UserInfo) != null)
                    {
                        CookieHelper.RemoveCookie(Constants.UserInfo);
                    }
                }

                MySession.UserNameSession = userName;//登录状态记录到session中;
                myJson.State   = EnumState.登录成功;
                myJson.Message = userName + ",欢迎您回来!";
                context.Response.Write(jsSerial.Serialize(myJson));
                return;
            }
        }