Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public partial class Startup
- {
- public void ConfigureAuth(IAppBuilder app)
- {
- app.UseCookieAuthentication(new CookieAuthenticationOptions
- {
- AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
- LoginPath = new PathString("/Account/Login"),
- SlidingExpiration = true,
- CookieSecure = CookieSecureOption.Never,
- ExpireTimeSpan = TimeSpan.FromMinutes(30)
- });
- AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
- }
- }
- public ActionResult Login(LoginViewModel model, string returnUrl)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- var isAuthenticated = false;
- using (var db = new DatabaseEntities())
- {
- var user = db.Users.FirstOrDefault(args => args.Username == model.Username);
- if (user == null)
- {
- ModelState.AddModelError("", "Username is not found");
- return View(model);
- }
- if (user.AuthenticationSource == 1)
- {
- isAuthenticated = LDAP.Authenticate(model.Username, model.Password);
- }
- else
- {
- if (user.Password == model.Password)
- {
- if (user.IsLoggedIn == false)
- isAuthenticated = true;
- else if (user.IsLoggedIn == true)
- {
- ModelState.AddModelError("", "This user is logged in");
- return View(model);
- }
- }
- }
- if (isAuthenticated)
- {
- var claims = new List<Claim>();
- claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Username));
- claims.Add(new Claim(ClaimTypes.Name, user.Username));
- claims.Add(new Claim("UserId", user.Id.ToString()));
- claims.Add(new Claim("DisplayName", user.DisplayName));
- var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
- AuthenticationManager.SignIn(identity);
- user.LastLoginDate = DateTime.UtcNow;
- user.IsLoggedIn = true;
- db.SaveChanges();
- return RedirectToAction("Index", "Home");
- }
- }
- ModelState.AddModelError("", "Username or Password is invalid");
- return View(model);
- }
- public ActionResult LogOff(string returnUrl)
- {
- using (var db = new DatabaseEntities())
- {
- var LoggedUsername = User.Identity.Name;
- var user = db.Users.FirstOrDefault(args => args.Username == LoggedUsername);
- user.IsLoggedIn = false;
- db.SaveChanges();
- }
- AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
- return RedirectToAction("Login");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement