Advertisement
Guest User

Untitled

a guest
Nov 1st, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. public partial class Startup
  2. {
  3. public void ConfigureAuth(IAppBuilder app)
  4. {
  5. app.UseCookieAuthentication(new CookieAuthenticationOptions
  6. {
  7. AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
  8. LoginPath = new PathString("/Account/Login"),
  9. SlidingExpiration = true,
  10. CookieSecure = CookieSecureOption.Never,
  11. ExpireTimeSpan = TimeSpan.FromMinutes(30)
  12. });
  13.  
  14. AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
  15. }
  16. }
  17.  
  18. public ActionResult Login(LoginViewModel model, string returnUrl)
  19. {
  20. if (!ModelState.IsValid)
  21. {
  22. return View(model);
  23. }
  24. var isAuthenticated = false;
  25.  
  26. using (var db = new DatabaseEntities())
  27. {
  28. var user = db.Users.FirstOrDefault(args => args.Username == model.Username);
  29. if (user == null)
  30. {
  31. ModelState.AddModelError("", "Username is not found");
  32. return View(model);
  33. }
  34.  
  35. if (user.AuthenticationSource == 1)
  36. {
  37. isAuthenticated = LDAP.Authenticate(model.Username, model.Password);
  38. }
  39. else
  40. {
  41. if (user.Password == model.Password)
  42. {
  43. if (user.IsLoggedIn == false)
  44. isAuthenticated = true;
  45. else if (user.IsLoggedIn == true)
  46. {
  47.  
  48. ModelState.AddModelError("", "This user is logged in");
  49. return View(model);
  50. }
  51. }
  52. }
  53.  
  54. if (isAuthenticated)
  55. {
  56. var claims = new List<Claim>();
  57.  
  58. claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Username));
  59. claims.Add(new Claim(ClaimTypes.Name, user.Username));
  60. claims.Add(new Claim("UserId", user.Id.ToString()));
  61. claims.Add(new Claim("DisplayName", user.DisplayName));
  62.  
  63. var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
  64. AuthenticationManager.SignIn(identity);
  65.  
  66. user.LastLoginDate = DateTime.UtcNow;
  67. user.IsLoggedIn = true;
  68.  
  69. db.SaveChanges();
  70.  
  71. return RedirectToAction("Index", "Home");
  72. }
  73.  
  74. }
  75. ModelState.AddModelError("", "Username or Password is invalid");
  76. return View(model);
  77.  
  78. }
  79.  
  80. public ActionResult LogOff(string returnUrl)
  81. {
  82. using (var db = new DatabaseEntities())
  83. {
  84. var LoggedUsername = User.Identity.Name;
  85. var user = db.Users.FirstOrDefault(args => args.Username == LoggedUsername);
  86. user.IsLoggedIn = false;
  87. db.SaveChanges();
  88. }
  89.  
  90. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
  91. return RedirectToAction("Login");
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement