Esempio n. 1
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string queryString = WebUtils.GetQueryString("lang");

            if (Language.Contain(queryString))
            {
                CookieUtils.SetCookie("langcookie", queryString, 2592000);
                string queryString2 = WebUtils.GetQueryString("jumpurl");
                if (!string.IsNullOrEmpty(queryString2))
                {
                    base.Response.Redirect(queryString2);
                }
                else if (base.Request.UrlReferrer != null)
                {
                    base.Response.Redirect(base.Request.UrlReferrer.ToString());
                }
                else
                {
                    base.Response.Redirect("/");
                }
            }
            else
            {
                base.Response.Write(WebUtils.GetCaption("CMS_NotExistLanguageSet"));
                base.Response.End();
            }
        }
        public string AdminLogin(string userName, bool isAutoLogin)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(null);
            }
            var adminInfo = AdminManager.GetAdminInfoByUserName(userName);

            if (adminInfo == null || adminInfo.Locked)
            {
                return(null);
            }

            AdminInfo     = adminInfo;
            IsAdminLoggin = true;

            var expiresAt   = TimeSpan.FromDays(Constants.AccessTokenExpireDays);
            var accessToken = AdminApi.Instance.GetAccessToken(adminInfo.Id, adminInfo.UserName, expiresAt);

            LogUtils.AddAdminLog(adminInfo, "管理员登录");

            if (isAutoLogin)
            {
                CookieUtils.SetCookie(Constants.AuthKeyAdminCookie, accessToken, expiresAt);
            }
            else
            {
                CookieUtils.SetCookie(Constants.AuthKeyAdminCookie, accessToken);
            }

            return(accessToken);
        }
Esempio n. 3
0
        public string AdminLogin(string userName, bool isAutoLogin)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(null);
            }
            var adminInfo = AdminManager.GetAdminInfoByUserName(userName);

            if (adminInfo == null || adminInfo.IsLockedOut)
            {
                return(null);
            }

            AdminInfo     = adminInfo;
            IsAdminLoggin = true;

            var expiresAt   = DateTime.Now.AddDays(AccessTokenExpireDays);
            var accessToken = GetAccessToken(adminInfo.Id, adminInfo.UserName, expiresAt);

            LogUtils.AddAdminLog(adminInfo.UserName, "管理员登录");

            if (isAutoLogin)
            {
                CookieUtils.SetCookie(AuthKeyAdminCookie, accessToken, expiresAt);
            }
            else
            {
                CookieUtils.SetCookie(AuthKeyAdminCookie, accessToken);
            }

            return(accessToken);
        }
Esempio n. 4
0
        public string UserLogin(string userName, bool isAutoLogin)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(null);
            }

            var userInfo = UserManager.GetUserInfoByUserName(userName);

            if (userInfo == null || userInfo.IsLockedOut || !userInfo.IsChecked)
            {
                return(null);
            }

            UserInfo = userInfo;

            var expiresAt   = DateTime.Now.AddDays(AccessTokenExpireDays);
            var accessToken = GetAccessToken(UserId, UserName, expiresAt);

            DataProvider.UserDao.UpdateLastActivityDateAndCountOfLogin(UserInfo);
            LogUtils.AddUserLoginLog(userName);

            if (isAutoLogin)
            {
                CookieUtils.SetCookie(AuthKeyUserCookie, accessToken, expiresAt);
            }
            else
            {
                CookieUtils.SetCookie(AuthKeyUserCookie, accessToken);
            }

            return(accessToken);
        }
