AccountController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using System.Web.Security; using Newtonsoft.Json; using Yb.Data.Provider; using Yb.PermissionModel; using Yb.PermissionModel.Provider; using YbRapidSolution.Data; using YbRapidSolution.Entities; using YbRapidSolution.Mvc.Models; using YbRapidSolution.Presenter.Compression; using YbRapidSolution.Services; namespace YbRapidSolution.Mvc.Controllers.Security { [MvcCompression] public class AccountController : Controller { private readonly ICustomerService _service; public AccountController(ICustomerService service) { _service = service; } #region 后台登录与注销 // // GET: /Logon/ [AllowAnonymous] public ActionResult Login() { return View(new LoginModel()); } [AllowAnonymous] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Login(LoginModel model) { if (!ModelState.IsValid) { if (string.IsNullOrWhiteSpace(model.UserName)) ViewBag.EasyUIMessage = "请输入用户名"; else if (string.IsNullOrWhiteSpace(model.Password)) ViewBag.EasyUIMessage = "请输入登录密码"; else { AuditLogApi.Info(string.Format("用户‘{0}’登录失败,IP地址:{1}", model.UserName, GetIP4Address())); ViewBag.EasyUIMessage = "验证失败,必须输入用户名和密码"; } return View(model); } try { var result = PersonApi.ValidatePerson(model.UserName, model.Password); if (result!=null) { var psm = OrgApi.FindPersonMembersBy(result.ID).Where(c=>c.Status>0).Select(c=>c.Parent); var authCookie = FormsAuthentication.GetAuthCookie(model.UserName, model.RememberMe); var ticket = FormsAuthentication.Decrypt(authCookie.Value); var userModel = new IdentifyModel { ID = result.ID, UserName = result.UserName, DisplayName = result.DisplayName, Code = result.Code, Email = result.Email, IDCard = result.IDCard, PasswordTimeLimit = result.PasswordTimeLimit, MainOrgID = result.MainOrgID, Lang = result.Lang, Theme = result.Theme }; userModel.SetOrgIds(psm); var userData = JsonConvert.SerializeObject(userModel); //var userData = "1"; //var userData = SerializerUtility.StringSerialize(userModel); var newTicket = new FormsAuthenticationTicket( ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData); // 将新的Ticke转变为Cookie值,然后添加到Cookies集合中 authCookie.Value = FormsAuthentication.Encrypt(newTicket); this.HttpContext.Response.Cookies.Add(authCookie); AuditLogApi.Info(string.Format("用户‘{0}’登录成功,IP地址:{1}", model.UserName, GetIP4Address())); // 获得 来到登录页之前的页面,即url中return参数的值 string url = FormsAuthentication.GetRedirectUrl(model.UserName, model.RememberMe); return Redirect(url); } ViewBag.EasyUIMessage = "错误的用户名或密码"; return View(model); } catch (Exception er) { ViewBag.EasyUIMessage = er.Message; return View(model); } } [AllowAnonymous] public ActionResult SignOut() { FormsAuthentication.SignOut(); return Redirect("~/Account/Login"); } #endregion #region 前台登录、注销方法 [AllowAnonymous] public ActionResult Logon() { var model = new LoginModel(); var cookies = this.Request.Cookies; var cookie=cookies.Get("Customer"); if (cookie!=null && cookie.HasKeys) { model.UserName= cookie["tel"]; } return View(model); } [AllowAnonymous] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Logon(LoginModel model) { var tel = ""; var pwd = ""; if (!ModelState.IsValid) { if (string.IsNullOrWhiteSpace(model.UserName)) { ViewBag.EasyUIMessage = "请输入电话号码"; return View("Logon", model); } if (string.IsNullOrWhiteSpace(model.Password)) { ViewBag.EasyUIMessage = "请输入验证码"; return View("Logon", model); } } tel = model.UserName.Trim(); if (!IsMobilePhone(tel)) { ViewBag.EasyUIMessage = "手机号码格式不正确"; return View("Logon", model); } pwd = model.Password.Trim(); if (!IsValidCode(pwd)) { ViewBag.EasyUIMessage = "验证码格式不对,验证码为4为数字"; return View("Logon", model); } try { var user = _service.GetByTel(model.UserName); if (user != null) { if (user.DeleteStatus == (int)DeleteStatus.Deleted) { ViewBag.EasyUIMessage = "当前用户已被禁用,请联系管理员"; return View("Logon", model); } if (user.SendDate < DateTime.Now.AddMinutes(-30)) { ViewBag.EasyUIMessage = "验证码已过期,请重新获取验证码."; return View("Logon", model); } if (user.ValidationCode!=model.Password) { ViewBag.EasyUIMessage = "验证码错误,请确认后重新输入."; return View("Logon", model); } var authCookie = FormsAuthentication.GetAuthCookie(model.UserName, true); var ticket = FormsAuthentication.Decrypt(authCookie.Value); var userModel = new IdentifyModel { ID = user.Id, UserName = model.UserName }; var userData = JsonConvert.SerializeObject(userModel); //var userData = "1"; //var userData = SerializerUtility.StringSerialize(userModel); var newTicket = new FormsAuthenticationTicket( ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration.AddYears(30), true, userData); // 将新的Ticke转变为Cookie值,然后添加到Cookies集合中 authCookie.Value = FormsAuthentication.Encrypt(newTicket); authCookie.Expires = ticket.Expiration.AddYears(30); this.HttpContext.Response.Cookies.Add(authCookie); var cookie = new HttpCookie("Customer"); cookie["tel"] = model.UserName; cookie.Expires = DateTime.Now.AddYears(30); this.Response.Cookies.Add(cookie); AuditLogApi.Info(string.Format("用户‘{0}’登录成功,IP地址:{1}", model.UserName, GetIP4Address())); var url = ""; if (this.TempData.ContainsKey("Url")) { var value = this.TempData["Url"]; if (value != null) { url = value.ToString(); } } else { url = FormsAuthentication.GetRedirectUrl(model.UserName, model.RememberMe); } if (string.IsNullOrWhiteSpace(url) || url.ToLower().Contains("/admin")) { return RedirectToAction("Index", "Home"); } return Redirect(url); } ViewBag.EasyUIMessage = "请首先获取验证码"; return View("Logon", model); } catch (Exception er) { ViewBag.EasyUIMessage = er.Message; return View("Logon", model); } } [AllowAnonymous] public ActionResult SignOutHome() { return Redirect("/Account/Logon"); } #endregion #region Help 方法 public static bool IsMobilePhone(string input) { Regex regex = new Regex("^1\\d{10}$"); return regex.IsMatch(input); } public static bool IsValidCode(string input) { Regex regex = new Regex("\\d{4}"); return regex.IsMatch(input); } public static string GetIP4Address() { string IP4Address = String.Empty; foreach (IPAddress IPA in Dns.GetHostAddresses(System.Web.HttpContext.Current.Request.UserHostAddress)) { if (IPA.AddressFamily.ToString() == "InterNetwork") { IP4Address = IPA.ToString(); break; } } if (IP4Address != String.Empty) { return IP4Address; } foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName())) { if (IPA.AddressFamily.ToString() == "InterNetwork") { IP4Address = IPA.ToString(); break; } } return IP4Address; } #endregion } }