public async Task <IActionResult> Login(LoginForm form) { if (!ModelState.IsValid) { return(View(form)); } var user = await manager.FindByNameAsync(form.Username); if (user != null) { if ((await signIn.PasswordSignInAsync(user, form.Password, false, false)).Succeeded) { return(Redirect(form?.ReturnUrl ?? "/")); } } ModelState?.AddModelError(null, "Введены неправильные имя или пароль"); return(View(form)); }
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // TODO var result = await SignInManager.PasswordSignInAsync(model.Ssn, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: // Screw that -> return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } }
public ActionResult Delete(CMS_NewsModels model) { try { //if (!ModelState.IsValid) //{ // Response.StatusCode = (int)HttpStatusCode.BadRequest; // return PartialView("_Delete", model); //} var msg = ""; var result = _factory.Delete(model.Id, ref msg); if (result) return RedirectToAction("Index"); ModelState.AddModelError("Title", msg); Response.StatusCode = (int)HttpStatusCode.BadRequest; return PartialView("_Delete", model); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return PartialView("_Delete", model); } }
public async Task <ActionResult> AddFeatureValue(FeatureValueViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } var featureValuesPresent = await TenderProvider.GetFeatureValues(viewModel.TenderGuid, viewModel.FeatureStringId); var featureValuesSum = featureValuesPresent.Sum(m => m.Value); if (viewModel.Value + featureValuesSum > 0.3) { ModelState.AddModelError(nameof(viewModel.Value), GlobalRes.MaximumNonPriceCriteriaMessage); return(View(viewModel)); } var featureValueDTO = viewModel.ToDTO(); await TenderProvider.AddFeatureValue(viewModel.TenderGuid, viewModel.FeatureStringId, featureValueDTO); return(RedirectToAction("Info", "DraftTenderInfo", new { tenderGuid = viewModel.TenderGuid })); }
public async Task <ActionResult> Checkout(CheckoutViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var cart = new ShoppingCart(HttpContext); var userName = User.Identity.Name; var result = await cart.CheckoutAsync(model, userName); if (result.Succeeded) { TempData["transactionId"] = "Thanks for your order. Your transaction ID is " + result.TransactionId; return(RedirectToAction("Complete")); } ModelState.AddModelError(string.Empty, result.Message); return(View(model)); }
public async Task <IActionResult> Create(CreateUserViewModel model) { if (ModelState.IsValid) { User user = new User { Email = model.Email, UserName = model.Email, Year = model.Year }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(RedirectToAction("Index")); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } return(View(model)); }
public ActionResult Create([Bind(Include = "StopID,lat,longitude,stop,RouteId")] StopOver stopOver) { var stopOvers = db.StopOvers.Where(x => x.stop == stopOver.stop); if (stopOvers.Count() != 0) { ModelState.AddModelError("", "The Stop-Overs already exists"); } if (ModelState.IsValid) { var name = stopOver.stop.Split(';'); foreach (var n in name) { stopOver.stop = n; db.StopOvers.Add(stopOver); db.SaveChanges(); } return RedirectToAction("Index"); } ViewBag.RouteId = new SelectList(db.Routes, "RouteId", "RouteName", stopOver.RouteId); return View(stopOver); }
private bool ValidateRegistration(string userName, string email, string password, string confirmPassword) { if (String.IsNullOrEmpty(userName)) { ModelState.AddModelError("username", "You must specify a username."); } if (String.IsNullOrEmpty(email)) { ModelState.AddModelError("email", "You must specify an email address."); } if (password == null || password.Length < MembershipService.MinPasswordLength) { ModelState.AddModelError("password", String.Format(CultureInfo.CurrentCulture, "You must specify a password of {0} or more characters.", MembershipService.MinPasswordLength)); } if (!String.Equals(password, confirmPassword, StringComparison.Ordinal)) { ModelState.AddModelError("_FORM", "The new password and confirmation password do not match."); } return(ModelState.IsValid); }
public bool checkForApplyVisaValidation(ApplyVisa U) { if (U.CountryId == 0 || U.CountryId.ToString().Trim().Length == 0) { ModelState.AddModelError("CountryId", "Select Country"); return true; } else if (U.DateOfApplication == null || U.DateOfApplication.ToString().Trim().Length == 0) { ModelState.AddModelError("DateOfApplication", "Fill Date"); return true; } else if (U.Occupation == "-1" || U.Occupation.ToString().Trim().Length == 0) { ModelState.AddModelError("Occupation", "Select Occupation"); return true; } else { return false; } }
public ActionResult Index(Support s) { RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper(); if (String.IsNullOrEmpty(recaptchaHelper.Response)) { ModelState.AddModelError("", "Captcha answer cannot be empty."); return View(s); } RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse(); if (recaptchaResult != RecaptchaVerificationResult.Success) { ModelState.AddModelError("", "Incorrect captcha answer."); return View(s); } if (ModelState.IsValid) { _mailPusher.SendEmail("*****@*****.**", "Administrator","*****@*****.**", s.Subject +" "+ s.Name + "[" + s.MobileNumber + "]", s.Message); TempData["msg"] = "Your Message has been Successfully Sent"; return View(); } ModelState.AddModelError("", "Kindly ensure you supply all necessary and required details"); return View(s); }
public ActionResult Index(HttpPostedFileBase csvFile) { if (ModelState.IsValid) { if (csvFile != null) { using (var iRepo = new ImportRepository()) { iRepo.ImportFileData(csvFile.InputStream, csvFile.ContentLength); ViewBag.ImportSuccess = true; return(View()); } } else { ModelState.AddModelError("", "PDW file is required to upload new data."); } } return(View()); }
private void AddBrokenRuleInfo <T>(T item, string defaultText) where T : class, ISavable { if (item is BusinessBase bb) { var errors = bb.BrokenRulesCollection. Where(r => r.Severity == RuleSeverity.Error); foreach (var rule in errors) { if (string.IsNullOrEmpty(rule.Property)) { ModelState.AddModelError(string.Empty, rule.Description); } else { ModelState.AddModelError(rule.Property, rule.Description); } } } else { ModelState.AddModelError(string.Empty, defaultText); } }
public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { User user = new User { Email = model.Email, UserName = model.Email, Year = model.Year }; // додаємо користувача var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "user"); // генерация токена для пользователя var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action( "ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); EmailService emailService = new EmailService(_config); await emailService.SendEmailAsync(model.Email, "Confirm your account", $"Щоб підтвердити реєстрацію, перейдіть по посиланню: <a href='{callbackUrl}'>link</a>"); return Content("Щоб підтвердити реєстрацію, перевірте пошту та перейдіть по посиланню в листі"); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } return View(new RegisterViewModel { ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList() }); }
public IActionResult EditCategoryItem(int? id) { if (id == null) { return NotFound(); } var foundItem = _context.CaseReportFormCategories .Where(crfc => crfc.ID == id) .FirstOrDefault(); if (foundItem == null) { return NotFound(); } foundItem.Name = Request.Form["Name"]; if (TryValidateModel(foundItem)) { try { _context.Update(foundItem); _context.SaveChanges(); } catch (DbUpdateException /* ex */) { ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists, " + "see your system administrator."); } } else { Hashtable errors = ModelStateHelper.Errors(ModelState); return Json(new { success = false, errors }); } return Json(new { result = "ok" }); }
public async Task<IActionResult> SignIn(SignInModel model,string returnUrl) { try { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.UserName); if (user == null) { ModelState.AddModelError("ex", ExceptionMessages.UserNotFound); return View(model); } if (user.IsBlocked) { ModelState.AddModelError("ex", ExceptionMessages.UserIsBlocked); return View(model); } var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, false); if (result.Succeeded) return RedirectToAction(nameof(UserController.Index),UserController.Name,new { area= UserController.Area }); if (result.IsLockedOut) ModelState.AddModelError("ex", ExceptionMessages.UserIsLockedOut); else if (result.IsNotAllowed) ModelState.AddModelError("ex", ExceptionMessages.UserIsNotAllowed); else ModelState.AddModelError("ex", ExceptionMessages.UserCredentialsIncorrect); return View(model); } catch (Exception e) { ModelState.AddModelError("ex", e.Message); return View(model); } }
public ActionResult Create([Bind(Include = "DocNo,OrganName,Date,Subject,ActName,StartDate,EndDate,Place,StdBudget,OthName,OthBudget,Total,Act1,Act2,Act3,Act4,Act5,Act6,Result1,Comment1,Result1Date,Result2,Comment2,Result2Date,Result3,Comment3,Result3Date,Result4,Comment4,Result4Date,Result5,Comment5,Result5Date,Result6,Comment6,Result6Date,Result7,Comment7,Result7Date,Remark")] Proposal proposal, HttpPostedFileBase upload) { try { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { var avatar = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } proposal.Files = new List <File> { avatar }; } db.Proposals.Add(proposal); db.SaveChanges(); return(RedirectToAction("Index")); } } catch (RetryLimitExceededException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return(View(proposal)); }
public IActionResult AddRefueling(NewRefulingVm model) { if (model is null) { TempData["InCorrectOperation"] = "Tankowanie nie dodane, skontaktuj się z pomocą techniczną aby zgłosić błąd, lub spróbuj ponownie!"; return(RedirectToAction("VehicleHistory", "Vehicle", new { id = model.VehicleId })); } if (model.VehicleId != 0) { model.LastMeters = _vehicleService.GetLastRefuelingMileage(model.VehicleId); } if (model.MeterStatus < model.LastMeters) { ModelState.AddModelError("MeterStatus", $"Aktualny przebieg, nie może być niższy od poprzedniego - {model.LastMeters} km, edytuj przebieg pojazdu, lub wpisz inną wartość!"); } if (!ModelState.IsValid) { model.VehicleFuelTypes = _vehicleService.GetAllFuelsTypesForRefuling(); model.UnitOfFuelForList = _vehicleService.GetUnitsOfFuels(); model.VehiclesList = _vehicleService.GetUserCars(_userManager.GetUserId(User)); return(View(model)); } var carHistory = _vehicleService.ReturnCarHistoryToAdd("Tankowanie", _userManager.GetUserId(User)); var isAddedRefuelingCorrectly = _vehicleService.AddRefuling(model, carHistory); if (isAddedRefuelingCorrectly == true) { TempData["CorrectOperation"] = "Pomyślnie dodano tankowanie!"; } else { TempData["InCorrectOperation"] = "Tankowanie nie dodane, skontaktuj się z pomocą techniczną aby zgłosić błąd, lub spróbuj ponownie!"; } return(RedirectToAction("VehicleHistory", "Vehicle", new { id = model.VehicleId })); }
public IActionResult Create(User user) { if (ModelState.IsValid) { User CheckEmail = _context.user.SingleOrDefault(x => x.email == user.email); if (CheckEmail == null) { PasswordHasher <User> Hasher = new PasswordHasher <User>(); user.password = Hasher.HashPassword(user, user.password); User newUser = new User { firstName = user.firstName, lastName = user.lastName, email = user.email, password = user.password }; _context.user.Add(newUser); _context.SaveChanges(); HttpContext.Session.SetInt32("UserInSession", user.UserId); HttpContext.Session.SetString("UserName", user.firstName); return(RedirectToAction("Dashboard")); } else { ModelState.AddModelError("email", "This email is already taken!"); return(View("Index")); } } else { return(View("Index")); } }
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } }
public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto) { ActionResult <UserDto> res; if (await _userManager.Users.AnyAsync(x => x.Email == registerDto.Email)) { ModelState.AddModelError("email", "Email taken"); res = ValidationProblem(); } else if (await _userManager.Users.AnyAsync(x => x.UserName == registerDto.Username)) { ModelState.AddModelError("username", "Username taken"); res = ValidationProblem(); } else { var user = new AppUser { DisplayName = registerDto.DisplayName, Email = registerDto.Email, UserName = registerDto.Username, }; var result = await _userManager.CreateAsync(user, registerDto.Password); if (result.Succeeded) { await SetRefreshToken(user); res = CreateUserObject(user); } else { res = BadRequest("Problem registering user"); } } return(res); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { Клиенты user = null; using (library_globalContext db = new library_globalContext()) { user = db.Клиенты.FirstOrDefault(u => u.Login == model.Name); } if (user == null) { // создаем нового пользователя using (library_globalContext db = new library_globalContext()) { int lastid = db.Клиенты.Max(u => u.IdКлиента); db.Клиенты.Add(new Клиенты { IdКлиента = lastid + 1, Login = model.Name, Password = model.Password, IdRole = 2 }); db.SaveChanges(); user = db.Клиенты.Where(u => u.Login == model.Name && u.Password == model.Password).FirstOrDefault(); } // если пользователь удачно добавлен в бд if (user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "Пользователь с таким логином уже существует"); } } return(View(model)); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Login, Input.Password, Input.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { _logger.LogInformation("User logged in."); Log.Logger.Information("User logged in : " + Input.Login); return(LocalRedirect(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); Log.Logger.Warning("User account locked out : " + Input.Login); return(RedirectToPage("./Lockout")); } else { Log.Logger.Warning("Invalide Login : "******"Invalid login attempt."); return(Page()); } } // If we got this far, something failed, redisplay form return(Page()); }
public IActionResult Login(LoginViewModel login) { if (!ModelState.IsValid) { return(View(login)); } var _client = _httpClientFactory.CreateClient("BlogClient"); var jsonBody = JsonConvert.SerializeObject(login); var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); var response = _client.PostAsync("/Api/Auth", content).Result; if (response.IsSuccessStatusCode) { var token = response.Content.ReadAsStringAsync().Result; var claims = new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, login.UserName), new Claim(ClaimTypes.Name, login.UserName), new Claim("AccessToken", token) }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var properties = new AuthenticationProperties { IsPersistent = true, AllowRefresh = true }; HttpContext.SignInAsync(principal, properties); return(Redirect("/Home")); } else { ModelState.AddModelError("Username", "User Not Valid"); return(View(login)); } }
public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"کاربر با شناسه '{_userManager.GetUserId(User)}' یافت نشد."); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { ModelState.AddModelError(string.Empty, "کلمه عبور صحیح نمی باشد."); return Page(); } } var result = await _userManager.DeleteAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new InvalidOperationException($"خطای غیر منتظره در هنگام حذف کاربر با شناسه '{userId}'."); } //TODO: Delete Any Related Records in DB (if exists) //Delete User's Profile Image if (!user.ProfileImagePath.EndsWith("default.png")) _ifileManager.DeleteFile(user.ProfileImagePath); await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return Redirect("~/"); }
public ActionResult Edit(PermissionEditViewModel item) { var out_pg = CreateViewModel<PermissionEditViewModel>(); out_pg.Permission = item.Permission; string err_msg = string.Empty; bool IsSomethingToChange = false; var oldname = _userPermissionGroupRepository.FindById(item.Permission.Id).Name; if (ModelState.IsValid) { try { UpdateUserPermission(item.Permission.Id, item.Permission.Name, oldname); GroupUpdateUserPermission(item.Permission.Id, item.Permission.Name, oldname); UpdateNewOwnerName(item.Permission.Id, item.Permission.UserID); //_userPermissionGroupService.UpdateUserPermission(item.Permission.Id, item.Permission.Name); //_userPermissionGroupService.GroupUpdateUserPermission(item.Permission.Id, item.Permission.Name, oldname); } catch (Exception ex) { err_msg = ex.Message; ModelState.AddModelError("", err_msg); } if (_userPermissionGroupRepository.FindAll().Where(x => x.Name.Trim().Contains(item.Permission.Name.Trim())).Any()) { IsSomethingToChange = true; } } return Json(new { item = item.Permission, Change = IsSomethingToChange, IsSucceed = ModelState.IsValid, Msg = ModelState.IsValid ? ViewResources.SharedStrings.TimeZonesEditMessage : err_msg, DisplayMessage = !string.IsNullOrEmpty(err_msg), viewData = ModelState.IsValid ? null : this.RenderPartialView("Edit", out_pg) }); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync().ConfigureAwait(false); if (info == null) { throw new ApplicationException("Error loading external login information during confirmation."); } var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, EmailConfirmed = true }; var result = await _userManager.CreateAsync(user).ConfigureAwait(false); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info).ConfigureAwait(false); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false).ConfigureAwait(false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(LocalRedirect(Url.GetLocalUrl(returnUrl))); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ReturnUrl = returnUrl; return(Page()); }
public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); // add the email claim and value for this user //await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Input.Email)); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); }
public async Task<ActionResult> Login(LoginViewModel vm) { if (ModelState.IsValid) { var user = _userManager.Users.FirstOrDefault(s => s.UserName == vm.Username); if (user == null) { ModelState.AddModelError("", "User doesn't exist"); return View(vm); } var result = await _signInManager.PasswordSignInAsync(vm.Username, vm.Password, vm.RememberMe, false); if (result.Succeeded) { //save last login date var User = _userManager.Users.Where(c => c.UserName == vm.Username).FirstOrDefault(); user.LastLoginDateUtc = DateTime.UtcNow; await _userManager.UpdateAsync(User); var st = vm.ReturnUrl; if (st != null) return Redirect(vm.ReturnUrl); else return RedirectToAction("index", "Home"); } ModelState.AddModelError("", "Invalid Login attempt"); } return View(vm); }
public async Task <IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null) { if (!ModelState.IsValid) { return(Page()); } returnUrl = returnUrl ?? Url.Content("~/"); var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { throw new InvalidOperationException($"Unable to load two-factor authentication user."); } var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty); var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine); if (result.Succeeded) { _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id); return(LocalRedirect(returnUrl)); } else if (result.IsLockedOut) { _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id); return(RedirectToPage("./Lockout")); } else { _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id); ModelState.AddModelError(string.Empty, "Invalid authenticator code."); return(Page()); } }
public ActionResult Register(RegisterViewModel model) { ActionResult result = null; try { if (!ModelState.IsValid) { throw new Exception(); } try { User userModel = new User(); userModel.ConfirmPassword = model.ConfirmPassword; userModel.Password = model.Password; userModel.FirstName = model.FirstName; userModel.LastName = model.LastName; userModel.Username = model.Username; userModel.Email = model.Email; VendingMachine.RegisterUser(userModel); } catch (UserExistsException) { ModelState.AddModelError("invalid-user", "The username is already taken."); throw; } result = RedirectToAction("Index", "Vending"); } catch (Exception) { result = View("Register"); } return(result); }