Esempio n. 5
0
        public async Task <ActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (!VeryfyCodeUtility.IsVerifyCodeMatch(Session, model.ValidateCode))
            {
                ModelState.AddModelError("ValidateCode", "验证码错误!");
                return(View(model));
            }

            var loginResult = await UsersRepository.Login(model.UserName, model.Password);

            if (loginResult.Status == SigninStatus.Succ)
            {
                FormsAuthSvc.CreateAuthenticationTicket(loginResult.UserInfo, Response, HttpContext, model.IsRemember);
                //添加到Fom
                if (model.IsRemember)
                {
                    CookieUtils.SetCookie(FormsAuthSvc.GetUserNameCookieKey(), model.UserName, true);
                }
                else
                {
                    CookieUtils.RemoveCookie(FormsAuthSvc.GetUserNameCookieKey());
                }
                //添加登录日志
                await SysOperationLogRepository.Insert(TableSource.Users, OperationType.UserLogin, "", "");

                return(Redirect(Url.AdminHome()));
            }

            ModelState.AddModelError("UserName", "登录失败!" + loginResult.Status.GetDescriotion());
            return(View(model));
        }
        public void Get(string name)
        {
            var response = HttpContext.Current.Response;

            var code = VcManager.CreateValidateCode();

            if (CacheUtils.Exists($"SiteServer.API.Controllers.V1.CaptchaController.{code}"))
            {
                code = VcManager.CreateValidateCode();
            }

            CookieUtils.SetCookie("SS-" + name, code, DateTime.Now.AddMinutes(10));

            response.BufferOutput = true;                                //特别注意
            response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1)); //特别注意
            response.Cache.SetCacheability(HttpCacheability.NoCache);    //特别注意
            response.AppendHeader("Pragma", "No-Cache");                 //特别注意
            response.ContentType = "image/png";

            var validateimage = new Bitmap(130, 53, PixelFormat.Format32bppRgb);

            var r      = new Random();
            var colors = Colors[r.Next(0, 5)];

            var g = Graphics.FromImage(validateimage);

            g.FillRectangle(new SolidBrush(Color.FromArgb(240, 243, 248)), 0, 0, 200, 200);                                                          //矩形框
            g.DrawString(code, new Font(FontFamily.GenericSerif, 28, FontStyle.Bold | FontStyle.Italic), new SolidBrush(colors), new PointF(14, 3)); //字体/颜色

            var random = new Random();

            for (var i = 0; i < 25; i++)
            {
                var x1 = random.Next(validateimage.Width);
                var x2 = random.Next(validateimage.Width);
                var y1 = random.Next(validateimage.Height);
                var y2 = random.Next(validateimage.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            for (var i = 0; i < 100; i++)
            {
                var x = random.Next(validateimage.Width);
                var y = random.Next(validateimage.Height);

                validateimage.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.Save();
            var ms = new MemoryStream();

            validateimage.Save(ms, ImageFormat.Png);
            response.ClearContent();
            response.BinaryWrite(ms.ToArray());
            response.End();
        }
Esempio n. 7
0
        public void AdminLogin(string administratorName)
        {
            if (string.IsNullOrEmpty(administratorName))
            {
                return;
            }

            AdminName = administratorName;
            LogUtils.AddAdminLog(administratorName, "管理员登录");
            CookieUtils.SetCookie(AdministratorAccessToken, GetAdminTokenByAdminName(administratorName), DateTime.Now.AddDays(AccessTokenExpireDays));
        }
Esempio n. 8
0
        public void UserLogin(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return;
            }

            UserName = userName;
            LogUtils.AddUserLoginLog(userName);
            CookieUtils.SetCookie(UserAccessToken, GetUserTokenByUserName(userName), DateTime.Now.AddDays(AccessTokenExpireDays));
        }
Esempio n. 9
0
        public ActionResult Login(LoginModel model)
        {
            var result = new JsonModel();

            #region check params
            if (model == null)
            {
                result.msg = "请输入数据!";
                return(Json(result));
            }
            if (string.IsNullOrEmpty(model.UserName))
            {
                result.msg = "请输入用户名";
                return(Json(result));
            }
            if (string.IsNullOrEmpty(model.Password) || model.Password.Length < 6)
            {
                result.msg = "请输入正确的密码";
                return(Json(result));
            }
            if (string.IsNullOrEmpty(model.ValidateCode))
            {
                result.msg = "请输入验证码";
                return(Json(result));
            }
            #endregion

            if (!VeryfyCodeUtility.IsVerifyCodeMatch(Session, model.ValidateCode))
            {
                result.msg = "验证码错误!";
                return(Json(result));
            }

            var loginResult = UsersRepository.AdminLogin(model.UserName, model.Password);
            if (loginResult.Status == SigninStatus.Succ)
            {
                FormsAuthSvc.CreateAuthenticationTicket(loginResult.UserInfo, Response, HttpContext, model.IsRemember);
                //添加到Fom
                if (model.IsRemember)
                {
                    CookieUtils.SetCookie(FormsAuthSvc.GetUserNameCookieKey(), model.UserName, true);
                }
                else
                {
                    CookieUtils.RemoveCookie(FormsAuthSvc.GetUserNameCookieKey());
                }
                //添加登录日志
                SysOperationLogRepository.Insert(TableSource.Users, OperationType.UserLogin, loginResult.UserInfo.Id);
                result.code = JsonModelCode.Succ;
                return(Json(result));
            }
            result.msg = "登录失败!" + loginResult.Status.GetDescriotion();
            return(Json(result));
        }
        public IActionResult Index()
        {
            /*
             * net core不自带httpcontext 需要在 Startup 注入
             * 1、在ConfigureServices 中 services.AddStaticHttpContext();
             * 2、在Configure 中 app.UseStaticHttpContext();
             */

            var builder = new StringBuilder("测试如下:\r\n");

            //Post
            builder.Append($"Post值:{WebUtils.GetFormVal<string>("a")}\r\n");

            //IP
            builder.Append($"IP:{IPUtils.GetIP()}\r\n");

            //WebUtils
            builder.Append($"pid:{WebUtils.GetQueryVal<int>("pid")}\r\n");                                  //?pid=1
            builder.Append($"date:{WebUtils.GetQueryVal<DateTime>("date", new DateTime(1900, 1, 1))}\r\n"); //?date=2020-12-31
            //全url
            builder.Append($"全URL:{WebUtils.GetAbsoluteUri()}\r\n");

            //CacheUtils 缓存
            DateTime dateTime = DateTime.Now;
            var      cache    = new CacheUtils();

            var cacheDT = DateTime.Now;

            if (cache.ContainKey("time"))
            {
                cacheDT = cache.Get <DateTime>("time");
            }
            else
            {
                cache.Insert <DateTime>("time", dateTime, 3600);
            }

            builder.Append($"当前时间:{dateTime.ToFormatString()} \r\n");
            builder.Append($"缓存时间:{cacheDT.ToFormatString()} \r\n");

            //当前网站目录
            builder.Append($"当前网站目录:{SystemUtils.GetMapPath()} \r\n");
            builder.Append($"upload目录:{SystemUtils.GetMapPath("/upload")} \r\n");

            //cookie
            CookieUtils.SetCookie("username", "jsonlee");
            builder.Append($"username cookie: {CookieUtils.GetCookie("username")} \r\n");

            //session
            SessionUtils.SetSession("username", System.Web.HttpUtility.UrlEncode("刘备"));
            builder.Append($"username session: {System.Web.HttpUtility.UrlDecode(SessionUtils.GetSession("username"))} \r\n");

            return(Content(builder.ToString()));
        }
Esempio n. 11
0
 public static string GetCookieWXOpenID(string wxOpenID)
 {
     if (CookieUtils.IsExists(COOKIE_WXOPENID_NAME))
     {
         return(CookieUtils.GetCookie(COOKIE_WXOPENID_NAME));
     }
     else
     {
         CookieUtils.SetCookie(COOKIE_WXOPENID_NAME, wxOpenID, DateTime.MaxValue);
         return(wxOpenID);
     }
 }
Esempio n. 12
0
 public static string GetCookieSN()
 {
     if (CookieUtils.IsExists(COOKIE_SN_NAME))
     {
         return(CookieUtils.GetCookie(COOKIE_SN_NAME));
     }
     else
     {
         var value = StringUtils.GetShortGuid();
         CookieUtils.SetCookie(COOKIE_SN_NAME, value, DateTime.MaxValue);
         return(value);
     }
 }
Esempio n. 13
0
        /// <summary>
        /// 发送注册邮件
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public Result SendRegistEmail(Account account)
        {
            Result result = new Result()
            {
                Status     = true,
                Message    = "发送邮件成功",
                StatusCode = "SR000"
            };

            try
            {
                //生成code码加入缓存 设置时效日期
                if (account != null)
                {
                    byte[] phonebyte = Encoding.UTF8.GetBytes(account.Phone.ToString());
                    string code      = Base64Engine.ToBase64String(phonebyte);

                    CookieUtils.SetCookie(string.Format("code{0}", account.Phone), code, DateTime.Now.AddHours(1));


                    SendMailInfo sendinfo = new SendMailInfo();

                    using (StreamReader sr = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "VerificationMail.html"))
                    {
                        sendinfo.Content = sr.ReadToEnd();
                    }
                    sendinfo.Title = "验证账户";
                    if (!string.IsNullOrEmpty(sendinfo.Content))
                    {
                        sendinfo.Content = sendinfo.Content.Replace("(手机)", account.Phone.ToString());
                        sendinfo.Content = sendinfo.Content.Replace("(邮箱)", account.Email);
                        sendinfo.Content = sendinfo.Content.Replace("(验证码)", code);
                    }

                    VerifiedMail.Sender.AddSend(sendinfo, new List <string>()
                    {
                        account.Email
                    });
                }
            }
            catch (Exception ex)
            {
                result.Status     = false;
                result.Message    = string.Format("邮件验证出错 /r/n{0}", ex.Message);
                result.StatusCode = "EX000";
                LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:SendRegistEmail() .AccountService"), LogType.ErrorLog);
            }

            return(result);
        }
        public ActionResult Index()
        {
            var builder = new StringBuilder("测试如下:<br/>\r\n");

            //IP
            builder.Append($"IP:{IPUtils.GetIP()}<br/>\r\n");

            //WebUtils
            builder.Append($"pid:{WebUtils.GetQueryInt("pid")}<br/>\r\n"); //?pid=1
            //全url
            builder.Append($"全URL:{WebUtils.GetAbsoluteUri()}<br/>\r\n");

            //CacheUtils 缓存
            DateTime dateTime = DateTime.Now;
            var      cache    = new CacheUtils();

            var cacheDT = DateTime.Now;

            if (cache.ContainKey("time"))
            {
                cacheDT = cache.Get <DateTime>("time");
            }
            else
            {
                cache.Insert <DateTime>("time", dateTime, 3600);
            }

            builder.Append($"当前时间:{dateTime.ToFormatString()} <br/>\r\n");
            builder.Append($"缓存时间:{cacheDT.ToFormatString()} <br/>\r\n");

            //当前网站目录
            builder.Append($"当前网站目录:{SystemUtils.GetMapPath()} <br/>");
            builder.Append($"upload目录:{SystemUtils.GetMapPath("/upload")} <br/>");

            //cookie
            CookieUtils.SetCookie("username", "jsonlee");
            builder.Append($"username cookie: {CookieUtils.GetCookie("username")} <br/>\r\n");

            //session
            SessionUtils.SetSession("username", "刘备");
            builder.Append($"username session: {SessionUtils.GetSession<string>("username")}  <br/>\r\n");

            builder.Append($"mobile client : {SystemUtils.IsMobileClient.Value} <br/>\r\n");
            builder.Append($"weixin client : {SystemUtils.IsWeixinClient.Value} <br/>\r\n");

            builder.Append($"is iphone : {SystemUtils.IsIphone.Value} <br/>\r\n");
            builder.Append($"is android : {SystemUtils.IsAndroid.Value} <br/>\r\n");

            return(Content(builder.ToString()));
        }
