Exemplo n.º 1
0
        // De-serialises EMAIL from json file, splitting file based on
        // de-limiter to seperate objects
        public bool FromJsonEMAIL()
        {
            try
            {
                JsonSerializer serializer = new JsonSerializer();

                using (FileStream s = File.Open(_emailFilePath, FileMode.Open))
                    using (StreamReader sr = new StreamReader(s))
                        using (JsonReader reader = new JsonTextReader(sr))
                        {
                            while (reader.Read())
                            {
                                // deserialize only when there's "{" character in the stream
                                if (reader.TokenType == JsonToken.StartObject)
                                {
                                    var o = serializer.Deserialize <Email>(reader);

                                    EmailMessages.Add(o);
                                }
                            }
                        }

                return(true);
            }
            catch (Exception ex)
            {
                ErrorCode = ex.ToString();
                return(false);
            }
        }
        public async Task <SendAddSerialEmailResponse> Handle(SendAddSerialEmailRequest request,
                                                              CancellationToken cancellationToken)
        {
            var user = await userService.GetUserWithSerials(httpContextReader.CurrentUserId);

            if (!(await userService.GetUserWithSerials(httpContextReader.CurrentUserId)).HasEmptySerialSlot())
            {
                throw new PremiumOperationException("Account has no more serial slots");
            }

            if (await serialService.SerialExists(request.Serial, httpContextReader.CurrentUserId))
            {
                throw new DuplicateException("Serial already exists");
            }

            var result = await userTokenGenerator.GenerateAddSerialToken();

            var(encryptedSerial, encryptedEmail, encryptedToken) = (cryptoService.Encrypt(request.Serial),
                                                                    cryptoService.Encrypt(result.Email),
                                                                    cryptoService.Encrypt(result.Token));

            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}api/account/serial/add?email={encryptedEmail}&token={encryptedToken}&serial={encryptedSerial}";

            var emailTemplate =
                (await emailTemplateGenerator.FindEmailTemplate(EmailTemplateDictionary.RegisterTemplate))
                .ReplaceParameters(new EmailTemplateParameter("{{username}}", result.Username),
                                   new EmailTemplateParameter("{{callbackUrl}}", callbackUrl));

            await emailSender.Send(EmailMessages.ActivationAccountEmail(result.Email, emailTemplate));

            return(new SendAddSerialEmailResponse());
        }
Exemplo n.º 3
0
        public async Task <SendChangeEmailEmailResponse> Handle(SendChangeEmailEmailRequest request,
                                                                CancellationToken cancellationToken)
        {
            if (await authValidationService.EmailExists(request.NewEmail))
            {
                throw new DuplicateException("Account with this email already exists");
            }

            var result = await userTokenGenerator.GenerateChangeEmailToken();

            var(encryptedToken, encryptedEmail, encryptedNewEmail) =
                (cryptoService.Encrypt(result.Token), cryptoService.Encrypt(result.Email),
                 cryptoService.Encrypt(request.NewEmail));

            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}api/account/changeEmail?email={encryptedEmail}&token={encryptedToken}&newEmail={encryptedNewEmail}";

            var emailTemplate =
                (await emailTemplateGenerator.FindEmailTemplate(EmailTemplateDictionary.RegisterTemplate))
                .ReplaceParameters(new EmailTemplateParameter("{{username}}", result.Username),
                                   new EmailTemplateParameter("{{callbackUrl}}", callbackUrl));

            await emailSender.Send(EmailMessages.ActivationAccountEmail(result.Email, emailTemplate));

            return(new SendChangeEmailEmailResponse());
        }
Exemplo n.º 4
0
        public async Task <SignUpResponse> Handle(SignUpRequest request, CancellationToken cancellationToken)
        {
            if (await authValidationService.EmailExists(request.Email))
            {
                throw new DuplicateException("Email address already exists", ErrorCodes.EmailExists);
            }

            if (await authValidationService.UsernameExists(request.Username))
            {
                throw new DuplicateException("Username already exists", ErrorCodes.UsernameExists);
            }

            var user = await identityService.SignUp(request.Email, request.Username, request.Password);

            if (user != null)
            {
                await balanceService.CreateBalanceAccount(user.Id);

                var confirmAccountToken = await identityService.GenerateConfirmAccountToken(user);

                string callbackUrl = $"{Configuration.GetValue<string>(AppSettingsKeys.ClientAddress)}register/confirm?email={user.Email}&token={confirmAccountToken}";

                return(await emailSender.Send(EmailMessages.ActivationAccountEmail(user.Email, user.UserName, callbackUrl))
                    ? new SignUpResponse
                {
                    Token = confirmAccountToken, User = mapper.Map <UserAuthDto>(user)
                }

                    : throw new ServiceException("Account confirmation email sending failed"));
            }

            throw new AuthException("Error occurred during signing up");
        }
Exemplo n.º 5
0
        public async Task <RegisterResponse> Handle(RegisterRequest request, CancellationToken cancellationToken)
        {
            if (await authValidationService.EmailExists(request.Email))
            {
                throw new DuplicateException("Email already exists", ErrorCodes.EmailExists);
            }

            if (await authValidationService.UsernameExists(request.Username))
            {
                throw new DuplicateException("Username already exists", ErrorCodes.UsernameExists);
            }

            var signUpResult = await authService.SignUp(request.Email, request.Password, request.Username);

            if (signUpResult != null)
            {
                var registerToken = signUpResult.User?.Tokens.SingleOrDefault(t => t.Code == signUpResult.Token) ??
                                    throw new TokenException("Register token was not created",
                                                             ErrorCodes.CannotGenerateToken);

                return(await emailSender.Send(EmailMessages.ActivationAccountEmail(signUpResult.User?.Email,
                                                                                   signUpResult.User?.Username,
                                                                                   $"{Configuration.GetValue<string>(AppSettingsKeys.ClientAddress)}account/confirm?userId={signUpResult.User?.Id}&token={registerToken.Code}"))
                    ? new RegisterResponse()
                    : throw new ServiceException("Some error occurred during sending an email message",
                                                 ErrorCodes.SendEmailFailed));
            }

            throw new AuthException("Error occurred during signing up");
        }
        public async Task <SendActivationEmailResponse> Handle(SendActivationEmailRequest request,
                                                               CancellationToken cancellationToken)
        {
            var result = await authService.GenerateActivationEmailToken(request.Email);

            if (result == null)
            {
                return(new SendActivationEmailResponse());
            }

            var(encryptedToken, encryptedEmail) =
                (cryptoService.Encrypt(result.Token), cryptoService.Encrypt(result.Email));

            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}api/auth/confirm?email={encryptedEmail}&token={encryptedToken}";

            var emailTemplate =
                (await emailTemplateGenerator.FindEmailTemplate(EmailTemplateDictionary.RegisterTemplate))
                .ReplaceParameters(new EmailTemplateParameter("{{username}}", result.Username),
                                   new EmailTemplateParameter("{{callbackUrl}}", callbackUrl));

            return(await emailSender.Send(EmailMessages.ActivationAccountEmail(result.Email, emailTemplate))
                ? new SendActivationEmailResponse
            {
                Token = encryptedToken, Email = result.Email
            }

                : new SendActivationEmailResponse());
        }
Exemplo n.º 7
0
        public async Task <User> Register(string email, string username, string password)
        {
            var user = User.Create(email, username);

            if (await EmailExists(email))
            {
                Alertify.Push("Email address already exists", AlertType.Error);
                return(null);
            }

            if (await UsernameExists(username))
            {
                Alertify.Push("Username already exists", AlertType.Error);
                return(null);
            }

            if ((await userManager.CreateAsync(user, password)).Succeeded)
            {
                await rolesService.AdmitRole(RoleName.User, user);

                var confirmAccountToken = await userManager.GenerateEmailConfirmationTokenAsync(user);

                confirmAccountToken = cryptoService.Encrypt(confirmAccountToken);

                string callbackUrl =
                    $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}/Auth/ConfirmAccount?email={user.Email}&token={confirmAccountToken}";

                await emailSender.Send(EmailMessages.ActivationAccountEmail(email, callbackUrl));

                return(user);
            }

            Alertify.Push("Creating account failed", AlertType.Error);
            return(null);
        }
Exemplo n.º 8
0
        public async Task <SendResetPasswordResponse> Handle(SendResetPasswordRequest request,
                                                             CancellationToken cancellationToken)
        {
            if (!await captchaService.VerifyCaptcha(request.CaptchaResponse))
            {
                throw new CaptchaException();
            }

            var result = await userTokenGenerator.GenerateResetPasswordToken(request.Login);

            if (result == null)
            {
                return(new SendResetPasswordResponse());
            }

            var(encryptedToken, encryptedEmail) =
                (cryptoService.Encrypt(result.Token), cryptoService.Encrypt(result.Email));

            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}api/auth/resetPassword/verify?email={encryptedEmail}&token={encryptedToken}";

            var emailTemplate =
                (await emailTemplateGenerator.FindEmailTemplate(EmailTemplateDictionary.RegisterTemplate))
                .ReplaceParameters(new EmailTemplateParameter("{{username}}", result.Username),
                                   new EmailTemplateParameter("{{callbackUrl}}", callbackUrl));

            await emailSender.Send(EmailMessages.ActivationAccountEmail(result.Email, emailTemplate));

            return(new SendResetPasswordResponse());
        }
Exemplo n.º 9
0
        public void EmailMessages_DecodeBodyText_VariousFormats()
        {
            List <Tuple <string, bool, string> > listTestSubjects = new List <Tuple <string, bool, string> >()
            {
                //Raw,Expected
                //Godaddy with =3D typed in the email
                new Tuple <string, bool, string>(@"<html><body><span style=3D""font-family:Verdana; color:#000000; font-size:10pt;""><div><span style=3D"""">test =3D3D more text =3D</span></div></span></body></html>"
                                                 , false, @"<html><body><span style=""font-family:Verdana; color:#000000; font-size:10pt;""><div><span style="""">test =3D more text =</span></div></span></body></html>"),
                //Godaddy with various non-ascii characters.
                new Tuple <string, bool, string>(@"<html><body><span style=3D""font-family:Verdana; color:#000000; font-size:10pt;""><div class=3D""gs"" style=3D""""><div class=3D"""" style=3D""""><div id=3D"":n1"" class=3D""ii gt"" style=3D""""><div id=3D"":n0"" class=3D""a3s aXjCH "" style=3D""""><div dir=3D""ltr"" style=3D"""">chuck nu=C2=A4 =C3=82 =C3=80 =C2=A2<div class=3D""yj6qo"" style=3D""""></div><div class=3D""adL"" style=3D""""><br style=3D""""></div></div><div class=3D""adL"" style=3D""""></div></div></div><div class=3D""hi"" style=3D""""></div></div></div></span></body></html>"
                                                 , false, @"<html><body><span style=""font-family:Verdana; color:#000000; font-size:10pt;""><div class=""gs"" style=""""><div class="""" style=""""><div id="":n1"" class=""ii gt"" style=""""><div id="":n0"" class=""a3s aXjCH "" style=""""><div dir=""ltr"" style="""">chuck nu¤ Â À ¢<div class=""yj6qo"" style=""""></div><div class=""adL"" style=""""><br style=""""></div></div><div class=""adL"" style=""""></div></div></div><div class=""hi"" style=""""></div></div></div></span></body></html>"),
                //Gmail base64
                new Tuple <string, bool, string>(@"<div dir=""ltr"">chuck nu¤ Â À ¢<br></div>", true
                                                 , @"<div dir=""ltr"">chuck nu¤ Â À ¢<br></div>"),
                //Gmail non-base64 with =3D typed in email and a new line at the end.
                new Tuple <string, bool, string>(@"=3D and other things 
", false, @"= and other things 
"),
                //Gmail non-base64 with multiple lines and plain text
                //Gmail non-base64 with =3D typed in email and a new line at the end.
                new Tuple <string, bool, string>(@"plain text
multiple lines

", false, @"plain text
multiple lines

"),
            };
            Encoding encoding = Encoding.GetEncoding("utf-8");

            foreach (Tuple <string, bool, string> test in listTestSubjects)
            {
                Assert.AreEqual(test.Item3, EmailMessages.DecodeBodyText("=", test.Item1, encoding));
            }
        }
Exemplo n.º 10
0
        public async Task <bool> TransferCharacter(int sourceCharacterId, int targetCharacterId)
        {
            var user = await userService.GetUserWithCharacters(httpContextReader.CurrentUserId) ??
                       throw new EntityNotFoundException("User not found");

            var(sourceCharacter, targetCharacter) =
                (user.Characters.FirstOrDefault(c => c.Id == sourceCharacterId) ??
                 throw new EntityNotFoundException("Character not found"),
                 user.Characters.FirstOrDefault(c => c.Id == targetCharacterId) ??
                 throw new EntityNotFoundException("Character not found"));

            using (var transaction = database.BeginTransaction().Transaction)
            {
                await ExecuteTransferCharacter(sourceCharacter, targetCharacter);

                transaction.Complete();
            }

            try
            {
                await emailSender.Send(EmailMessages.TransferCharacterEmail(user.Email));

                mtaManager.CallFunction(MtaResources.WebsiteHttpFunctions, MtaFunctions.TransferCharacter);
            }
            catch (MTARequestException)
            {
            }

            return(true);
        }
Exemplo n.º 11
0
        public void EmailMessages_FindAndReplaceImageTagsWithAttachedImage_HtmlBodyNoImage()
        {
            string localHtml           = @"<html><head><title>Email Stuff</head><body><p><hr><a href=""http://www.google.com"">Google Link</a>Check out my <i>great</i> link!</p></body></html>";
            bool   areImagesDownloaded = false;
            string actualLocalPath     = EmailMessages.FindAndReplaceImageTagsWithAttachedImage(localHtml, areImagesDownloaded, out List <string> listLocalImagePaths);

            Assert.AreEqual(actualLocalPath, localHtml);
        }
Exemplo n.º 12
0
        public void EmailMessages_FindAndReplaceImageTagsWithAttachedImage_ClosingSlashInsideImg()
        {
            string localHtml           = @"<html><head><title>Email Stuff</head><body><img src=""image""/></body></html>";
            bool   areImagesDownloaded = false;
            string actualLocalPath     = EmailMessages.FindAndReplaceImageTagsWithAttachedImage(localHtml, areImagesDownloaded, out List <string> listLocalImagePaths);
            string expectedLocalPath   = @"<html><head><title>Email Stuff</head><body><img alt=""image"" src=""cid:image""/></body></html>";

            Assert.AreEqual(expectedLocalPath, actualLocalPath);
        }
Exemplo n.º 13
0
        public void EmailMessages_FindAndReplaceImageTagsWithAttachedImage_HtmlBodyWithMultiImages()
        {
            string localHtml           = @"<html><head><title>Email Stuff</head><body><p>Text Text Text Text<img src=""image""></img><span></span><img src=""image2""></img>Text Text Text Text</p></body></html>";
            bool   areImagesDownloaded = false;
            string actualLocalPath     = EmailMessages.FindAndReplaceImageTagsWithAttachedImage(localHtml, areImagesDownloaded, out List <string> listLocalImagePaths);
            string expectedLocalPath   = @"<html><head><title>Email Stuff</head><body><p>Text Text Text Text<img alt=""image"" src=""cid:image""/><span></span><img alt=""image"" src=""cid:image2""/>Text Text Text Text</p></body></html>";

            Assert.AreEqual(expectedLocalPath, actualLocalPath);
        }
Exemplo n.º 14
0
        public async Task <SendResetPasswordResponse> Handle(SendResetPasswordRequest request, CancellationToken cancellationToken)
        {
            var sendResetPasswordResult = await resetPasswordManager.GenerateResetPasswordToken(request.Email) ?? throw new TokenException("Error occurred during generating reset password token", ErrorCodes.CannotGenerateToken);

            return(await emailSender.Send(EmailMessages.ResetPasswordEmail(sendResetPasswordResult.Email, sendResetPasswordResult.Username,
                                                                           $"{Configuration.GetValue<string>(AppSettingsKeys.ClientAddress)}account/resetPassword?userId={sendResetPasswordResult.UserId}&token={sendResetPasswordResult.Token}"))
            ? new SendResetPasswordResponse()
            : throw new TokenException("Error occurred during generating reset password token", ErrorCodes.CannotGenerateToken));
        }
Exemplo n.º 15
0
        public bool SendNotificationAboutNewOrUpdatedWorkload(string uniqueName, int newOrUpdate)
        {
            EmailLogic clientEmail = new EmailLogic();

            // Mounting parameters and message.
            string ToName  = Util.GetUserAlias(uniqueName);
            string ToEmail = uniqueName;
            string Subject = "";

            StringBuilder StructureModified = new StringBuilder();

            StructureModified = EmailMessages.GetEmailMessageStructure();

            // Replacing the generic title by the customized.
            StructureModified.Replace("[MessageTitle]", "Hi " + ToName + ", we have news to you: ");

            if (newOrUpdate == 0) // new workload
            {
                Subject += "[ARDA] New workload available to you";

                // Replacing the generic subtitle by the customized.
                StructureModified.Replace("[MessageSubtitle]", "A new <strong>Workload</strong> was created and signed to you.");

                // Replacing the generic message body by the customized.
                StructureModified.Replace("[MessageBody]", "To see your new workload, please, click on the link bellow.");
            }
            else
            {
                Subject += "[ARDA] Existing workload has been updated";

                // Replacing the generic subtitle by the customized.
                StructureModified.Replace("[MessageSubtitle]", "A existent <strong>Workload</strong> signed to you was updated.");

                // Replacing the generic message body by the customized.
                StructureModified.Replace("[MessageBody]", "To see your workload updated, please, click on the link bellow.");
            }

            // Replacing the generic callout box.
            StructureModified.Replace("[MessageCallout]", "Dashboard (Kanban): <a href='/Dashboard/Index'>My workloads</a>");

            // Creating a object that will send the message.
            EmailLogic EmailObject = new EmailLogic();

            try
            {
                var EmailTask = EmailObject.SendEmailAsync(ToName, ToEmail, Subject, StructureModified.ToString());
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 16
0
        public void EmailMessages_ProcessRawEmailMessageIn_InvalidBoundaries()
        {
            string       strRawEmail  = @"From: John Doe <*****@*****.**>
To: Mary Smith <*****@*****.**>
Subject: Saying Hello
Date: Thu, 11 Feb 2016 06:58:09 CST
Message-ID: <*****@*****.**>
Content-Type: multipart/mixed; boundary=""B1""

This is a multi-part message in MIME format.
--B1
Content-Type: multipart/alternative; boundary=""B12""
MIME-Version: 1.0

--B12
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Hello from Argentina!

--B12
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

This is a message just to say hello.
So, ""Hello"".

--B12--
--B1
Content-Type: image/gif
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=""map_of_Argentina.gif""

R01GOD1hJQA1AKIAAP/////78P/omn19fQAAAAAAAAAAAAAAACwAAAAAJQA1AAAD7Qi63P5w
wEmjBCLrnQnhYCgM1wh+pkgqqeC9XrutmBm7hAK3tP31gFcAiFKVQrGFR6kscnonTe7FAAad
GugmRu3CmiBt57fsVq3Y0VFKnpYdxPC6M7Ze4crnnHum4oN6LFJ1bn5NXTN7OF5fQkN5WYow
BEN2dkGQGWJtSzqGTICJgnQuTJN/WJsojad9qXMuhIWdjXKjY4tenjo6tjVssk2gaWq3uGNX
U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
7itICBxISKDBgwgTKjyYAAA7
--B1--";
            EmailMessage emailMessage = null;

            try {
                emailMessage = EmailMessages.ProcessRawEmailMessageIn(strRawEmail, 0,
                                                                      EmailAddressT.CreateEmailAddress(emailUserName: "******"), false);
            }
            catch (Exception ex) {
                Assert.Fail(ex.Message);
            }
            Assert.IsNotNull(emailMessage.Attachments);
            Assert.AreEqual(emailMessage.Attachments.Count, 1);
        }
Exemplo n.º 17
0
        public async Task <bool> SendChangeEmailCallback(string newEmail)
        {
            var currentUser = await GetCurrentUser();

            var changeEmailToken = await userManager.GenerateChangeEmailTokenAsync(currentUser, newEmail);

            changeEmailToken = cryptoService.Encrypt(changeEmailToken);

            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ClientAddress)}account/changeEmail/confirm?newEmail={newEmail}&token={changeEmailToken}";

            return(await emailSender.Send(EmailMessages.EmailChangeEmail(newEmail, callbackUrl)));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates an XML element containing the data for the invite
        /// </summary>
        /// <param name="document">XML document the element will be added to</param>
        /// <returns>XML element containing the data for the invite</returns>
        public XmlElement ToXml(XmlDocument document)
        {
            XmlElement invite = document.CreateElement("INVITE");

            XmlAttribute id = document.CreateAttribute("Id");

            id.Value = Id.ToString();
            invite.Attributes.Append(id);

            XmlAttribute emailAddress = document.CreateAttribute("EmailAddress");

            emailAddress.Value = EmailAddress;
            invite.Attributes.Append(emailAddress);

            XmlAttribute isAdmin = document.CreateAttribute("IsAdmin");

            isAdmin.Value = IsAdmin.ToString();
            invite.Attributes.Append(isAdmin);

            XmlAttribute includesCeremony = document.CreateAttribute("IncludesCeremony");

            includesCeremony.Value = IncludesCeremony.ToString();
            invite.Attributes.Append(includesCeremony);

            XmlAttribute reserveSandholeRoom = document.CreateAttribute("ReserveSandholeRoom");

            reserveSandholeRoom.Value = ReserveSandholeRoom.ToString();
            invite.Attributes.Append(reserveSandholeRoom);

            XmlAttribute emailMessages = document.CreateAttribute("EmailMessages");

            emailMessages.Value = EmailMessages.ToString();
            invite.Attributes.Append(emailMessages);

            XmlAttribute notifyGiftWebsite = document.CreateAttribute("NotifyGiftWebsite");

            notifyGiftWebsite.Value = NotifyGiftWebsite.ToString();
            invite.Attributes.Append(notifyGiftWebsite);

            XmlElement guests = document.CreateElement("GUESTS");

            invite.AppendChild(guests);

            foreach (Guest guest in Guests)
            {
                guests.AppendChild(guest.ToXml(document));
            }

            return(invite);
        }
Exemplo n.º 19
0
        public async Task <SignUpResponse> Handle(SignUpRequest request, CancellationToken cancellationToken)
        {
            if (!await captchaService.VerifyCaptcha(request.CaptchaResponse))
            {
                throw new CaptchaException();
            }

            if (await authValidationService.UsernameExists(request.Username) ||
                await authValidationService.EmailExists(request.Email))
            {
                throw new DuplicateException("Account already exists");
            }

            if (await serialService.SerialExists(request.Serial))
            {
                throw new DuplicateException("Serial already exists");
            }

            User referrer = default;

            if (!string.IsNullOrEmpty(request.Referrer))
            {
                referrer = await userService.FindUserByUsername(request.Referrer);
            }

            var response = await authService.SignUp(request.Username, request.Email, request.Password, request.Serial,
                                                    referrer == null? 0 : referrer.Id);

            var(encryptedToken, encryptedEmail) = (cryptoService.Encrypt(response.TokenCode),
                                                   cryptoService.Encrypt(response.User.Email));

            //TODO:Change it on ClientAddress
            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}api/auth/confirm?email={encryptedEmail}&token={encryptedToken}";

            var emailTemplate =
                (await emailTemplateGenerator.FindEmailTemplate(EmailTemplateDictionary.RegisterTemplate))
                .ReplaceParameters(new EmailTemplateParameter("{{username}}", response.User.Username),
                                   new EmailTemplateParameter("{{callbackUrl}}", callbackUrl));

            return(await emailSender.Send(EmailMessages.ActivationAccountEmail(response.User.Email, emailTemplate))
                ? (SignUpResponse) new SignUpResponse
            {
                TokenCode = encryptedToken, User = mapper.Map <UserAuthDto>(response.User)
            }

                   .LogInformation($"User {request.Username} with email {request.Email} signed up")
                : throw new ServiceException("Sending confirmation email failed"));
        }
        public async Task <GenerateChangeEmailTokenResponse> Handle(GenerateChangeEmailTokenRequest request, CancellationToken cancellationToken)
        {
            if (await authValidationService.EmailExists(request.NewEmail))
            {
                throw new DuplicateException("Email already exists", ErrorCodes.EmailExists);
            }

            var generateChangeEmailTokenResult = await profileService.GenerateChangeEmailToken(request.NewEmail) ??
                                                 throw new TokenException("Error occurred during generating change email token", ErrorCodes.CannotGenerateToken);

            return(await emailSender.Send(EmailMessages.EmailChangeEmail(request.NewEmail,
                                                                         $"{Configuration.GetValue<string>(AppSettingsKeys.ClientAddress)}profile/changeEmail?userId={generateChangeEmailTokenResult.UserId}&token={generateChangeEmailTokenResult.Token}&newEmail={generateChangeEmailTokenResult.NewEmail}"))
                    ? new GenerateChangeEmailTokenResponse()
                    : throw new ServiceException("Sending change email callback failed", ErrorCodes.SendEmailFailed));
        }
Exemplo n.º 21
0
        public async Task <bool> SendResetPasswordCallback(string email, string newPassword)
        {
            var user = await userManager.FindByEmailAsync(email) ?? throw new EntityNotFoundException("User not found");

            if (UserBlockedSpecification.Create().IsSatisfied(user))
            {
                throw new BlockException();
            }

            var resetPasswordToken = cryptoService.Encrypt(await userManager.GeneratePasswordResetTokenAsync(user));

            newPassword = cryptoService.Encrypt(newPassword);

            string callbackUrl = $"{Configuration.GetValue<string>(AppSettingsKeys.ClientAddress)}resetPassword/confirm?email={user.Email}&newPassword={newPassword}&token={resetPasswordToken}";

            return(await emailSender.Send(EmailMessages.ResetPasswordEmail(email, user.UserName, callbackUrl)));
        }
Exemplo n.º 22
0
        public void EmailMessages_ProcessInlineEncodedText_VariousFormats()
        {
            List <Tuple <string, string> > listTestSubjects = new List <Tuple <string, string> >()
            {
                //Raw,Expected
                //UTF-8 Base64 encoded string with non-ascii characters.
                new Tuple <string, string>("=?UTF-8?B?RndkOiDCoiDDhiAxMjM0NSDDpiDDvyBzb21lIGFzY2lpIGNoYXJzIMOCIMOD?=", "Fwd: ¢ Æ 12345 æ ÿ some ascii chars  Ã"),
                //UTF-8 QuotedPrintable encoded string with non-ascii charaters.
                new Tuple <string, string>("=?UTF-8?Q?nu=C2=A4=20=C3=82=20=C3=80=20=C2=A2?=", "nu¤ Â À ¢"),
                //UTF-8 QuotedPrintable string embedded within a larger string.
                new Tuple <string, string>("[FWD: test =?UTF-8?Q?=3D=33D=20more=20text=20=3D=5D?=", "[FWD: test =3D more text =]"),
                //Plain text string.
                new Tuple <string, string>("regular old plain text subject line", "regular old plain text subject line"),
                //Empty string.
                new Tuple <string, string>("", ""),
                //Multiple inline UTF-8 QuotedPrintable encoded strings.
                new Tuple <string, string>("=?utf-8?Q?RE:_Half_year_dental_check-up_at?==?utf-8?Q?_Super_&_Clean_Teeth_for_=C3=81_Team?=with regular text in between=?utf-8?Q?_Third_Clause?="
                                           , "RE: Half year dental check-up at Super & Clean Teeth for Á Teamwith regular text in between Third Clause"),
                //Multiple inline encoded strings with a variety of formats.
                new Tuple <string, string>(@"=?utf-8?Q?encodedtext?= =?iso-8859-1?q?this=20is=20some=20text?=
=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
    =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=", @"encodedtext this is some text
If you can read this yo
    u understand the example."),
                //Normal plaintext email address
                new Tuple <string, string>("*****@*****.**", "*****@*****.**"),
                //Aliased email address, with UTF-8 QuotedPrintable inline encoded string.
                new Tuple <string, string>("=?UTF-8?Q?Bobby_Wiggleh=C3=81rt?= <*****@*****.**>"
                                           , "Bobby WigglehÁrt <*****@*****.**>"),
                //using a 'c' instead of 'B' (Base64) or 'Q' (Quoted Printable)
                new Tuple <string, string>("=?UTF-8?c?nu=C2=A4=20=C3=82=20=C3=80=20=C2=A2?=", "nu¤ Â À ¢"),
                //Assert that an email message containing any characters that cannot be represented by a byte do not cause parsing to fail.
                //E.g. the typical hyphen character is '-' but some email will contain '–' which causes an "Arithmetic operation resulted in an overflow." UE.
                //The failure happens when we try to decode the body text of the email for non-ascii characters by casting each char to a byte.
                new Tuple <string, string>("=?UTF-8?Q?hyphen: -  EN Dash: –?=", "hyphen: -  EN Dash: –"),
                //Assert that the same email message containing hex characters parses into the human-readable format ('=E2=80=93' equates to '–').
                new Tuple <string, string>("=?UTF-8?Q?=68=79=70=68=65=6E=3A=20=2D=20=20=45=4E=20=44=61=73=68=3A=20=E2=80=93?=", "hyphen: -  EN Dash: –"),
                //Assert that Cp1252 (Windows-1252) encoded text can be parsed.
                new Tuple <string, string>("=?Cp1252?Q?Oregon=92s_rain=92s_refreshing?=", "Oregon’s rain’s refreshing"),
            };

            foreach (Tuple <string, string> test in listTestSubjects)
            {
                Assert.AreEqual(test.Item2, EmailMessages.ProcessInlineEncodedText(test.Item1));
            }
        }
        /// <summary>
        /// our Post action that captures the information from the user
        /// and sends the object into the EmailMessages class to appropriate
        /// create the needed email messages
        /// </summary>
        /// <returns>A Page</returns>
        public async Task <IActionResult> OnPost()
        {
            if (ModelState.IsValid)
            {
                await _emailSender.SendEmailAsync("*****@*****.**",
                                                  EmailMessages.Request,
                                                  EmailMessages.ContactUsRequest(this));

                await _emailSender.SendEmailAsync(Email,
                                                  EmailMessages.Thanks,
                                                  EmailMessages.ContactUsReply(this));

                return(RedirectToPage("/"));
            }
            //equiv to return View();
            return(Page());
        }
Exemplo n.º 24
0
        public async Task <IActionResult> OnPost()
        {
            if (ModelState.IsValid)
            {
                RSVPUser user = new RSVPUser()
                {
                    Agree                = Agree,
                    Name                 = Name,
                    Email                = Email,
                    PhoneNumber          = PhoneNumber,
                    IsVeteran            = IsVeteran,
                    PreferredTime        = PreferredTime,
                    IsWashingtonResident = IsWashingtonResident,
                    ChooseMaritalStatus  = ChooseMaritalStatus,
                    SpouseName           = SpouseName,
                    HasChildren          = HasChildren,
                    IsCurrentlyPregnant  = IsCurrentlyPregnant,
                    MinorChildName       = MinorChildName,
                    ContRemBeneficiary   = ContRemBeneficiary,
                    PersonToInherit      = PersonToInherit,
                    PersonalRep          = PersonalRep,
                    //BackupRep = BackupRep,
                };
                //if (PersonalRep == BackupRep)
                //{
                //	TempData["Error"] = "Please make sure your Personal Rep is not the same as your Backup Rep.";
                //	return Page();
                //}
                if (!Agree)
                {
                    TempData["Error"] = "You cannot sign up unless you agree to the terms and conditions.";
                    return(Page());
                }
                await _context.AddAsync(user);

                await _context.SaveChangesAsync();

                await _emailSender.SendEmailAsync(Email,
                                                  EmailMessages.Thanks,
                                                  EmailMessages.SignUpReply(user));

                return(RedirectToPage("/"));
            }
            return(Page());
        }
Exemplo n.º 25
0
        public async Task <bool> SendResetPasswordCallback(string email, string newPassword)
        {
            var user = await userManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(false);
            }

            var resetPasswordToken = await userManager.GeneratePasswordResetTokenAsync(user);

            resetPasswordToken = cryptoService.Encrypt(resetPasswordToken);

            newPassword = cryptoService.Encrypt(newPassword);

            string callbackUrl = $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}/Auth/ConfirmResetPassword?email={user.Email}&newPassword={newPassword}&token={resetPasswordToken}";

            return(await emailSender.Send(EmailMessages.ResetPasswordEmail(email, callbackUrl)));
        }
Exemplo n.º 26
0
        public void EmailMessages_FindAndReplacePostalAddressTag()
        {
            //Format disclaimer.
            PrefT.UpdateString(PrefName.EmailDisclaimerTemplate, "This email has been sent to you from:\r\n[PostalAddress].\r\n\r\nHow to unsubscribe:\r\nIf you no longer want to receive any email messages from us, simply reply to this email with the word \"unsubscribe\" in the subject line.");
            //Setup practice address.
            PrefT.UpdateString(PrefName.PracticeAddress, "Practice Address1 Here");
            PrefT.UpdateString(PrefName.PracticeAddress2, "3275 Marietta St SE");
            PrefT.UpdateString(PrefName.PracticeCity, "Salem");
            PrefT.UpdateString(PrefName.PracticeST, "OR");
            PrefT.UpdateString(PrefName.PracticeZip, "97317");
            //Setup clinic address.
            Clinic clinic = ClinicT.CreateClinic();

            clinic.Address = "Clinic Address1 Here";
            Clinics.Update(clinic);
            Clinics.RefreshCache();
            //Turn feature off.
            PrefT.UpdateBool(PrefName.EmailDisclaimerIsOn, false);
            string emailBody = "Hi, this is an email.\r\n\r\nRegards,\r\nEvery OD Engineer... ever.";
            string emailBodyWithDisclaimer = EmailMessages.FindAndReplacePostalAddressTag(emailBody, 0);

            //Feature is off so no disclaimer added.
            Assert.AreEqual(emailBody, emailBodyWithDisclaimer);
            //Turn feature on.
            PrefT.UpdateBool(PrefName.EmailDisclaimerIsOn, true);
            //Turn clinics off.
            PrefT.UpdateBool(PrefName.EasyNoClinics, true);
            emailBodyWithDisclaimer = EmailMessages.FindAndReplacePostalAddressTag(emailBody, 0);
            //Feature is on so disclaimer added (no clinic).
            Assert.AreNotEqual(emailBody, emailBodyWithDisclaimer);
            Assert.IsTrue(emailBodyWithDisclaimer.EndsWith("subject line."));
            Assert.IsTrue(emailBodyWithDisclaimer.Contains("Practice Address"));
            Assert.IsFalse(emailBodyWithDisclaimer.Contains("Clinic Address"));
            //Turn clinics on.
            PrefT.UpdateBool(PrefName.EasyNoClinics, false);
            emailBodyWithDisclaimer = EmailMessages.FindAndReplacePostalAddressTag(emailBody, clinic.ClinicNum);
            //Feature is on so disclaimer added (with clinic).
            Assert.AreNotEqual(emailBody, emailBodyWithDisclaimer);
            Assert.IsTrue(emailBodyWithDisclaimer.EndsWith("subject line."));
            Assert.IsTrue(emailBodyWithDisclaimer.Contains("Clinic Address"));
            Assert.IsFalse(emailBodyWithDisclaimer.Contains("Practice Address"));
        }
Exemplo n.º 27
0
        public async Task <Reply> SendReply(string content, string reportId, IEnumerable <IFormFile> files = null)
        {
            var currentUser = await profileService.GetCurrentUser();

            var report = await GetReport(reportId);

            if (report.IsClosed)
            {
                throw new NoPermissionsException("This report is closed");
            }

            bool isAdmin = currentUser.IsAdmin();

            var reply = Reply.Create(content, isAdmin, report);

            if (report.ReporterId == null && !isAdmin)
            {
                throw new NoPermissionsException("You are not allowed to write this reply");
            }
            else if (report.ReporterId == null && isAdmin)
            {
                await emailSender.Send(EmailMessages.ReplyEmail(report.Email, content, report.Subject));
            }
            else
            {
                ValidatePermissions(currentUser, report, isAdmin, reply);
            }

            report.Replies.Add(reply);

            report.Update();

            if (!await database.Complete())
            {
                return(null);
            }

            await AttachFiles(files, report, reply);

            return(reply);
        }
Exemplo n.º 28
0
        public void EmailMessages_CreateForward_HtmlEncoding()
        {
            EmailMessage receivedEmail = EmailMessageT.CreateEmailMessage(0, fromAddress: "*****@*****.**", toAddress: "*****@*****.**"
                                                                          , subject: "=?UTF-8?Q?nu=C2=A4=20=C3=82=20=C3=80=20=C2=A2?=");

            receivedEmail.RawEmailIn = @"MIME-Version: 1.0
Date: Thu, 10 Oct 2019 06:27:02 -0700
Message-ID: <CAALTEpk8yAUh7pO=FzgCy0r0b20Fi5vefw_8yhRvstMfTvRtAQ@mail.gmail.com>
Subject: & subject
From: =?UTF-8?Q?Bobby_Wiggleh=C3=81rt?= <*****@*****.**>
To: Bobby Wigglehart <*****@*****.**>
Content-Type: multipart/alternative; boundary=""0000000000005e7d3705948e5be6""
X-Antivirus: AVG (VPS 191009-2, 10/09/2019), Inbound message
X-Antivirus-Status: Clean

--0000000000005e7d3705948e5be6
Content-Type: text/plain; charset=""UTF-8""

non-breaking space  
less than <
greater than >
ampersand &

--0000000000005e7d3705948e5be6
Content-Type: text/html; charset=""UTF-8""
Content-Transfer-Encoding: quoted-printable

<div dir=3D""ltr"">non-breaking space &nbsp;<div>less than &lt;</div><div>greater than &gt;</div><div>ampersand &amp;=C2=A0</div></div>

--0000000000005e7d3705948e5be6--";
            EmailAddress emailAddress = new EmailAddress()
            {
                EmailUsername = "******"
            };
            EmailMessage forwardEmail = EmailMessages.CreateForward(receivedEmail, emailAddress);

            Assert.AreEqual(emailAddress.EmailUsername, forwardEmail.FromAddress);
            Assert.AreEqual("FWD: nu¤ Â À ¢", forwardEmail.Subject);
            Assert.AreEqual("\r\n\r\n\r\nOn " + DateTime.MinValue.ToString() + " [email protected] sent:\r\n>non-breaking space  less than <greater than >ampersand &"
                            , forwardEmail.BodyText);
        }
Exemplo n.º 29
0
        public bool SendNotificationOfNewUserByEmail(string uniqueName)
        {
            EmailLogic clientEmail = new EmailLogic();

            // Mounting parameters and message.
            var Configuration = new ConfigurationBuilder().AddJsonFile("secrets.json").Build();
            var admin         = Configuration["Email:Administrator"];

            string ToName  = "Arda Administrator";
            string ToEmail = admin;
            string Subject = "[ARDA] A new user has been logged @ Arda";

            StringBuilder StructureModified = new StringBuilder();

            StructureModified = EmailMessages.GetEmailMessageStructure();

            // Replacing the generic title by the customized.
            StructureModified.Replace("[MessageTitle]", "Hi " + ToName + ", someone requested access to the system");

            // Replacing the generic subtitle by the customized.
            StructureModified.Replace("[MessageSubtitle]", "Who did the request was <strong>" + uniqueName + "</strong>. If you deserve, can access 'Users' area and distribute the appropriated permissions.");

            // Replacing the generic message body by the customized.
            StructureModified.Replace("[MessageBody]", "Details about the request: </br></br><ul><li>Email: " + uniqueName + "</li><li>Date/time access: " + DateTime.Now + "</li></ul>");

            // Replacing the generic callout box.
            StructureModified.Replace("[MessageCallout]", "For more details about the request, send a message to <strong>[email protected]</strong>.");

            // Creating a object that will send the message.
            EmailLogic EmailObject = new EmailLogic();

            try
            {
                var EmailTask = EmailObject.SendEmailAsync(ToName, ToEmail, Subject, StructureModified.ToString());
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 30
0
        public async Task <SendChangePasswordEmailResponse> Handle(SendChangePasswordEmailRequest request,
                                                                   CancellationToken cancellationToken)
        {
            var result = await userTokenGenerator.GenerateChangePasswordToken(request.OldPassword);

            var(encryptedToken, encryptedEmail, encryptedPassword) =
                (cryptoService.Encrypt(result.Token), cryptoService.Encrypt(result.Email),
                 cryptoService.Encrypt(request.NewPassword));

            string callbackUrl =
                $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}api/account/changePassword?email={encryptedEmail}&token={encryptedToken}&newPassword={encryptedPassword}";

            var emailTemplate =
                (await emailTemplateGenerator.FindEmailTemplate(EmailTemplateDictionary.RegisterTemplate))
                .ReplaceParameters(new EmailTemplateParameter("{{username}}", result.Username),
                                   new EmailTemplateParameter("{{callbackUrl}}", callbackUrl));

            await emailSender.Send(EmailMessages.ActivationAccountEmail(result.Email, emailTemplate));

            return(new SendChangePasswordEmailResponse());
        }