public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { User user = await _userManager.FindUserByUsernameOrEmailAsync(request.UsernameOrEmail); if (await _userManager.IsEmailConfirmedAsync(user)) { throw new ValidationException(new[] { new ValidationFailure(nameof(request.UsernameOrEmail), "The email address is already confirmed") }); } var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var param = new Dictionary <string, string> { { "token", token }, { "email", user.Email } }; var uri = QueryHelpers.AddQueryString(request.ClientUri, param); var template = new ConfirmEmailTemplate { DisplayName = user.DisplayName, ArpaLogo = $"{_jwtConfiguration.Audience}/images/arpa_logo.png", ClientUri = uri, ClubAddress = _clubConfiguration.Address, ClubMail = _clubConfiguration.Email, ClubName = _clubConfiguration.Name, ClubPhoneNumber = _clubConfiguration.Phone }; await _emailSender.SendTemplatedEmailAsync(template, user.Email); return(Unit.Value); }
public void Should_Parse_Email_Template() { // Arrange TemplateParser templateParser = CreateTemplateParser(); ITemplate templateData = new ConfirmEmailTemplate(); // Act var result = templateParser.Parse(templateData); // Assert result.Should().NotBeNullOrEmpty(); result.Should().Contain("<title>"); result.Should().Contain("</title>"); }
public ConfirmEmailTemplate GetConfirmEmailChangingTemplate(MyProfileViewModel model, string callbackUrl) { string websiteName = generalFunction.GetAppSettingsValue("websiteName"); var link = "<a href='" + callbackUrl + "'>here</a>"; string body = "<p>Hi " + model.Username + ",<br /><br /> We have received a request to change your email address for your account in " + websiteName + ".</p><p>Please confirm your account by clicking <a href='" + callbackUrl + "'> here</a></p>" + "<p>If you did not do so, please ignore this email.</p>" + "<p><i>Do not reply to this email.</i></p><br /><br /><p>Regards,<br>" + websiteName + "</p>"; string subject = "Confirm Email for Changing Email Address of an Account in " + websiteName; ConfirmEmailTemplate confirmEmailTemplate = new ConfirmEmailTemplate(); confirmEmailTemplate.Subject = subject; confirmEmailTemplate.Body = body; return(confirmEmailTemplate); }
public ConfirmEmailTemplate GetConfirmEmailTemplate(RegisterViewModel model, string callbackUrl) { string websiteName = generalFunction.GetAppSettingsValue("websiteName"); var link = "<a href='" + callbackUrl + "'>here</a>"; string body = "<p>Hi " + model.Username + ",<br /><br /> Thanks for signing up an account in " + websiteName + ".</p><p>Please confirm your account by clicking <a href='" + callbackUrl + "'> here</a></p>" + "<p>If you did not do so, please ignore this email.</p>" + "<p><i>Do not reply to this email.</i></p><br /><br /><p>Regards,<br>" + websiteName + "</p>"; string subject = "Confirm email for sign up account in " + websiteName; ConfirmEmailTemplate confirmEmailTemplate = new ConfirmEmailTemplate(); confirmEmailTemplate.Subject = subject; confirmEmailTemplate.Body = body; return(confirmEmailTemplate); }
public async Task Should_Send_Templated_Email_With_Default_Subject_Async() { // Arrange EmailSender emailSender = CreateEmailSender(); var confirmEmailTemplate = new ConfirmEmailTemplate(); var expectedRecipient = "*****@*****.**"; var expectedSubject = _emailConfiguration.DefaultSubject; var expectedBody = "some body without title tags"; _templateParser.Parse(Arg.Any <ITemplate>()).Returns(expectedBody); // Act await emailSender.SendTemplatedEmailAsync(confirmEmailTemplate, expectedRecipient); // Assert _server.ReceivedEmailCount.Should().Be(1); SmtpMessage receivedMail = _server.ReceivedEmail.First(); receivedMail.MessageParts[0].BodyData.Should().Be(expectedBody); receivedMail.ToAddresses.First().Address.Should().Be(expectedRecipient); receivedMail.Headers.Get("Subject").Should().Be(expectedSubject); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (model != null) { bool usernameExist = db.AspNetUsers.Where(a => a.UserName == model.Username).Any(); bool emailExist = db.AspNetUsers.Where(a => a.Email == model.Email).Any(); if (usernameExist) { ModelState.AddModelError("UserName", "Username already taken. Please try again with other username."); } if (usernameExist) { ModelState.AddModelError("Email", "Email Address already taken. Please try again with other Email Address."); } } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Username, Email = model.Email, Name = model.Name, Gender = model.Gender }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); ConfirmEmailTemplate confirmEmailTemplate = GetConfirmEmailTemplate(model, callbackUrl); SendEmail(model.Email, confirmEmailTemplate.Subject, confirmEmailTemplate.Body); return(RedirectToAction("EmailSent", "Account")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task Should_Send_Templated_Email_Async() { // Arrange _server.ClearReceivedEmail(); EmailSender emailSender = CreateEmailSender(); var confirmEmailTemplate = new ConfirmEmailTemplate(); var expectedRecipient = "*****@*****.**"; var expectedSubject = "Expected subject"; var expectedBody = $"<title>{expectedSubject}</title>"; _templateParser.Parse(Arg.Any <ITemplate>()).Returns(expectedBody); // Act await emailSender.SendTemplatedEmailAsync(confirmEmailTemplate, expectedRecipient); // Assert _server.ReceivedEmailCount.Should().Be(1); SmtpMessage receivedMail = _server.ReceivedEmail.First(); receivedMail.MessageParts[0].BodyData.Should().Be(expectedBody); receivedMail.ToAddresses.First().Address.Should().Be(expectedRecipient); receivedMail.Headers.Get("Subject").Should().Be(expectedSubject); }
public async Task <ActionResult> EditProfile(MyProfileViewModel model, IEnumerable <HttpPostedFileBase> ProfilePicture) { if (model != null) { AspNetUsers aspNetUsers = db.AspNetUsers.Find(model.Id); string originalUsername = aspNetUsers.UserName; string originalEmail = aspNetUsers.Email; //check whether username n email exists bool usernameExist = db.AspNetUsers.Where(a => a.UserName == model.Username && a.UserName != originalUsername).Any(); bool emailExist = db.AspNetUsers.Where(a => a.Email == model.Email && a.Email != originalEmail).Any(); if (usernameExist) { ModelState.AddModelError("Username", "Username already exists. Please try with other username."); } if (emailExist) { ModelState.AddModelError("Email", "Email already exists. Please try with other email address."); } if (ModelState.IsValid) { try { string FileName = ""; aspNetUsers.UserName = model.Username; aspNetUsers.Email = model.Email; aspNetUsers.Name = model.Name; aspNetUsers.Gender = model.Gender; if (model.Email != originalEmail) { aspNetUsers.EmailConfirmed = false; //user has changed the email, set emailConfirmed to false, to allow user to confirm their email once again } if (ProfilePicture != null) { foreach (var file in ProfilePicture) { if (file != null) { // get the file name of the selected image file and save into images folder FileName = new FileInfo(file.FileName).Name; string serverFilePath = HttpContext.Server.MapPath("~/Images/") + FileName; file.SaveAs(serverFilePath); //remember to set 'write' permission on Images folder in the server aspNetUsers.ProfilePicturePath = serverFilePath; } } aspNetUsers.ProfilePicture = FileName; } db.Entry(aspNetUsers).State = EntityState.Modified; db.SaveChanges(); ModelState.Clear(); if (model.Email != originalEmail) { //send confirm account email string code = await UserManager.GenerateEmailConfirmationTokenAsync(aspNetUsers.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = aspNetUsers.Id, code = code }, protocol: Request.Url.Scheme); ConfirmEmailTemplate confirmEmailTemplate = GetConfirmEmailChangingTemplate(model, callbackUrl); SendEmail(model.Email, confirmEmailTemplate.Subject, confirmEmailTemplate.Body); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return(RedirectToAction("EmailSent", "Account")); } if (model.Username != originalUsername) { TempData["ProfileUpdateSuccess"] = "Profile updated successfully. Please login."; AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return(RedirectToAction("Login")); } else { TempData["ProfileUpdateSuccess"] = "Profile updated successfully."; return(RedirectToAction("MyProfile")); } } catch (Exception ex) { ModelState.AddModelError("Id", ex.InnerException.Message); } } } return(View(model)); }