Esempio n. 15
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     if (base.IsPost)
     {
         UserInfo userInfo    = new UserInfo();
         string   formString  = WebUtils.GetFormString("_loginname");
         string   formString2 = WebUtils.GetFormString("_loginpwd");
         bool     flag        = WebUtils.GetFormInt("_loginremeber").Equals(1);
         if (PageBase.config.VerifycodeForLogin && string.Compare(base.ValidateCode, WebUtils.GetFormString("_loginyzm"), true) != 0)
         {
             base.WriteJsonTip(base.GetCaption("ValidateCodeIncorrect"));
         }
         else
         {
             LoginStatus loginStatus = SinGooCMS.BLL.User.UserLogin(formString, formString2, ref userInfo);
             if (loginStatus == LoginStatus.Success)
             {
                 if (flag)
                 {
                     CookieUtils.SetCookie("_remeberusername", userInfo.UserName, 31536000);
                 }
                 string text = base.Server.UrlDecode(WebUtils.GetFormString("_loginreturnurl"));
                 if (!string.IsNullOrEmpty(text))
                 {
                     base.WriteJsonTip(true, "Đăng nhập thành công", text);
                 }
                 else
                 {
                     base.WriteJsonTip(true, "Đăng nhập thành công", UrlRewrite.Get("infocenter_url"));
                 }
             }
             else if (loginStatus == LoginStatus.MutilLoginFail)
             {
                 base.WriteJsonTip(base.GetCaption("Login_LoginFailTooMany").Replace("${num}", PageBase.config.TryLoginTimes.ToString()));
             }
             else
             {
                 base.WriteJsonTip(base.GetCaption("Login_FailWithMsg").Replace("${msg}", base.GetCaption("LoginStatus_" + loginStatus.ToString())));
             }
         }
     }
     else
     {
         base.Put("remeberusername", CookieUtils.GetCookie("_remeberusername"));
         base.Put("returnurl", (base.Request.Url.ToString().IndexOf("?returnurl=") == -1) ? "" : base.Request.Url.ToString().Substring(base.Request.Url.ToString().IndexOf("?returnurl=") + "?returnurl=".Length));
         base.Put("thirdlogin", OAuthConfig.Load());
         base.UsingClient("user/login.html");
     }
 }
Esempio n. 16
0
        public string AdminLogin(string adminName)
        {
            if (string.IsNullOrEmpty(adminName))
            {
                return(null);
            }

            AdminName = adminName;
            var accessToken = GetAdminTokenByAdminName(adminName);

            LogUtils.AddAdminLog(adminName, "管理员登录");
            CookieUtils.SetCookie(AuthKeyAdminCookie, accessToken, DateTime.Now.AddDays(AccessTokenExpireDays));

            return(accessToken);
        }
Esempio n. 17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var cookieName = Request.QueryString["cookieName"];

            var validateCode = VcManager.CreateValidateCode();

            CookieUtils.SetCookie(cookieName, validateCode, DateTime.Now.AddDays(1));

            Response.BufferOutput = true;                                //特别注意
            Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1)); //特别注意
            Response.Cache.SetCacheability(HttpCacheability.NoCache);    //特别注意
            Response.AppendHeader("Pragma", "No-Cache");                 //特别注意
            Response.ContentType = "image/png";
            ValidateCode(validateCode);
        }
Esempio n. 18
0
        /// <summary>
        /// 发送忘记密码验证码
        /// </summary>
        /// <param name="mail"></param>
        /// <returns></returns>
        public Result SendForgetVerificationCode(string mail)
        {
            Result result = new Result()
            {
                Status     = true,
                Message    = "发送邮件成功",
                StatusCode = "SR000"
            };

            try
            {
                //生成code码加入缓存 设置时效日期
                if (!string.IsNullOrEmpty(mail))
                {
                    string code = VerificationUtils.GetVefication();

                    CookieUtils.SetCookie(string.Format("forget{0}", mail), code, DateTime.Now.AddMinutes(30));


                    SendMailInfo sendinfo = new SendMailInfo();

                    using (StreamReader sr = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "ForgetVerificationMail.html"))
                    {
                        sendinfo.Content = sr.ReadToEnd();
                    }
                    sendinfo.Title = string.Format("你此次重置密码的验证码是:{0}", code);
                    if (!string.IsNullOrEmpty(sendinfo.Content))
                    {
                        sendinfo.Content = sendinfo.Content.Replace("(手机)", mail);
                        sendinfo.Content = sendinfo.Content.Replace("(验证码)", code);
                    }

                    VerifiedMail.Sender.AddSend(sendinfo, new List <string>()
                    {
                        "*****@*****.**"
                    });
                }
            }
            catch (Exception ex)
            {
                result.Status     = false;
                result.Message    = string.Format("忘记密码邮件验证出错 /r/n{0}", ex.Message);
                result.StatusCode = "EX000";
                LoggerUtils.LogIn(LoggerUtils.ColectExceptionMessage(ex, "At service:SendForgetVerificationCode() .AccountService"), LogType.ErrorLog);
            }

            return(result);
        }
