using System.Linq; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.Rendering; using MusicStore.Models; using System.Security.Claims; namespace MusicStore.Controllers { [Authorize] public class AccountController : Controller { public AccountController(UserManager userManager, SignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public UserManager UserManager { get; private set; } public SignInManager SignInManager { get; private set; } // // GET: /Account/Login [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task Login(LoginViewModel model, string returnUrl = null) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var signInStatus = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false, cancellationToken: Context.RequestAborted); switch (signInStatus) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task VerifyCode(string provider, bool rememberMe, string returnUrl = null) { var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(cancellationToken: Context.RequestAborted); if (user == null) { return View("Error"); } // Remove before production #if DEMO if (user != null) { ViewBag.Code = await UserManager.GenerateTwoFactorTokenAsync(user, provider, cancellationToken: Context.RequestAborted); } #endif return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser, cancellationToken: Context.RequestAborted); switch (result) { case SignInStatus.Success: return RedirectToLocal(model.ReturnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid code."); return View(model); } } // // GET: /Account/Register [AllowAnonymous] public IActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password, cancellationToken: Context.RequestAborted); if (result.Succeeded) { //Bug: Remember browser option missing? //Uncomment this and comment the later part if account verification is not needed. //await SignInManager.SignInAsync(user, isPersistent: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user, cancellationToken: Context.RequestAborted); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme); await UserManager.SendEmailAsync(user, "Confirm your account", "Please confirm your account by clicking here", cancellationToken: Context.RequestAborted); #if !DEMO return RedirectToAction("Index", "Home"); #else //To display the email link in a friendly page instead of sending email ViewBag.Link = callbackUrl; return View("DemoLinkDisplay"); #endif } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await SignInManager.UserManager.FindByIdAsync(userId, cancellationToken: Context.RequestAborted); if (user == null) { return View("Error"); } var result = await UserManager.ConfirmEmailAsync(user, code, cancellationToken: Context.RequestAborted); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [AllowAnonymous] public ActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email, cancellationToken: Context.RequestAborted); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user, cancellationToken: Context.RequestAborted))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GeneratePasswordResetTokenAsync(user, cancellationToken: Context.RequestAborted); var callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: Context.Request.Scheme); await UserManager.SendEmailAsync(user, "Reset Password", "Please reset your password by clicking here", cancellationToken: Context.RequestAborted); #if !DEMO return RedirectToAction("ForgotPasswordConfirmation"); #else //To display the email link in a friendly page instead of sending email ViewBag.Link = callbackUrl; return View("DemoLinkDisplay"); #endif } ModelState.AddModelError("", string.Format("We could not locate an account with email : {0}", model.Email)); // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { //TODO: Fix this? var resetPasswordViewModel = new ResetPasswordViewModel() { Code = code }; return code == null ? View("Error") : View(resetPasswordViewModel); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.Email, cancellationToken: Context.RequestAborted); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user, model.Code, model.Password, cancellationToken: Context.RequestAborted); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return View(); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } // // GET: /Account/SendCode [AllowAnonymous] public async Task SendCode(bool rememberMe, string returnUrl = null) { //TODO : Default rememberMe as well? var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(cancellationToken: Context.RequestAborted); if (user == null) { return View("Error"); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } // Generate the token and send it if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider, cancellationToken: Context.RequestAborted)) { return View("Error"); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task ExternalLoginCallback(string returnUrl = null) { //https://github.com/aspnet/Identity/issues/216 var loginInfo = await SignInManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent: false, cancellationToken: Context.RequestAborted); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.LoginProvider; // REVIEW: handle case where email not in claims? var email = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider //https://github.com/aspnet/Identity/issues/216 var info = await SignInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, cancellationToken: Context.RequestAborted); #if TESTING //Just for automated testing adding a claim named 'ManageStore' - Not required for production var manageClaim = info.ExternalIdentity.Claims.Where(c => c.Type == "ManageStore").FirstOrDefault(); if (manageClaim != null) { await UserManager.AddClaimAsync(user, manageClaim, cancellationToken: Context.RequestAborted); } #endif if (result.Succeeded) { result = await UserManager.AddLoginAsync(user, info, cancellationToken: Context.RequestAborted); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, cancellationToken: Context.RequestAborted); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public IActionResult LogOff() { SignInManager.SignOut(); return RedirectToAction("Index", "Home"); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private async Task GetCurrentUserAsync() { return await UserManager.FindByIdAsync(Context.User.Identity.GetUserId(), cancellationToken: Context.RequestAborted); } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } #endregion } }