protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { if (FormsAuthentication.CookiesSupported) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now var username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; var roles = string.Empty; using (var entities = new MySiteEntities()) { var user = entities.Users.SingleOrDefault(u => u.UserId == username); roles = user.Roles; } //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details HttpContext.Current.User = new GenericPrincipal( new GenericIdentity(username, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } }
public ActionResult Login(User model, string returnUrl) { // Lets first check if the Model is valid or not if (ModelState.IsValid) { using (var entities = new MySiteEntities()) { IArticleRepository ar = new EF_ArticleRepository(new DbConnectionContext()); var username = model.UserId; var 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 var userValid = entities.Users.Any(user => user.UserId == username && user.Password == password); // User found in the database if (userValid) { FormsAuthentication.SetAuthCookie(username, false); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); }
// GET: /Listing/ // GET: /Article/Articles public ViewResult MyListings(int? page) { var pageSize = 9; var pageNumber = (page ?? 1); var username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; int userId; using (var entities = new MySiteEntities()) { var user = entities.Users.SingleOrDefault(u => u.UserId == username); userId = user.Id; } return View(ar.GetMyListings(userId).ToPagedList(pageNumber, pageSize)); }
public ActionResult Edit(int id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; int userId; using (var entities = new MySiteEntities()) { var user = entities.Users.SingleOrDefault(u => u.UserId == username); userId = user.Id; } var listing = ar.GetMyListingById(userId, id); if (listing == null) { return HttpNotFound(); } return View(listing); }