public ActionResult Login(Account model, string returnUrl) { if (ModelState.IsValid) { using (DbTESTEntities1 entities = new DbTESTEntities1()) { string username = model.name; string password = model.password; // Now if our password was enctypted or hashed we would have done the // same operation on the user entered password here, But for now // since the password is in plain text lets just authenticate directly Account userValid = entities.Account.SingleOrDefault(user => user.name == username && user.password == password); // User found in the database if (userValid!=null) { string userdata = userValid.roles; string formsCookieStr = string.Empty; HttpContext currentContext = System.Web.HttpContext.Current; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, userdata, FormsAuthentication.FormsCookiePath); formsCookieStr = FormsAuthentication.Encrypt(ticket); HttpCookie FormsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, formsCookieStr); currentContext.Response.Cookies.Add(FormsCookie); //FormsAuthentication.SetAuthCookie(username, false); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } } // 如果執行到這裡,發生某項失敗,則重新顯示表單 return View(model); }
//[Authorize(Roles = "admin")] public JsonResult CreateAccount(string name,string password, string phone, string email,string roles) { Account userValid = db.Account.SingleOrDefault(user => user.name == name); if (userValid != null) { return Json("已有此帳號", JsonRequestBehavior.AllowGet); } try { Account data = new Account { name = name, password =password, phone = phone, email = email, roles = roles }; db.Account.Add(data); db.SaveChanges(); return Json("新增成功", JsonRequestBehavior.AllowGet); } catch { return Json("新增失敗", JsonRequestBehavior.AllowGet); } }
public ActionResult Verify(string guidString) { string msg = ""; if(guidString==null) { msg = "無認證字串"; } else if (guidString != null) { string[] strs = guidString.Split('@'); string guid = strs[0]; string name = strs[1]; var query = (from p in db.AccountVerify where p.guid == guid && p.name == name select p).FirstOrDefault(); try { Account data = new Account { name = query.name, password = query.password, phone = query.phone, email = query.email, address =query.address, roles = query.roles }; db.Account.Add(data); db.SaveChanges(); AccountVerify account = db.AccountVerify.Find(query.id); db.AccountVerify.Remove(account); db.SaveChanges(); msg = "帳號已啟動"; //return Json("帳號已啟動", JsonRequestBehavior.AllowGet); } catch { msg = "帳號啟動失敗"; //return Json("帳號啟動失敗", JsonRequestBehavior.AllowGet); } } ViewData["msg"] = msg; return View(); }