Advertisement
Guest User

Untitled

a guest
Jun 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. [HttpPost]
  2.         [ValidateAntiForgeryToken]
  3.         public async Task<IActionResult> Login(LoginViewModel loginViewModel)
  4.         {
  5.             if (!ModelState.IsValid)
  6.                 return View(loginViewModel);
  7.  
  8.             var user = await _userManager.FindByNameAsync(loginViewModel.UserName);
  9.  
  10.             if (user == null)
  11.             {
  12.                 ModelState.AddModelError(string.Empty, "The username does not exist.");
  13.                 return View(loginViewModel);
  14.             }
  15.  
  16.             var role = await _userManager.IsInRoleAsync(user, Roles.Admin);
  17.  
  18.             if (!role)
  19.             {
  20.                 ModelState.AddModelError(string.Empty, "You have no permission.");
  21.                 return View(loginViewModel);
  22.             }
  23.  
  24.             var result = await _signInManager.PasswordSignInAsync(loginViewModel.UserName,
  25.                 loginViewModel.Password, true , lockoutOnFailure: false);
  26.  
  27.             if (result.Succeeded)
  28.             {
  29.                 var claims = new[] {
  30.                     new Claim(ClaimTypes.Role, Roles.Admin)
  31.                 };
  32.  
  33.                 var principal = new ClaimsPrincipal(
  34.                     new ClaimsIdentity(claims, CookieAuthenticationOptionsConstants.AuthenticationScheme));
  35.  
  36.                 await HttpContext.Authentication.SignInAsync(CookieAuthenticationOptionsConstants.AuthenticationScheme,
  37.                     principal,
  38.                     new AuthenticationProperties { IsPersistent = true });
  39.  
  40.                 return Redirect(loginViewModel.RedirectUrl);
  41.             }
  42.  
  43.             if (result.IsLockedOut)
  44.             {
  45.                 return this.RedirectToHome();
  46.             }
  47.             else
  48.             {
  49.                 ModelState.AddModelError(string.Empty, "The username/password couple is invalid.");
  50.                 return View(loginViewModel);
  51.             }
  52.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement