PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/RealState-Site/Site/Areas/Customer/Controllers/AccountController.cs

https://gitlab.com/hebron80/sample-app
C# | 409 lines | 323 code | 38 blank | 48 comment | 40 complexity | 13f433ac35dfa948f0632c9dc57b2844 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using Microsoft.AspNet.Identity;
  9. using Microsoft.AspNet.Identity.EntityFramework;
  10. using Microsoft.Owin.Security;
  11. using Site.Areas.Customer.Models;
  12. namespace Site.Areas.Customer.Controllers
  13. {
  14. //[Authorize]
  15. public class AccountController : BaseController
  16. {
  17. //public AccountController()
  18. // : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
  19. //{
  20. //}
  21. //public AccountController(UserManager<ApplicationUser> userManager)
  22. //{
  23. // UserManager = userManager;
  24. //}
  25. //public UserManager<ApplicationUser> UserManager { get; private set; }
  26. //
  27. // GET: /Account/Login
  28. [AllowAnonymous]
  29. public ActionResult Login(string returnUrl)
  30. {
  31. ViewBag.ReturnUrl = returnUrl;
  32. return View();
  33. }
  34. //
  35. // POST: /Account/Login
  36. [HttpPost]
  37. [AllowAnonymous]
  38. [ValidateAntiForgeryToken]
  39. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  40. {
  41. if (ModelState.IsValid)
  42. {
  43. var user = await UserManager.FindAsync(model.UserName, model.Password);
  44. if (user != null)
  45. {
  46. await SignInAsync(user, model.RememberMe);
  47. return RedirectToLocal(returnUrl);
  48. }
  49. else
  50. {
  51. ModelState.AddModelError("", "Invalid username or password.");
  52. }
  53. }
  54. // If we got this far, something failed, redisplay form
  55. return View(model);
  56. }
  57. //
  58. // GET: /Account/Register
  59. [AllowAnonymous]
  60. public ActionResult Register()
  61. {
  62. return View();
  63. }
  64. //
  65. // POST: /Account/Register
  66. [HttpPost]
  67. [AllowAnonymous]
  68. [ValidateAntiForgeryToken]
  69. public async Task<ActionResult> Register(RegisterViewModel model)
  70. {
  71. if (ModelState.IsValid)
  72. {
  73. var user = new ApplicationUser() { UserName = model.UserName };
  74. var result = await UserManager.CreateAsync(user, model.Password);
  75. if (result.Succeeded)
  76. {
  77. await SignInAsync(user, isPersistent: false);
  78. return RedirectToAction("Index", "Home");
  79. }
  80. else
  81. {
  82. AddErrors(result);
  83. }
  84. }
  85. // If we got this far, something failed, redisplay form
  86. return View(model);
  87. }
  88. //
  89. // POST: /Account/Disassociate
  90. [HttpPost]
  91. [ValidateAntiForgeryToken]
  92. public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
  93. {
  94. ManageMessageId? message = null;
  95. IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
  96. if (result.Succeeded)
  97. {
  98. message = ManageMessageId.RemoveLoginSuccess;
  99. }
  100. else
  101. {
  102. message = ManageMessageId.Error;
  103. }
  104. return RedirectToAction("Manage", new { Message = message });
  105. }
  106. //
  107. // GET: /Account/Manage
  108. public ActionResult Manage(ManageMessageId? message)
  109. {
  110. ViewBag.StatusMessage =
  111. message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
  112. : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
  113. : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
  114. : message == ManageMessageId.Error ? "An error has occurred."
  115. : "";
  116. ViewBag.HasLocalPassword = HasPassword();
  117. ViewBag.ReturnUrl = Url.Action("Manage");
  118. return View();
  119. }
  120. //
  121. // POST: /Account/Manage
  122. [HttpPost]
  123. [ValidateAntiForgeryToken]
  124. public async Task<ActionResult> Manage(ManageUserViewModel model)
  125. {
  126. bool hasPassword = HasPassword();
  127. ViewBag.HasLocalPassword = hasPassword;
  128. ViewBag.ReturnUrl = Url.Action("Manage");
  129. if (hasPassword)
  130. {
  131. if (ModelState.IsValid)
  132. {
  133. IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
  134. if (result.Succeeded)
  135. {
  136. return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
  137. }
  138. else
  139. {
  140. AddErrors(result);
  141. }
  142. }
  143. }
  144. else
  145. {
  146. // User does not have a password so remove any validation errors caused by a missing OldPassword field
  147. ModelState state = ModelState["OldPassword"];
  148. if (state != null)
  149. {
  150. state.Errors.Clear();
  151. }
  152. if (ModelState.IsValid)
  153. {
  154. IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
  155. if (result.Succeeded)
  156. {
  157. return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
  158. }
  159. else
  160. {
  161. AddErrors(result);
  162. }
  163. }
  164. }
  165. // If we got this far, something failed, redisplay form
  166. return View(model);
  167. }
  168. //
  169. // POST: /Account/ExternalLogin
  170. [HttpPost]
  171. [AllowAnonymous]
  172. [ValidateAntiForgeryToken]
  173. public ActionResult ExternalLogin(string provider, string returnUrl)
  174. {
  175. // Request a redirect to the external login provider
  176. return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  177. }
  178. //
  179. // GET: /Account/ExternalLoginCallback
  180. [AllowAnonymous]
  181. public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  182. {
  183. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  184. if (loginInfo == null)
  185. {
  186. return RedirectToAction("Login");
  187. }
  188. // Sign in the user with this external login provider if the user already has a login
  189. var user = await UserManager.FindAsync(loginInfo.Login);
  190. if (user != null)
  191. {
  192. await SignInAsync(user, isPersistent: false);
  193. return RedirectToLocal(returnUrl);
  194. }
  195. else
  196. {
  197. // If the user does not have an account, then prompt the user to create an account
  198. ViewBag.ReturnUrl = returnUrl;
  199. ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  200. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = loginInfo.DefaultUserName });
  201. }
  202. }
  203. //
  204. // POST: /Account/LinkLogin
  205. [HttpPost]
  206. [ValidateAntiForgeryToken]
  207. public ActionResult LinkLogin(string provider)
  208. {
  209. // Request a redirect to the external login provider to link a login for the current user
  210. return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
  211. }
  212. //
  213. // GET: /Account/LinkLoginCallback
  214. public async Task<ActionResult> LinkLoginCallback()
  215. {
  216. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
  217. if (loginInfo == null)
  218. {
  219. return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
  220. }
  221. var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
  222. if (result.Succeeded)
  223. {
  224. return RedirectToAction("Manage");
  225. }
  226. return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
  227. }
  228. //
  229. // POST: /Account/ExternalLoginConfirmation
  230. [HttpPost]
  231. [AllowAnonymous]
  232. [ValidateAntiForgeryToken]
  233. public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  234. {
  235. if (User.Identity.IsAuthenticated)
  236. {
  237. return RedirectToAction("Manage");
  238. }
  239. if (ModelState.IsValid)
  240. {
  241. // Get the information about the user from the external login provider
  242. var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  243. if (info == null)
  244. {
  245. return View("ExternalLoginFailure");
  246. }
  247. var user = new ApplicationUser() { UserName = model.UserName };
  248. var result = await UserManager.CreateAsync(user);
  249. if (result.Succeeded)
  250. {
  251. result = await UserManager.AddLoginAsync(user.Id, info.Login);
  252. if (result.Succeeded)
  253. {
  254. await SignInAsync(user, isPersistent: false);
  255. return RedirectToLocal(returnUrl);
  256. }
  257. }
  258. AddErrors(result);
  259. }
  260. ViewBag.ReturnUrl = returnUrl;
  261. return View(model);
  262. }
  263. //
  264. // POST: /Account/LogOff
  265. [HttpPost]
  266. [ValidateAntiForgeryToken]
  267. public ActionResult LogOff()
  268. {
  269. AuthenticationManager.SignOut();
  270. return RedirectToAction("Index", "Home");
  271. }
  272. //
  273. // GET: /Account/ExternalLoginFailure
  274. [AllowAnonymous]
  275. public ActionResult ExternalLoginFailure()
  276. {
  277. return View();
  278. }
  279. [ChildActionOnly]
  280. public ActionResult RemoveAccountList()
  281. {
  282. var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
  283. ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
  284. return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
  285. }
  286. protected override void Dispose(bool disposing)
  287. {
  288. if (disposing && UserManager != null)
  289. {
  290. UserManager.Dispose();
  291. UserManager = null;
  292. }
  293. base.Dispose(disposing);
  294. }
  295. #region Helpers
  296. // Used for XSRF protection when adding external logins
  297. private const string XsrfKey = "XsrfId";
  298. private IAuthenticationManager AuthenticationManager
  299. {
  300. get
  301. {
  302. return HttpContext.GetOwinContext().Authentication;
  303. }
  304. }
  305. private async Task SignInAsync(ApplicationUser user, bool isPersistent)
  306. {
  307. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  308. var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
  309. AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
  310. }
  311. private void AddErrors(IdentityResult result)
  312. {
  313. foreach (var error in result.Errors)
  314. {
  315. ModelState.AddModelError("", error);
  316. }
  317. }
  318. private bool HasPassword()
  319. {
  320. var user = UserManager.FindById(User.Identity.GetUserId());
  321. if (user != null)
  322. {
  323. return user.PasswordHash != null;
  324. }
  325. return false;
  326. }
  327. public enum ManageMessageId
  328. {
  329. ChangePasswordSuccess,
  330. SetPasswordSuccess,
  331. RemoveLoginSuccess,
  332. Error
  333. }
  334. private ActionResult RedirectToLocal(string returnUrl)
  335. {
  336. if (Url.IsLocalUrl(returnUrl))
  337. {
  338. return Redirect(returnUrl);
  339. }
  340. else
  341. {
  342. return RedirectToAction("Index", "Home");
  343. }
  344. }
  345. private class ChallengeResult : HttpUnauthorizedResult
  346. {
  347. public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
  348. {
  349. }
  350. public ChallengeResult(string provider, string redirectUri, string userId)
  351. {
  352. LoginProvider = provider;
  353. RedirectUri = redirectUri;
  354. UserId = userId;
  355. }
  356. public string LoginProvider { get; set; }
  357. public string RedirectUri { get; set; }
  358. public string UserId { get; set; }
  359. public override void ExecuteResult(ControllerContext context)
  360. {
  361. var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
  362. if (UserId != null)
  363. {
  364. properties.Dictionary[XsrfKey] = UserId;
  365. }
  366. context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  367. }
  368. }
  369. #endregion
  370. }
  371. }