public ActionResult ChangeAvatar(PrivateCabinetModel model, HttpPostedFileBase file) { if (ModelState.IsValid) { if (file != null) { using (var context = new SimpleMembershipContext()) { var user = context.UserProfiles.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId); user.ImageData = new byte[file.ContentLength]; file.InputStream.Read(user.ImageData, 0, file.ContentLength); user.ImageMimeType = file.ContentType; context.SaveChanges(); } } } return RedirectToAction("Index"); }
public SimpleMembershipInitializer() { Database.SetInitializer<SimpleMembershipContext>(null); try { using (var context = new SimpleMembershipContext()) { if (!context.Database.Exists()) { //Без миграции ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } //инициализация WebSecurity вынесена в Global.asax } catch (Exception ex) { throw new InvalidOperationException("Не удалось инициализировать базу данных ASP.NET Simple Membership. Чтобы получить дополнительные сведения, перейдите по адресу: http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
public ActionResult _SubmitSectionChange(ChangeSectionModel section) { using (var context = new SimpleMembershipContext()) { var db_section = context.Sections.FirstOrDefault(x => x.SectionId == section.SectionId); if (ModelState.IsValid) { try { db_section.SectionTitle = section.SectionTitle; context.SaveChanges(); } catch { Response.StatusCode = (int)HttpStatusCode.BadRequest; } } else { section.SectionTitle = db_section.SectionTitle; Response.StatusCode = (int)HttpStatusCode.BadRequest; } } return PartialView("_Section", section); }
public ActionResult ResetPassword(RecoveryPasswordModel model) { if (ModelState.IsValid) { SimpleMembershipContext db = new SimpleMembershipContext(); //ищем айди юзера по его имени var userid = (from i in db.UserProfiles where i.UserName == model.UserName select i.UserId).FirstOrDefault(); //проверка соответствия айди юзера и токена bool any = (from j in db.webpages_Memberships where (j.UserId == userid) && (j.PasswordVerificationToken == model.Token) select j).Any(); if (any == true) { //сброс пароля bool response = WebSecurity.ResetPassword(model.Token, model.NewPassword); if (response == true) TempData["success"] = "Пароль успешно изменен. Теперь можете войти."; else { TempData["failure"] = "Увы, пароль не был изменен."; } } else { TempData["failure"] = "Выявлено несоотвествие пользователя и токена сброса пароля."; } } else { ModelState.AddModelError("", "Невозможно выполнить сброс пароля."); } return View(); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { try { var context = new SimpleMembershipContext(); var user = context.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower()); context.Dispose(); if (user == null) { WebSecurity.CreateUserAndAccount( model.UserName, model.Password, new { Email = model.Email, Mobile = model.Mobile, RegistrationDate = DateTime.Now } ); Roles.AddUserToRole(model.UserName, "active"); WebSecurity.Login(model.UserName, model.Password); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "Электронный адрес уже существует. Введите другой электронный адрес."); } } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } return View(model); }
public ActionResult Login(LoginModel model) { var user = new UserProfile(); using(var context = new SimpleMembershipContext()) { user = context.UserProfiles.FirstOrDefault(u => u.UserName == model.UserName || u.Email == model.UserName); } if (user != null && ModelState.IsValid) { if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) { return RedirectToAction("Index", "Home"); } else { if (WebSecurity.Login(user.UserName, model.Password, persistCookie: model.RememberMe)) { return RedirectToAction("Index", "Home"); } } } ModelState.AddModelError("", "Данные для входа указаны неверно."); return View(model); }
public ActionResult ForgotPassword(string Email) { var user = new SimpleMembershipContext().UserProfiles.FirstOrDefault(u => u.Email.ToLower() == Email.ToLower()); if (user == null) { TempData["failure"] = "Не существует пользователя с такой почтой."; } else { var token = WebSecurity.GeneratePasswordResetToken(user.UserName); var resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { userName = user.UserName, resetToken = token }, "http") + "'>ссылке</a>"; var subject = "Сброс пароля"; var body = "<b>Для сброса пароля перейдите по </b>" + resetLink; bool flag = true; try { SendEMail(Email, subject, body); } catch (Exception) { flag = false; } if (flag) TempData["success"] = "Письмо для сброса пароля было отправлено на указанную почту"; else TempData["failure"] = "При отправке письме для сброса пароля произошла ошибка"; } return View(); }
public bool RemoveUser(UserModel user) { var result = true; try { var roles = Roles.GetRolesForUser(user.UserName); if (roles != null && roles.Length != 0) { Roles.RemoveUserFromRoles(user.UserName, roles); } using (var context = new SimpleMembershipContext()) { var toRemove = context.UserProfiles.FirstOrDefault(u => u.UserId == user.UserId); toRemove.UserName = null; toRemove.Email = null; toRemove.ImageData = null; toRemove.ImageMimeType = null; toRemove.Mobile = null; context.SaveChanges(); } } catch { result = false; } return result; }
public PartialViewResult _GetCommentData(CommentInfo model) { if (model.UserId != WebSecurity.CurrentUserId) { using (var context = new SimpleMembershipContext()) { var record = context.Likes.FirstOrDefault(l => l.UserId == WebSecurity.CurrentUserId && l.CommentId == model.CommentId); if (record == null) { context.Likes.Add(new Like { CommentId = model.CommentId, UserId = WebSecurity.CurrentUserId, Vote = 1 }); model.CommentVote++; } else { if (record.Vote == 0) { record.Vote++; model.CommentVote++; } else { model.CommentVote--; record.Vote--; } } context.SaveChanges(); } } return PartialView("_GetCommentData", model); }