public ActionResult My() { ApplicationUserManager userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); string userId = User.Identity.GetUserId(); // get user roles List <string> roles = userManager.GetRoles(userId).ToList(); var user = System.Web.HttpContext.Current.User.Identity.GetUserId(); ApplicationDbContext db = new ApplicationDbContext(); ApplicationMyUser mUser = db.Users.Find(user); if (mUser != null) { if (System.Web.HttpContext.Current.User.IsInRole("admin")) { return(View("AdminCabinet", mUser)); } else if (System.Web.HttpContext.Current.User.IsInRole("manager")) { return(View("ManagerCabinet", mUser)); } else { //ViewBag.Orders = mUser.Orders.ToList().ToPagedList(pageNumber, pageSize); return(View("MyCabinet", mUser)); } } else { return(View("Index")); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationMyUser { UserName = model.Email, Email = model.Email, IsBloked = false }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // Дополнительные сведения о включении подтверждения учетной записи и сброса пароля см. на странице https://go.microsoft.com/fwlink/?LinkID=320771. // Отправка сообщения электронной почты с этой ссылкой // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы return(View(model)); }
public ActionResult MyOrders(int?page, string Id) { ApplicationDbContext db = new ApplicationDbContext(); ApplicationMyUser mUser = db.Users.Find(Id); int pageSize = 3; int pageNumber = (page ?? 1); return(View(mUser.Orders.ToList().ToPagedList(pageNumber, pageSize))); }
private bool IsAdmin(ApplicationMyUser mUser, List <string> roles) { foreach (var role in roles) { if (role == "admin") { return(true); } } return(false); }
private bool IsManager(ApplicationMyUser mUser, List <string> roles) { foreach (var role in roles) { if (role == "manager") { return(true); } } return(false); }
// POST: ApplicationMyUsers/Create // Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные // сведения см. в статье https://go.microsoft.com/fwlink/?LinkId=317598. // GET: ApplicationMyUsers/Edit/5 public ActionResult Edit(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ApplicationMyUser applicationMyUser = applicationMyUserRepository.FindUser(id); if (applicationMyUser == null) { return(HttpNotFound()); } return(View(applicationMyUser)); }
public ActionResult Create(int?id) { if (id != null) { ViewBag.IdJourney = new SelectList(db.Journeys.ToList(), "IdJourney", "IdJourney"); Order order = new Order(); Journey journey = db.Journeys.Find(id); order.Journey = journey; order.IdJourney = id; ApplicationMyUser myUser = db.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()); order.User = myUser; return(View(order)); } return(Redirect("Home/Index")); }
public ActionResult Edit([Bind(Include = "Id,IsBloked,Email,UserName")] ApplicationMyUser applicationMyUser) { ApplicationMyUser user = applicationMyUserRepository.FindUser(applicationMyUser.Id); if (user != null) { user.IsBloked = applicationMyUser.IsBloked; if (ModelState.IsValid) { log.Info(" Пользователь " + User.Identity.Name + " c айпи " + Request.UserHostAddress + " изменил пользователя " + applicationMyUser.Email + " с айди " + applicationMyUser.Id); applicationMyUserRepository.Modified(user); return(RedirectToAction("Index")); } } return(View(applicationMyUser)); }
public ActionResult MyCreate(int?Idjourney) { if (Idjourney == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Order order = new Order(); order.Discount = 0; ApplicationMyUser myUser = db.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()); order.User = myUser; order.OrderStatus = db.OrderStatuses.Find(1); order.Journey = db.Journeys.Find(Idjourney); return(Redirect("Home/Index")); }
public ActionResult AddUser(UserCreatedByAdmin user) { ApplicationDbContext db = new ApplicationDbContext(); var userManager = new ApplicationUserManager(new UserStore <ApplicationMyUser>(db)); var identityRole = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(db)); var adminsUser = new ApplicationMyUser { Email = user.Email, UserName = user.Email, IsBloked = false }; var result = userManager.Create(adminsUser, user.Password); if (result.Succeeded) { userManager.AddToRole(adminsUser.Id, identityRole.FindByName(user.Role).Name); log.Info(" Пользователь " + User.Identity.Name + " c айпи " + Request.UserHostAddress + " добавил пользователя " + user.Email + " c ролью " + user.Role); } db.SaveChanges(); return(Redirect("/Home/My")); }
public ActionResult Create([Bind(Include = "IdOrder,IdJourney,IdOrderStatus,Discount,User_Id,CountOfJourneys")] Order order) { Journey journey = db.Journeys.Find(order.IdJourney); order.Journey = journey; if (ModelState.IsValid) { OrderStatus orderStatus = db.OrderStatuses.Find(1); order.Discount = 0; ApplicationMyUser myUser = db.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()); order.User = myUser; order.Journey = journey; int?countJourneys = journey.StartedAmount - journey.QuantitySold; if (countJourneys != null) { if (order.CountOfJourneys > 0 && order.CountOfJourneys <= countJourneys) { EditJourneys(journey, (int)order.CountOfJourneys); OrderStatus status = db.OrderStatuses.Find(1); order.OrderStatus = status; order.OrderStatus_IdOrder = 1; db.Orders.Add(order); db.SaveChanges(); //orderRepository.Add(order); log.Info(" Пользователь " + User.Identity.Name + " c айпи " + Request.UserHostAddress + " создал заказ " + order.IdOrder); return(RedirectToAction("Index", "Home")); } else { ViewBag.Error = "Колличество запрашиваемых путевок выдать не возможно так как осталось " + countJourneys.ToString(); log.Info(" Пользователь " + User.Identity.Name + " c айпи " + Request.UserHostAddress + " пытался создать заказ "); return(View(order)); } } return(View(order)); } ViewBag.IdJourney = new SelectList(db.Journeys.ToList(), "IdJourney", "IdJourney", order.IdJourney); return(View(order)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Получение сведений о пользователе от внешнего поставщика входа var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationMyUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
protected override void Seed(ApplicationDbContext context) { var hotelsTypes = new List <HotelsType> { new HotelsType { HotelType = "Апарт-отель" }, new HotelsType { HotelType = "Мотель " }, new HotelsType { HotelType = "Гостевой дом" }, new HotelsType { HotelType = "Отели-курорты" }, new HotelsType { HotelType = "Бизнес-отели" } }; hotelsTypes.ForEach(hT => context.HotelsTypes.Add(hT)); var orderStatuses = new List <OrderStatus> { new OrderStatus { OrdersStatus = "Зарегистрирован" }, new OrderStatus { OrdersStatus = "Оплачен" }, new OrderStatus { OrdersStatus = "Отменен" } }; orderStatuses.ForEach(oS => context.OrderStatuses.Add(oS)); var typesTour = new List <TypesTour> { new TypesTour { TypeTour = "Отдых" }, new TypesTour { TypeTour = "Экскурсия" }, new TypesTour { TypeTour = "Шоппинг" } }; typesTour.ForEach(tT => context.TypesTours.Add(tT)); var userManager = new ApplicationUserManager(new UserStore <ApplicationMyUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); // создаем две роли var role1 = new IdentityRole { Name = "admin" }; var role2 = new IdentityRole { Name = "user" }; var role3 = new IdentityRole { Name = "manager" }; // добавляем роли в бд roleManager.Create(role1); roleManager.Create(role2); roleManager.Create(role3); // создаем пользователей var admin = new ApplicationMyUser { Email = "*****@*****.**", UserName = "******" }; string password = "******"; var result = userManager.Create(admin, password); // если создание пользователя прошло успешно if (result.Succeeded) { // добавляем для пользователя роль userManager.AddToRole(admin.Id, role1.Name); userManager.AddToRole(admin.Id, role2.Name); userManager.AddToRole(admin.Id, role3.Name); } context.SaveChanges(); base.Seed(context); }