Guest User

Untitled

a guest
Dec 18th, 2017
594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.95 KB | None | 0 0
  1. // get user object from the storage
  2. var user = await userManager.FindByIdAsync(userId);
  3.  
  4. // change username and email
  5. user.Username = "NewUsername";
  6. user.Email = "New@email.com";
  7.  
  8. // Persiste the changes
  9. await userManager.UpdateAsync(user);
  10.  
  11. // generage email confirmation code
  12. var emailConfirmationCode = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
  13.  
  14. // generate url for page where you can confirm the email
  15. var callbackurl= "http://example.com/ConfirmEmail";
  16.  
  17. // append userId and confirmation code as parameters to the url
  18. callbackurl += String.Format("?userId={0}&code={1}", user.Id, HttpUtility.UrlEncode(emailConfirmationCode));
  19.  
  20. var htmlContent = String.Format(
  21. @"Thank you for updating your email. Please confirm the email by clicking this link:
  22. <br><a href='{0}'>Confirm new email</a>",
  23. callbackurl);
  24.  
  25. // send email to the user with the confirmation link
  26. await userManager.SendEmailAsync(user.Id, subject: "Email confirmation", body: htmlContent);
  27.  
  28.  
  29.  
  30. // then this is the action to confirm the email on the user
  31. // link in the email should be pointing here
  32. public async Task<ActionResult> ConfirmEmail(string userId, string code)
  33. {
  34. var confirmResult = await userManager.ConfirmEmailAsync(userId, code);
  35.  
  36. return RedirectToAction("Index");
  37. }
  38.  
  39. public class ApplicationUser : IdentityUser
  40. {
  41. public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
  42. {
  43. // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
  44. var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
  45. // Add custom user claims here
  46. return userIdentity;
  47. }
  48.  
  49. [MaxLength(256)]
  50. public string UnConfirmedEmail { get; set; }//this is what we add
  51.  
  52. }
  53.  
  54. //
  55. // POST: /Account/Login
  56. [HttpPost]
  57. [AllowAnonymous]
  58. [ValidateAntiForgeryToken]
  59. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  60. {
  61. if (!ModelState.IsValid)
  62. {
  63. return View(model);
  64. }
  65.  
  66. var allowPassOnEmailVerfication = false;
  67. var user = await UserManager.FindByEmailAsync(model.Email);
  68. if (user != null)
  69. {
  70. if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail))
  71. {
  72. allowPassOnEmailVerfication = true;
  73. }
  74. }
  75.  
  76.  
  77. // This now counts login failures towards account lockout
  78. // To enable password failures to trigger account lockout, I changed to shouldLockout: true
  79. var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
  80. switch (result)
  81. {
  82. case SignInStatus.Success:
  83. return RedirectToLocal(returnUrl);
  84. case SignInStatus.LockedOut:
  85. return View("Lockout");
  86. case SignInStatus.RequiresVerification:
  87. return allowPassOnEmailVerfication ? RedirectToLocal(returnUrl) : RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  88. case SignInStatus.Failure:
  89. default:
  90. ModelState.AddModelError("", "Invalid login attempt.");
  91. return View(model);
  92. }
  93. }
  94.  
  95. public class IndexViewModel
  96. {
  97. public bool HasPassword { get; set; }
  98. public IList<UserLoginInfo> Logins { get; set; }
  99. public string PhoneNumber { get; set; }
  100. public bool TwoFactor { get; set; }
  101. public bool BrowserRemembered { get; set; }
  102.  
  103. public string ConfirmedEmail { get; set; } //add this
  104. public string UnConfirmedEmail { get; set; } //and this
  105. }
  106.  
  107. var userId = User.Identity.GetUserId();
  108. var currentUser = await UserManager.FindByIdAsync(userId);
  109.  
  110. var unConfirmedEmail = "";
  111. if (!String.IsNullOrWhiteSpace(currentUser.UnConfirmedEmail))
  112. {
  113. unConfirmedEmail = currentUser.UnConfirmedEmail;
  114. }
  115. var model = new IndexViewModel
  116. {
  117. HasPassword = HasPassword(),
  118. PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
  119. TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
  120. Logins = await UserManager.GetLoginsAsync(userId),
  121. BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
  122. ConfirmedEmail = currentUser.Email,
  123. UnConfirmedEmail = unConfirmedEmail
  124. };
  125.  
  126. <dt>Email:</dt>
  127. <dd>
  128. @Model.ConfirmedEmail
  129. @if (!String.IsNullOrWhiteSpace(Model.UnConfirmedEmail))
  130. {
  131. <em> - Unconfirmed: @Model.UnConfirmedEmail </em> @Html.ActionLink("Cancel", "CancelUnconfirmedEmail",new {email=Model.ConfirmedEmail})
  132. }
  133. else
  134. {
  135. @Html.ActionLink("Change Email", "ChangeEmail")
  136. }
  137. </dd>
  138.  
  139. public class ChangeEmailViewModel
  140. {
  141. public string ConfirmedEmail { get; set; }
  142. [Required]
  143. [EmailAddress]
  144. [Display(Name = "Email")]
  145. [DataType(DataType.EmailAddress)]
  146. public string UnConfirmedEmail { get; set; }
  147. }
  148.  
  149. public ActionResult ChangeEmail()
  150. {
  151. var user = UserManager.FindById(User.Identity.GetUserId());
  152. var model = new ChangeEmailViewModel()
  153. {
  154. ConfirmedEmail = user.Email
  155. };
  156.  
  157. return View(model);
  158. }
  159.  
  160. @model ProjectName.Models.ChangeEmailViewModel
  161. @{
  162. ViewBag.Title = "Change Email";
  163. }
  164.  
  165. <h2>@ViewBag.Title.</h2>
  166.  
  167. @using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
  168. {
  169. @Html.AntiForgeryToken()
  170. <h4>New Email Address:</h4>
  171. <hr />
  172. @Html.ValidationSummary("", new { @class = "text-danger" })
  173. @Html.HiddenFor(m=>m.ConfirmedEmail)
  174. <div class="form-group">
  175. @Html.LabelFor(m => m.UnConfirmedEmail, new { @class = "col-md-2 control-label" })
  176. <div class="col-md-10">
  177. @Html.TextBoxFor(m => m.UnConfirmedEmail, new { @class = "form-control" })
  178. </div>
  179. </div>
  180. <div class="form-group">
  181. <div class="col-md-offset-2 col-md-10">
  182. <input type="submit" class="btn btn-default" value="Email Link" />
  183. </div>
  184. </div>
  185. }
  186.  
  187. [HttpPost]
  188. public async Task<ActionResult> ChangeEmail(ChangeEmailViewModel model)
  189. {
  190. if (!ModelState.IsValid)
  191. {
  192. return RedirectToAction("ChangeEmail", "Manage");
  193. }
  194.  
  195. var user = await UserManager.FindByEmailAsync(model.ConfirmedEmail);
  196. var userId = user.Id;
  197. if (user != null)
  198. {
  199. //doing a quick swap so we can send the appropriate confirmation email
  200. user.UnConfirmedEmail = user.Email;
  201. user.Email = model.UnConfirmedEmail;
  202. user.EmailConfirmed = false;
  203. var result = await UserManager.UpdateAsync(user);
  204.  
  205. if (result.Succeeded)
  206. {
  207.  
  208. string callbackUrl =
  209. await SendEmailConfirmationTokenAsync(userId, "Confirm your new email");
  210.  
  211. var tempUnconfirmed = user.Email;
  212. user.Email = user.UnConfirmedEmail;
  213. user.UnConfirmedEmail = tempUnconfirmed;
  214. result = await UserManager.UpdateAsync(user);
  215.  
  216. callbackUrl = await SendEmailConfirmationWarningAsync(userId, "You email has been updated to: "+user.UnConfirmedEmail);
  217.  
  218.  
  219. }
  220. }
  221. return RedirectToAction("Index","Manage");
  222. }
  223.  
  224. private async Task<string> SendEmailConfirmationWarningAsync(string userID, string subject)
  225. {
  226. string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
  227. var callbackUrl = Url.Action("ConfirmEmail", "Account",
  228. new { userId = userID, code = code }, protocol: Request.Url.Scheme);
  229. await UserManager.SendEmailAsync(userID, subject,
  230. "Please confirm your account by clicking <a href="" + callbackUrl + "">here</a>");
  231.  
  232. return callbackUrl;
  233. }
  234.  
  235. public async Task<ActionResult> CancelUnconfirmedEmail(string emailOrUserId)
  236. {
  237. var user = await UserManager.FindByEmailAsync(emailOrUserId);
  238. if (user == null)
  239. {
  240. user = await UserManager.FindByIdAsync(emailOrUserId);
  241. if (user != null)
  242. {
  243. user.UnConfirmedEmail = "";
  244. user.EmailConfirmed = true;
  245. var result = await UserManager.UpdateAsync(user);
  246. }
  247. }
  248. else
  249. {
  250. user.UnConfirmedEmail = "";
  251. user.EmailConfirmed = true;
  252. var result = await UserManager.UpdateAsync(user);
  253. }
  254. return RedirectToAction("Index", "Manage");
  255.  
  256. }
  257.  
  258. var result = UserManager.ConfirmEmail(userId, code);
  259. if (result.Succeeded)
  260. {
  261.  
  262. var user = UserManager.FindById(userId);
  263. if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail))
  264. {
  265. user.Email = user.UnConfirmedEmail;
  266. user.UserName = user.UnConfirmedEmail;
  267. user.UnConfirmedEmail = "";
  268.  
  269. UserManager.Update(user);
  270. }
  271. }
Add Comment
Please, Sign In to add comment