public async Task <IActionResult> Login(LoginViewModel login, string returnUrl = null) { if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var userStatus = await _userManager.FindByNameAsync(login.Username); if (userStatus != null && userStatus.Status == Status.InActive) { ViewData["ReturnUrl"] = "/login.html"; ModelState.AddModelError(string.Empty, "Your account is not verified. Plese confirm your email."); return(View()); } var result = await _signInManager.PasswordSignInAsync(login.Username, login.Password, login.RememberMe, lockoutOnFailure : true); if (result.Succeeded && userStatus.Status == Status.Active) { string page = "https://ident.me/";//"https://ip.seeip.org/" using (HttpClient client = new HttpClient()) { var response = await client.GetAsync(page); if (response != null) { var content = response.Content.ReadAsStringAsync(); var userActivity = new AppUserActivityViewModel(); userActivity.IPAddress = content.Result.Trim(); var userAgent = Request.Headers["User-Agent"]; userActivity.Device = DetectDeviceExtension.GetDeviceType(userAgent); userActivity.UserId = userStatus.Id; userActivity.LastSession = DateTime.Now; userActivity.Username = userStatus.UserName; _userService.AddActivity(userActivity); _userService.Save(); } } if (returnUrl == null || returnUrl.Contains("login") || returnUrl.Contains("ResetPasswordConfirmation") || returnUrl.Contains("ConfirmEmail")) { return(RedirectToAction(nameof(HomeController.Index), "Home")); } // Convert returnUrl if (!Url.IsLocalUrl(returnUrl)) { var redundantPath = $"{Request.Scheme}://{Request.Host}"; var returnPath = returnUrl.Substring(redundantPath.Length); returnUrl = returnPath; } return(LocalRedirect(returnUrl)); } if (result.IsLockedOut) { var endTime = await _userManager.GetLockoutEndDateAsync(userStatus); return(View("LockoutAccount", endTime)); } else { ViewData["ReturnUrl"] = "/login.html"; if (userStatus != null) { ModelState.AddModelError(string.Empty, $"Invalid login credentials. Attempts remain: {5 - userStatus.AccessFailedCount}"); return(View()); } ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View()); } } // If we got this far, something failed, redisplay form return(View()); }
// User activity public void AddActivity(AppUserActivityViewModel userActivityVm) { var userActivity = Mapper.Map <AppUserActivityViewModel, AppUserActivity>(userActivityVm); _appUserActivityRepository.Add(userActivity); }