using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin.Security; using Sevomin.Models; using System; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Sevomin.WebFrontend.Controllers { public class AccountController : BaseController { public AccountController() : this(new UserManager(new UserStore(new UsersDbContext()))) { } public AccountController(UserManager userManager) { UserManager = userManager; } public UserManager UserManager { get; private set; } private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } [HttpPost] public async Task Signup(SignupViewModel model) { User user; if (model.IsAvalin) { user = new Avalin(model.Email, model.DisplayName); user.SignUpDate = DateTime.UtcNow; } else { int spaceIndex = model.DisplayName.IndexOf(' '); user = new Dovomin(model.Email, model.DisplayName.Substring(0, spaceIndex), model.DisplayName.Substring(spaceIndex + 1)); user.SignUpDate = DateTime.UtcNow; } var result = await UserManager.CreateAsync(user); if (result.Succeeded) { await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home"); } else { AddErrors(result); } return View(model); } public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] public async Task Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { var user = await UserManager.FindAsync(model.Username, model.Password); if (user != null) { await SignInAsync(user, model.RememberMe); return RedirectToLocal(returnUrl); } else { ModelState.AddModelError("", "Invalid username or password."); } } // If we got this far, something failed, redisplay form return View(model); } private async Task SignInAsync(User user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } } }