using SysBaseLibs; using SysDataLibs; using SysDataLibs.TableClass; using System; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Web; using System.Web.Mvc; namespace GSMarketSys.Controllers { public class LoginController : Controller { //GET: Login public ActionResult Index() { ViewBag.UserNo = WebLibs.GetCookieValue("UserName"); ViewBag.RememberMe = ""; ViewBag.ErrorInfo = TempData["ErrorInfo"]; DBConnSql dbConn = new DBConnSql(); dbConn.Open(); ViewBag.SelSystemIDInfo = GetData.Instance.GetSelStr(GSSystem_info.cSystemID, GSSystem_info.cshortName, Tn.GSSystem, GSSystem_info.cSystemType + "='N'", dbConn); dbConn.Close(); if (!string.IsNullOrEmpty(ViewBag.UserNo)) { ViewBag.RememberMe = "checked"; ViewBag.Password = WebLibs.GetCookieValue("UserPassword"); } ////通过平台保存的cookie登陆工商子系统 //if (LoginViaPlatCookie()) //{ // return RedirectToAction("MainIndex", "Main"); //} return View(); } ////通过平台保存的cookie登陆工商子系统 //protected bool LoginViaPlatCookie() //{ // bool lbRetval = false; // try // { // HttpCookie cookie = Request.Cookies["UserName"]; // if (cookie != null) // { // string strUserNo = cookie.Values["GSUserNo"]; // string strGuid = cookie.Values["GSGUID"]; // if ((!string.IsNullOrEmpty(strUserNo)) && (!string.IsNullOrEmpty(strGuid))) // { // UserSession lcUserSession = LoginGUID.Instance.GetOne(strGuid); // if (lcUserSession != null) // { // System.Web.HttpContext.Current.Session[Contants.UserInfoId] = lcUserSession; // lbRetval = true; // //return View(""); // //Response.Redirect("publish/MainIndex.aspx"); // } // } // } // } // catch (Exception err) // { // ThreadLog.LogErr("LoginViaPlatCookie failed, " + err.Message); // } // return lbRetval; //} [HttpPost] public ActionResult Login() { string lcErrorMsg = ""; string userNo = Request["UserNo"]; string password = Request["Password"]; string imageCode = Request["ImageCode"]; //string rememberMe = Request["RememberMe"]; if (SysDataLibs.AppEnv.SysSetObj.GetString("IsShowValidateCode") == "Y" && System.Web.HttpContext.Current.Session["suzygsjCheckCode"]?.ToString().ToLower() != imageCode.ToLower()) { TempData["ErrorInfo"] = "验证码不正确!"; return RedirectToAction("Index"); } if (string.IsNullOrWhiteSpace(userNo) || string.IsNullOrWhiteSpace(password)) { TempData["ErrorInfo"] = "用户名或密码不能为空"; return RedirectToAction("Index"); } bool lbLogin = UserSession.UserLogin(userNo, password, ref lcErrorMsg); //string lIp = ""; //if (Request.UserHostAddress != "") //{ // lIp = Request.UserHostAddress; //} if (lbLogin) { if (Request["RememberMe"] == "on") { WebLibs.SetCookieValue("UserName", userNo.Trim()); WebLibs.SetCookieValue("UserPassword", password.Trim()); } else { WebLibs.SetCookieValue("UserName", ""); WebLibs.SetCookieValue("UserPassword", ""); } if (System.Web.HttpContext.Current.Session != null && System.Web.HttpContext.Current.Session[Contants.UserInfoId] != null) { //UserSession loUserSession = (UserSession)System.Web.HttpContext.Current.Session[Contants.UserInfoId]; } //// 平台单点登录Cookie //if (loUserSession != null && loUserSession.IsSystem) //{ // SetPlatLoginCookie(UserNo, Password); //}//<--- Sys_Log_info loSysLog = new Sys_Log_info { SysLogId = RandomUtil.GetGUID(), LogCommand = "Logion", LogDate = DateTime.Now.ToString(CultureInfo.InvariantCulture), LogMessage = "用户 " + userNo.Trim() + " 登录成功 ", LogErrorMessage = "", LogSite = WebLibs.CurPageName, SysLogType = ((int)LogType.System).ToString(), UserId = userNo.Trim(), UserHostAddress = System.Web.HttpContext.Current.Request.UserHostAddress }; Sys_Log_info.LogMsg(loSysLog); //Response.Redirect("publish/IndexMain.aspx"); //Response.Redirect("Publish/MainIndexNew.aspx"); //JSComm.WebWriteScript("window.location.href='../Publish/AuditList.aspx'"); // FineUI.PageContext.RegisterStartupScript("window.location.href='publish/MainIndex.aspx'"); return RedirectToAction("MainIndex", "Main"); } else { Sys_Log_info loSysLog = new Sys_Log_info { SysLogId = RandomUtil.GetGUID(), LogCommand = "Logion", LogDate = DateTime.Now.ToString(CultureInfo.InvariantCulture), LogMessage = "用户 " + userNo.Trim() + " 登录失败!", LogErrorMessage = lcErrorMsg, SysLogType = ((int)LogType.System).ToString(), UserId = userNo.Trim(), UserHostAddress = System.Web.HttpContext.Current.Request.UserHostAddress }; Sys_Log_info.LogMsg(loSysLog); //JSComm.ShowMessage(lcErrorMsg); //errorDiv.Style.Add("display", "block"); //errormsg.InnerText = "用户 " + lcUserName.Trim() + "登录失败!!"; //return RedirectToAction("Index", "Login", new { ispostback = "true", errormsg = "用户 " + UserNo.Trim() + "登录失败!!" }); TempData["ErrorInfo"] = lcErrorMsg; return RedirectToAction("Index"); //return Content(""); } } public ActionResult LoginOut() { System.Web.HttpContext.Current.Session.RemoveAll(); return RedirectToAction("Index"); } // 平台单点登录Cookie protected void SetPlatLoginCookie(string lcUserName, string lcPassword) { try { if (Request.Cookies["UserName"] != null) { //Request.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1); Request.Cookies.Remove("UserName"); } HttpCookie cookie = new HttpCookie("UserName") { Domain = "sipac.gov.cn", Expires = DateTime.Now.AddMinutes(30) }; // 本机调试时注释此行 cookie.Values.Add("GSUserNo", lcUserName); string strGuid = Guid.NewGuid().ToString("N"); UserSession session = System.Web.HttpContext.Current.Session[Contants.UserInfoId] as UserSession; if (session != null) { LoginGUID.Instance.AddOne(strGuid, session); cookie.Values.Add("GSGUID", strGuid); } else { cookie.Values.Add("GSGUID", ""); } // 工商用户是否在平台注册过 string strAppNo = "1001"; nsSubSysUserManage.ServiceUserInfo userInfo = ISipPlatHelper.SubSysUserInfo(lcUserName, strAppNo); if (string.IsNullOrEmpty(userInfo?.UserNo)) return; // 通过工商系统的用户名调用平台提供的单点登录接口获得用户令牌 string lcEncryptPwd = SysSecLibs.SysSecurity.Encrypt(lcPassword); nsRightsWS.ServiceLogin result = ISipPlatHelper.LoginToPlatOrSubSys(lcUserName, lcEncryptPwd, strAppNo); if (result != null && result.Flag) { if (!string.IsNullOrEmpty(result.AuUrl)) { // 格式为:"http://spjg.sipac.gov.cn/SPJG/Layout/BaseLayout/Login.aspx?GUID=326d1948-5399-42f2-bb4d-56e8c93c0599&AppNo=1001&UserNo=sabAdmin"; string lcAuUrl = result.AuUrl; int nStart = lcAuUrl.IndexOf("GUID=", StringComparison.Ordinal); if (nStart > 0) { int nEnd = lcAuUrl.IndexOf("&", nStart, StringComparison.Ordinal); if (nEnd > 0) { string strAppGuid = lcAuUrl.Substring(nStart + 5, nEnd - nStart - 5); cookie.Values.Add("AppGUID", strAppGuid); } } } } // 写入Cookie Response.Cookies.Add(cookie); } catch (Exception err) { ThreadLog.LogErr("SetPlatLoginCookie failed, " + err.Message); } } private string CreateRandomCode(int codeCount) { string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z"; string[] allCharArray = allChar.Split(','); string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < codeCount; i++) { if (temp != -1) { rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); } int t = rand.Next(35); if (temp == t) { return CreateRandomCode(codeCount); } temp = t; randomCode += allCharArray[t]; } return randomCode; } private Bitmap CreateImage(string checkCode) { int iwidth = checkCode.Length * 12; Bitmap image = new Bitmap(iwidth, 20); Graphics g = Graphics.FromImage(image); Font f = new Font("Arial", 11, FontStyle.Bold); Brush b = new SolidBrush(Color.Black); //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); //g.Clear(Color.Blue); g.Clear(ColorTranslator.FromHtml("#A9BACA")); g.DrawString(checkCode, f, b, 2, 3); Pen blackPen = new Pen(ColorTranslator.FromHtml("#114889"), 1); Random rand = new Random(); for (int i = 0; i < 3; i++) { int y = rand.Next(image.Height); g.DrawLine(blackPen, 0, y, image.Width, y); } MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); //Response.ClearContent(); //Response.ContentType = "image/Jpeg"; //Response.BinaryWrite(ms.ToArray()); //g.Dispose(); //image.Dispose(); return image; } public FileContentResult ValidateCode() { //string code = GetRndStr(); string checkCode = CreateRandomCode(4); System.Web.HttpContext.Current.Session["suzygsjCheckCode"] = checkCode; byte[] imageByte; using (Bitmap img = CreateImage(checkCode)) { imageByte = BitmapToByte(img); //Session["validate"] = code; } return File(imageByte, "image/gif"); } public static byte[] BitmapToByte(Bitmap bitmap) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Jpeg); byte[] data = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(data, 0, Convert.ToInt32(stream.Length)); return data; } } public ActionResult Register() { DBConnSql dbConn = new DBConnSql(); dbConn.Open(); string systemId = GetRequest("SystemID"), warrantNumber = GetRequest("WarrantNumber"), password = GetRequest("Password"), regionId = "100001 ", regionName = new Regions_info(regionId, dbConn).Names, userName = GetRequest("UserName"), linkTel = GetRequest("LinkTel"); if (Utils.ProcessSqlStr(userName)|| Utils.ProcessSqlStr(linkTel) || Utils.ProcessSqlStr(warrantNumber)) { return Content(ErrorRebackInfo.GetErrorBackInfo(false,"0","输入参数包含敏感字符!")); } SysRegisters_info registersInfo = new SysRegisters_info { RegisterID = Guid.NewGuid().ToString("N"), SystemID = systemId, WarrantNumber = warrantNumber, MarketID = warrantNumber, MarketName = userName, //ValidStartTime = validStartTime, //ValidEndTime = validEndTime, RegionID = regionId, RegionName = regionName, LinkTel = linkTel, UserCode = warrantNumber.Substring(9), UserName = userName, IsAudit = "N", RegisterIP = System.Web.HttpContext.Current.Request.UserHostAddress, RegisterDate = DateTime.Now.ToShortDateString(), Password = password }; ThreadLog.LogInfo("----注册Sql:"+registersInfo.InsertSql()); if (dbConn.ExcuteSqlTran(registersInfo.InsertSql())) { dbConn.Close(); return Content(SysRebackDisplayInfo.Instance.GetDisplayValue("Reg_Success")); } dbConn.Close(); return Content(SysRebackDisplayInfo.Instance.GetDisplayValue("Reg_Error")); } /// /// 获取Requset[key]值,并ToSQL处理 /// /// /// /// private string GetRequest(string key, string type = "string") { string lcRetval = Request[key] ?? ""; if (type.ToLower() == "int") lcRetval = GetData.Instance.SetIntDefault(lcRetval); return Utils.AreaToSQLcs(lcRetval); } } }