PageRenderTime 38ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/MVCContent/Source/jQuery/Demo 1/Begin/MvcMusicStore/Controllers/AccountController.cs

https://bitbucket.org/bsatrom/presentations/
C# | 234 lines | 169 code | 39 blank | 26 comment | 10 complexity | 5a20124a1811876af4d509dd0b51c31b MD5 | raw file
Possible License(s): Apache-2.0, CC-BY-SA-3.0
  1. // ----------------------------------------------------------------------------------
  2. // Microsoft Developer & Platform Evangelism
  3. //
  4. // Copyright (c) Microsoft Corporation. All rights reserved.
  5. //
  6. // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  7. // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
  8. // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  9. // ----------------------------------------------------------------------------------
  10. // The example companies, organizations, products, domain names,
  11. // e-mail addresses, logos, people, places, and events depicted
  12. // herein are fictitious. No association with any real company,
  13. // organization, product, domain name, email address, logo, person,
  14. // places, or events is intended or should be inferred.
  15. // ----------------------------------------------------------------------------------
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Diagnostics.CodeAnalysis;
  19. using System.Linq;
  20. using System.Security.Principal;
  21. using System.Web;
  22. using System.Web.Mvc;
  23. using System.Web.Routing;
  24. using System.Web.Security;
  25. using MvcMusicStore.Models;
  26. namespace MvcMusicStore.Controllers
  27. {
  28. [HandleError]
  29. public class AccountController : Controller
  30. {
  31. // This constructor is used by the MVC framework to instantiate the controller using
  32. // the default forms authentication and membership providers.
  33. public AccountController()
  34. : this(null, null)
  35. {
  36. }
  37. // This constructor is not used by the MVC framework but is instead provided for ease
  38. // of unit testing this type. See the comments in AccountModels.cs for more information.
  39. public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService)
  40. {
  41. FormsService = formsService ?? new FormsAuthenticationService();
  42. MembershipService = membershipService ?? new AccountMembershipService();
  43. }
  44. public IFormsAuthenticationService FormsService
  45. {
  46. get;
  47. private set;
  48. }
  49. public IMembershipService MembershipService
  50. {
  51. get;
  52. private set;
  53. }
  54. protected override void Initialize(RequestContext requestContext)
  55. {
  56. if (requestContext.HttpContext.User.Identity is WindowsIdentity)
  57. {
  58. throw new InvalidOperationException("Windows authentication is not supported.");
  59. }
  60. else
  61. {
  62. base.Initialize(requestContext);
  63. }
  64. }
  65. protected override void OnActionExecuting(ActionExecutingContext filterContext)
  66. {
  67. ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
  68. base.OnActionExecuting(filterContext);
  69. }
  70. [Authorize]
  71. public ActionResult ChangePassword()
  72. {
  73. return View();
  74. }
  75. [Authorize]
  76. [HttpPost]
  77. public ActionResult ChangePassword(ChangePasswordModel model)
  78. {
  79. if (ModelState.IsValid)
  80. {
  81. if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
  82. {
  83. return RedirectToAction("ChangePasswordSuccess");
  84. }
  85. else
  86. {
  87. ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
  88. }
  89. }
  90. // If we got this far, something failed, redisplay form
  91. return View(model);
  92. }
  93. public ActionResult ChangePasswordSuccess()
  94. {
  95. return View();
  96. }
  97. public ActionResult LogOff()
  98. {
  99. FormsService.SignOut();
  100. return RedirectToAction("Index", "Home");
  101. }
  102. public ActionResult LogOn()
  103. {
  104. return View();
  105. }
  106. [HttpPost]
  107. [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
  108. Justification = "Needs to take same parameter type as Controller.Redirect()")]
  109. public ActionResult LogOn(LogOnModel model, string returnUrl)
  110. {
  111. if (ModelState.IsValid)
  112. {
  113. if (MembershipService.ValidateUser(model.UserName, model.Password))
  114. {
  115. MigrateShoppingCart(model.UserName);
  116. FormsService.SignIn(model.UserName, model.RememberMe);
  117. if (!String.IsNullOrEmpty(returnUrl))
  118. {
  119. return Redirect(returnUrl);
  120. }
  121. else
  122. {
  123. return RedirectToAction("Index", "Home");
  124. }
  125. }
  126. else
  127. {
  128. ModelState.AddModelError("", "The user name or password provided is incorrect.");
  129. }
  130. }
  131. // If we got this far, something failed, redisplay form
  132. return View(model);
  133. }
  134. private void MigrateShoppingCart(string UserName)
  135. {
  136. // Associate shopping cart items with logged-in user
  137. var cart = ShoppingCart.GetCart(this.HttpContext);
  138. cart.MigrateCart(UserName);
  139. Session[ShoppingCart.CartSessionKey] = UserName;
  140. }
  141. public ActionResult Register()
  142. {
  143. return View();
  144. }
  145. [HttpPost]
  146. public ActionResult Register(RegisterModel model)
  147. {
  148. if (ModelState.IsValid)
  149. {
  150. // Attempt to register the user
  151. MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
  152. if (createStatus == MembershipCreateStatus.Success)
  153. {
  154. MigrateShoppingCart(model.UserName);
  155. FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
  156. return RedirectToAction("Index", "Home");
  157. }
  158. else
  159. {
  160. ModelState.AddModelError("", ErrorCodeToString(createStatus));
  161. }
  162. }
  163. // If we got this far, something failed, redisplay form
  164. return View(model);
  165. }
  166. private static string ErrorCodeToString(MembershipCreateStatus createStatus)
  167. {
  168. // See http://go.microsoft.com/fwlink/?LinkID=177550 for
  169. // a full list of status codes.
  170. switch (createStatus)
  171. {
  172. case MembershipCreateStatus.DuplicateUserName:
  173. return "Username already exists. Please enter a different user name.";
  174. case MembershipCreateStatus.DuplicateEmail:
  175. return "A username for that e-mail address already exists. Please enter a different e-mail address.";
  176. case MembershipCreateStatus.InvalidPassword:
  177. return "The password provided is invalid. Please enter a valid password value.";
  178. case MembershipCreateStatus.InvalidEmail:
  179. return "The e-mail address provided is invalid. Please check the value and try again.";
  180. case MembershipCreateStatus.InvalidAnswer:
  181. return "The password retrieval answer provided is invalid. Please check the value and try again.";
  182. case MembershipCreateStatus.InvalidQuestion:
  183. return "The password retrieval question provided is invalid. Please check the value and try again.";
  184. case MembershipCreateStatus.InvalidUserName:
  185. return "The user name provided is invalid. Please check the value and try again.";
  186. case MembershipCreateStatus.ProviderError:
  187. return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
  188. case MembershipCreateStatus.UserRejected:
  189. return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
  190. default:
  191. return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
  192. }
  193. }
  194. }
  195. }