Esempio n. 19
0
        public string UserLogin(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                return(null);
            }

            UserName = userName;

            var accessToken = GetUserTokenByUserName(userName);

            LogUtils.AddUserLoginLog(userName);
            CookieUtils.SetCookie(AuthKeyUserCookie, accessToken, DateTime.Now.AddDays(AccessTokenExpireDays));

            return(accessToken);
        }
        public JsonResult LoginRequest(LoginRequest account)
        {
            Result <Account> loginresult = new Result <Account>()
            {
                Status     = true,
                Message    = "",
                StatusCode = "",
                Data       = null
            };

            string lastdate = CookieUtils.Get("lastSubmit");

            if (string.IsNullOrEmpty(lastdate))
            {
                CookieUtils.SetCookie("lastSubmit", DateTime.Now.ToString());
            }
            else
            {
                DateTime now = DateTime.Now;
                CookieUtils.SetCookie("lastSubmit", now.ToString());
                double seconds = now.Subtract(Convert.ToDateTime(lastdate)).TotalMilliseconds;
                if (seconds < 1000 * 5)
                {
                    loginresult.Status     = false;
                    loginresult.Message    = "操作过于频繁,请稍后再试";
                    loginresult.StatusCode = "LG000";
                }
            }

            //数据验证
            if (loginresult.Status)
            {
                loginresult = VerificationAccount(account.LoginUsername, account.LoginSecurity);
            }

            //登录操作
            if (loginresult.Status)
            {
                loginresult = ServiceObjectContainer.Get <IAccountService>().SignIn(account.LoginUsername, account.LoginSecurity);
                if (loginresult.Status)
                {
                    HttpContext.Session["CurrentAccount"] = loginresult.Data.Phone;
                }
            }
            return(Json(loginresult));
        }
        public JsonResult RegistRequest(RegistRequest regist)
        {
            Result registresult = new Result()
            {
                Status     = true,
                Message    = "账户注册成功,请到邮箱进行验证.",
                StatusCode = "RR100"
            };

            string lastdate = CookieUtils.Get("lastSubmit");

            if (string.IsNullOrEmpty(lastdate))
            {
                CookieUtils.SetCookie("lastSubmit", DateTime.Now.ToString());
            }
            else
            {
                DateTime now = DateTime.Now;
                CookieUtils.SetCookie("lastSubmit", now.ToString());
                double seconds = now.Subtract(Convert.ToDateTime(lastdate)).TotalMilliseconds;
                if (seconds < 1000 * 5)
                {
                    registresult.Status     = false;
                    registresult.Message    = "操作过于频繁,请稍后再试";
                    registresult.StatusCode = "RR000";
                }
            }

            if (registresult.Status)
            {
                IAccountService  service       = ServiceObjectContainer.Get <IAccountService>();
                Result <Account> accountresult = service.RegistInfo(regist);
                if (!accountresult.Status)
                {
                    registresult.Status     = false;
                    registresult.Message    = "注册账户失败,请稍后再试";
                    registresult.StatusCode = "RR001";
                }
                else
                {
                    service.SendRegistEmail(accountresult.Data);
                }
            }
            return(Json(registresult));
        }
        public JsonResult SignOutRequest(string phone)
        {
            Result result = new Result()
            {
                Status = false
            };
            string lastdate = CookieUtils.Get("lastSubmit");

            if (string.IsNullOrEmpty(lastdate))
            {
                CookieUtils.SetCookie("lastSubmit", DateTime.Now.ToString());
            }
            else
            {
                DateTime now = DateTime.Now;
                CookieUtils.SetCookie("lastSubmit", now.ToString());
                double seconds = now.Subtract(Convert.ToDateTime(lastdate)).TotalMilliseconds;
                if (seconds < 1000 * 5)
                {
                    result.Status     = false;
                    result.Message    = "操作过于频繁,请稍后再试";
                    result.StatusCode = "SO000";
                }
            }
            long signoutphone = 0;

            if (!long.TryParse(phone, out signoutphone))
            {
                result.Status     = false;
                result.Message    = "参数错误";
                result.StatusCode = "SO002";
            }

            result = ServiceObjectContainer.Get <IAccountService>().SignOut(signoutphone);

            if (result.Status)
            {
                HttpContext.Session["CurrentAccount"] = "";
            }

            return(Json(result));
        }
Esempio n. 23
0
        public async Task <ActionResult> LoginDialog(LoginModel model)
        {
            var result = new JsonModel();

            if (!VeryfyCodeUtility.IsVerifyCodeMatch(Session, model.ValidateCode))
            {
                ModelState.AddModelError("ValidateCode", "验证码错误!");
            }
            if (!ModelState.IsValid)
            {
                result.GetError(ModelState);
                return(Json(result));
            }

            var loginResult = await UsersRepository.Login(model.UserName, model.Password);

            if (loginResult.Status == SigninStatus.Succ)
            {
                FormsAuthSvc.CreateAuthenticationTicket(loginResult.UserInfo, Response, HttpContext, model.IsRemember);
                //添加到Fom
                if (model.IsRemember)
                {
                    CookieUtils.SetCookie(FormsAuthSvc.GetUserNameCookieKey(), model.UserName, true);
                }
                else
                {
                    CookieUtils.RemoveCookie(FormsAuthSvc.GetUserNameCookieKey());
                }
                //添加登录日志
                await SysOperationLogRepository.Insert(TableSource.Users, OperationType.UserLogin, "", "");

                result.message = "登录成功!";
                return(Json(result));
            }

            result.statusCode = 300;
            result.message    = "登录失败!" + loginResult.Status.GetDescriotion();
            //result.Error.Add(new ErorrModel() {Key="UserName",Value= "登录失败!" + loginResult.Status.GetDescriotion() });
            return(Json(result));
        }
Esempio n. 24
0
        private void FillFileSystems(bool isReload)
        {
            const string cookieName  = "SiteServer.BackgroundPages.Cms.Modal.SelectAttachment";
            var          isSetCookie = AuthRequest.IsQueryExists("ListType");

            if (!isSetCookie)
            {
                var cookieExists = false;
                if (CookieUtils.IsExists(cookieName))
                {
                    var cookieValue = CookieUtils.GetCookie(cookieName);
                    foreach (ListItem item in DdlListType.Items)
                    {
                        if (string.Equals(item.Value, cookieValue))
                        {
                            cookieExists  = true;
                            item.Selected = true;
                        }
                    }
                }
                if (!cookieExists)
                {
                    CookieUtils.SetCookie(cookieName, DdlListType.SelectedValue, DateTime.MaxValue);
                }
            }
            else
            {
                CookieUtils.SetCookie(cookieName, AuthRequest.GetQueryString("ListType"), DateTime.MaxValue);
            }
            if (DdlListType.SelectedValue == "List")
            {
                FillFileSystemsToList(isReload);
            }
            else if (DdlListType.SelectedValue == "Image")
            {
                FillFileSystemsToImage(isReload);
            }
        }
        public void Main(int publishmentSystemId, int nodeId, int contentId)
        {
            var body = new RequestBody();

            var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId);

            try
            {
                var contentInfo = DataProvider.VoteContentDao.GetContentInfo(publishmentSystemInfo, contentId);
                if ((contentInfo.EndDate - DateTime.Now).Seconds <= 0)
                {
                    throw new Exception("对不起,投票已经结束");
                }
                var cookieName = DataProvider.VoteOperationDao.GetCookieName(publishmentSystemId, nodeId, contentId);
                if (CookieUtils.IsExists(cookieName))
                {
                    throw new Exception("对不起,不能重复投票");
                }

                var optionIdArrayList = TranslateUtils.StringCollectionToIntList(HttpContext.Current.Request.Form["voteOption_" + contentId]);
                foreach (int optionId in optionIdArrayList)
                {
                    DataProvider.VoteOptionDao.AddVoteNum(optionId);
                }
                DataProvider.VoteOperationDao.Insert(new VoteOperationInfo(0, publishmentSystemId, nodeId, contentId, PageUtils.GetIpAddress(), body.UserName, DateTime.Now));

                HttpContext.Current.Response.Write(VoteTemplate.GetCallbackScript(publishmentSystemInfo, nodeId, contentId, true, string.Empty));
                CookieUtils.SetCookie(cookieName, true.ToString(), DateTime.MaxValue);
            }
            catch (Exception ex)
            {
                //HttpContext.Current.Response.Write(VoteTemplate.GetCallbackScript(publishmentSystemInfo, nodeId, contentId, false, ex.Message));
                HttpContext.Current.Response.Write(VoteTemplate.GetCallbackScript(publishmentSystemInfo, nodeId, contentId, false, "程序出错。"));
            }

            HttpContext.Current.Response.End();
        }
Esempio n. 26
0
    /// <summary>
    /// 验证用户
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <param name="password">密码</param>
    /// <param name="openId">单点登录标识</param>
    /// <param name="permissionItemCode">权限编号</param>
    /// <param name="persistCookie">是否保存密码</param>
    /// <param name="formsAuthentication">表单验证,是否需要重定位</param>
    /// <param name="returnStatusCode"></param>
    /// <param name="returnStatusMessage"></param>
    /// <returns></returns>
    public static UserInfo LogOn(string userName, string password, string openId, string permissionItemCode, bool persistCookie, bool formsAuthentication, out string returnStatusCode, out string returnStatusMessage)
    {
        // 登录服务
        UserInfo userInfo = RDIFrameworkService.Instance.LogOnService.UserLogOn(Utils.GetUserInfo(), userName, password, openId, false, out returnStatusCode, out returnStatusMessage);

        // 检查身份
        if (!returnStatusCode.Equals(StatusCode.OK.ToString()))
        {
            return(userInfo);
        }
        var isAuthorized = true;

        // 用户是否有哪个相应的权限
        if (!string.IsNullOrEmpty(permissionItemCode))
        {
            isAuthorized = RDIFrameworkService.Instance.PermissionService.IsAuthorized(userInfo, permissionItemCode, null);
        }
        // 有相应的权限才可以登录
        if (isAuthorized)
        {
            if (persistCookie)
            {
                // 相对安全的方式保存登录状态
                // SaveCookie(userName, password);
                // 内部单点登录方式
                CookieUtils.SetCookie("OpenId", userInfo.OpenId);
                //SaveCookie(userInfo);
            }
            LogOn(userInfo, formsAuthentication);
        }
        else
        {
            returnStatusCode    = StatusCode.LogOnDeny.ToString();
            returnStatusMessage = "访问被拒绝、您的账户没有后台管理访问权限。";
        }
        return(userInfo);
    }
Esempio n. 27
0
 public void SetCookie(string name, string value, TimeSpan expiresAt)
 {
     CookieUtils.SetCookie(name, value, expiresAt);
 }
Esempio n. 28
0
 public void SetCookie(string name, string value, DateTime expires)
 {
     CookieUtils.SetCookie(name, value, expires);
 }
Esempio n. 29
0
        /// <summary>
        /// 创建图片并保存在内存中
        /// </summary>
        /// <param name="checkCode"></param>
        public void CreateCheckCodeImage()
        {
            string checkCode = GenerateCheckCode();

            _codestring = checkCode;
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return;
            }

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 10.5)), 18);
            Graphics g = Graphics.FromImage(image);


            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            #region
            //画图片的背景噪音线
            for (int i = 0; i < 20; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            #endregion

            Font font = new System.Drawing.Font("Arial", 11, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);

            #region
            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            #endregion

            try
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                if (_codetype == VerifyCodeType.Web)
                {
                    //清除该页输出缓存,设置该页无缓存
                    System.Web.HttpContext.Current.Response.Buffer          = true;
                    System.Web.HttpContext.Current.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
                    System.Web.HttpContext.Current.Response.Expires         = 0;
                    System.Web.HttpContext.Current.Response.CacheControl    = "no-cache";
                    System.Web.HttpContext.Current.Response.AppendHeader("Pragma", "No-Cache");
                    System.Web.HttpContext.Current.Response.ClearContent();
                    System.Web.HttpContext.Current.Response.ContentType = "image/Gif";
                    System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());

                    CookieUtils.SetCookie("gif", DEncryptUtils.DESEncode(checkCode), 3600 * 24 * 30);
                }
                else
                {
                    _codeimg = image;
                }
            }
            finally
            {
                //显式释放资源
                image.Dispose();
                g.Dispose();
            }
        }
Esempio n. 30
0
 public void SetCookie(string name, string value)
 {
     CookieUtils.SetCookie(name, value);
 }