Exemplo n.º 1
0
        public async Task ItShouldBeIdempotent()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateFreeAccessUsersDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase, true);

                await this.target.ExecuteAsync(
                    CreatorId,
                    BlogId,
                    new List <ValidEmail>
                {
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**")
                });

                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(
                    CreatorId,
                    BlogId,
                    new List <ValidEmail>
                {
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**")
                });

                return(ExpectedSideEffects.None);
            });
        }
        public async Task WhenUpdateAccountSettingsCalledWithSameEMailAndEmailWasNotConfirmed_ItShouldStillNotBeConfirmed()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateAccountSettingsDbStatement(testDatabase, this.userManager.Object, this.requestSnapshot);
                await this.CreateUserAsync(testDatabase, false);
                await testDatabase.TakeSnapshotAsync();

                var expectedUser                = await this.GetUserAsync(testDatabase);
                expectedUser.UserName           = this.newUsername.Value;
                expectedUser.ProfileImageFileId = this.newFileId.Value;
                expectedUser.SecurityStamp      = this.securityStamp;

                var result = await this.target.ExecuteAsync(
                    this.userId,
                    this.newUsername,
                    ValidEmail.Parse(this.email.Value),
                    null,
                    this.newFileId,
                    this.securityStamp);

                Assert.AreEqual(false, result.EmailConfirmed);

                return(new ExpectedSideEffects
                {
                    Update = expectedUser
                });
            });
        }
Exemplo n.º 3
0
            public async Task WhenSomeEmailAddressesAreInvalid_ItShouldCallUpdateFreeAccessUsersAndItShouldReturnValidEmailAddresses()
            {
                var emailList = new List <string> {
                    "*****@*****.**", "two.test.com"
                };
                var freeAccessUsersData = new FreeAccessUsersData {
                    Emails = emailList
                };

                var validEmailList = new List <ValidEmail> {
                    ValidEmail.Parse(emailList[0])
                };
                var invalidEmailList = new List <Email> {
                    new Email(emailList[1])
                };

                var expectedResult = new PutFreeAccessUsersResult(invalidEmailList);

                this.updateFreeAccessUsers
                .Setup(v => v.HandleAsync(new UpdateFreeAccessUsersCommand(Requester, BlogId, validEmailList)))
                .Returns(Task.FromResult(0))
                .Verifiable();

                var result = await this.target.PutFreeAccessList(BlogId.Value.EncodeGuid(), freeAccessUsersData);

                this.updateFreeAccessUsers.Verify();
                Assert.AreEqual(expectedResult, result);
            }
 public void ValidEmail(ValidEmail valido)
 {
     try
     {
         DataSet ds = SqlHelper.ExecuteDataset(valido.conexion, "spCIDBD_get_ValidarCorreo", valido.Correo);
         valido.resultado = "No se encontraron resultados";
         if (ds != null)
         {
             if (ds.Tables[0] != null)
             {
                 if (ds.Tables[0].Rows.Count > 0)
                 {
                     valido.resultado = "REGOK";
                     valido.valido    = Convert.ToInt32(ds.Tables[0].Rows[0]["Resultado"]);
                     valido.token     = ds.Tables[0].Rows[0]["token"].ToString();
                     valido.GenerarJSON();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 5
0
        public void TestValidEmailSingle()
        {
            ValidEmail emailSettings = new ValidEmail();
            ValidEmail validEmail    = ValidateSettings <ValidEmail> .Validate(emailSettings);

            Assert.IsTrue(validEmail.Email == "*****@*****.**");
        }
Exemplo n.º 6
0
        private void buttonRegister_Click(object sender, EventArgs e)
        {
            if (!this.CheckTextBoxes())
            {
                MessageBox.Show("Заполните все поля", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var isEmailValid = ValidEmail.IsValidEmail(this.textBoxEmail.Text);

            if (!isEmailValid)
            {
                MessageBox.Show("Введите корректный Email!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var newUser = EntityManager.UserDataTable.NewПользователиRow();

            newUser.Фамилия  = this.textBoxSername.Text;
            newUser.Имя      = this.textBoxName.Text;
            newUser.Отчество = this.textBoxPatronomic.Text;
            newUser._E_mail  = this.textBoxEmail.Text;
            newUser.логин    = this.textBoxLogin.Text;
            newUser.пароль   = Encrypt(this.textBoxPassword.Text, this.password);
            EntityManager.UserDataTable.AddПользователиRow(newUser);
            EntityManager.UpdateUsers();
            this.пользователиTableAdapter.Fill(this._k_systemsDataSet.Пользователи);

            MessageBox.Show("Добавление клиента прошло успешно!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Exemplo n.º 7
0
        public async Task WhenNewEmailList_AndEmailsForBlogIsEmpty_ItShouldModifyEmailsForBlog()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateFreeAccessUsersDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase, false);
                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(
                    CreatorId,
                    BlogId,
                    new List <ValidEmail>
                {
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**")
                });

                return(new ExpectedSideEffects
                {
                    Inserts = new List <FreeAccessUser>
                    {
                        new FreeAccessUser {
                            BlogId = BlogId.Value, Email = "*****@*****.**"
                        },
                        new FreeAccessUser {
                            BlogId = BlogId.Value, Email = "*****@*****.**"
                        },
                    },
                });
            });
        }
Exemplo n.º 8
0
        public async Task WhenNewEmailListIsSubset_ItShouldDeleteOldEmailsForBlog()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateFreeAccessUsersDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase, true);
                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(
                    CreatorId,
                    BlogId,
                    new List <ValidEmail>
                {
                    ValidEmail.Parse("*****@*****.**"),
                });

                return(new ExpectedSideEffects
                {
                    Deletes = new List <FreeAccessUser>
                    {
                        new FreeAccessUser {
                            BlogId = BlogId.Value, Email = "*****@*****.**"
                        },
                        new FreeAccessUser {
                            BlogId = BlogId.Value, Email = "*****@*****.**"
                        },
                    },
                });
            });
        }
Exemplo n.º 9
0
        public HttpResponseMessage SendEmail([FromBody] Email email)
        {
            var emailIsValid = Regex.IsMatch(email.From,
                                             @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");

            if (!emailIsValid)
            {
                return(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    ReasonPhrase = "Valid Email is Required"
                });
            }
            ValidEmail validEmail = _mapper.Map <Email, ValidEmail>(email);

            if (!ModelState.IsValid)
            {
                return(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    ReasonPhrase = "Please include some text in the body"
                });
            }
            var message = new MimeMessage();

            message.ResentFrom.Add(new MailboxAddress(validEmail.Name, validEmail.From));
            message.From.Add(new MailboxAddress(validEmail.Name, validEmail.From));
            message.ResentTo.Add(new MailboxAddress(ConfigurationManager.AppSettings.Get("EMAIL_RECEIVE_NAME"), ConfigurationManager.AppSettings.Get("EMAIL_RECEIVE_ADDRESS")));
            message.To.Add(new MailboxAddress(ConfigurationManager.AppSettings.Get("EMAIL_RECEIVE_NAME"), ConfigurationManager.AppSettings.Get("EMAIL_RECEIVE_ADDRESS")));
            message.ResentReplyTo.Add(new MailboxAddress(validEmail.Name, validEmail.From));
            message.ReplyTo.Add(new MailboxAddress(validEmail.Name, validEmail.From));
            message.ResentSender = new MailboxAddress(validEmail.Name, validEmail.From);
            message.Sender       = new MailboxAddress(validEmail.Name, validEmail.From);
            message.Subject      = email.Subject;

            var builder = new BodyBuilder();

            builder.HtmlBody = string.Format(@"" + email.Body);
            message.Body     = builder.ToMessageBody();

            try
            {
                var result = Mail.SendEMail(message).Result;

                return(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    ReasonPhrase = result.Item2
                });
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    ReasonPhrase = ex.Message
                });
            }
        }
Exemplo n.º 10
0
        public async Task WhenEmailDoesNotExist_ItShouldDoNothing()
        {
            var command = new RequestPasswordResetCommand(ValidEmail.Parse(EmailAddress), null);

            this.userManager.Setup(_ => _.FindByEmailAsync(EmailAddress)).ReturnsAsync(null);

            await this.target.HandleAsync(command);
        }
Exemplo n.º 11
0
        public void TestValidOptional1()
        {
            ValidEmail emailSettings = new ValidEmail();

            emailSettings = ValidateSettings <ValidEmail> .Validate(emailSettings);

            Assert.IsTrue(String.IsNullOrEmpty(emailSettings.Email));
        }
Exemplo n.º 12
0
        public void TestInvalidOptional1()
        {
            ValidEmail emailSettings = new ValidEmail()
            {
                Email = "mehere.com"
            };

            emailSettings = ValidateSettings <ValidEmail> .Validate(emailSettings);
        }
Exemplo n.º 13
0
        public void TestValidOptional2()
        {
            ValidEmail emailSettings = new ValidEmail()
            {
                Email = "*****@*****.**"
            };

            emailSettings = ValidateSettings <ValidEmail> .Validate(emailSettings);

            Assert.IsTrue(emailSettings.Email == "*****@*****.**");
        }
Exemplo n.º 14
0
        public async Task WhenEmailExists_ItShouldSendEmail()
        {
            var command = new RequestPasswordResetCommand(ValidEmail.Parse(EmailAddress), null);

            this.userManager.Setup(_ => _.FindByEmailAsync(EmailAddress)).ReturnsAsync(new FifthweekUser()
            {
                Id       = UserId,
                UserName = Username
            });

            await this.AssertEmailSent(command);
        }
Exemplo n.º 15
0
            public async Task SetsTheEmailFieldWhenValidCredentialsAreProvided()
            {
                var scheduler  = new TestScheduler();
                var observable = arrangeCallToPasswordManagerWithValidCredentials();
                var observer   = TestScheduler.CreateObserver <string>();

                ViewModel.Email.Subscribe(observer);

                await ViewModel.StartPasswordManager();

                TestScheduler.Start();
                observer.Messages.AssertEqual(
                    ReactiveTest.OnNext(1, Email.Empty.ToString()),
                    ReactiveTest.OnNext(2, ValidEmail.ToString())
                    );
            }
        public async Task <PutFreeAccessUsersResult> PutFreeAccessList(string blogId, [FromBody] FreeAccessUsersData data)
        {
            blogId.AssertUrlParameterProvided("blogId");
            data.AssertBodyProvided("blogData");

            if (data.Emails == null)
            {
                data.Emails = new List <string>();
            }

            var validEmails   = new List <ValidEmail>();
            var invalidEmails = new HashSet <Email>();

            foreach (var email in data.Emails)
            {
                if (string.IsNullOrWhiteSpace(email))
                {
                    continue;
                }

                ValidEmail validEmail;
                if (ValidEmail.TryParse(email, out validEmail))
                {
                    validEmails.Add(validEmail);
                }
                else
                {
                    invalidEmails.Add(new Email(email));
                }
            }

            var requester = await this.requesterContext.GetRequesterAsync();

            var blogIdObject = new BlogId(blogId.DecodeGuid());

            await this.updateFreeAccessUsers.HandleAsync(new UpdateFreeAccessUsersCommand(
                                                             requester,
                                                             blogIdObject,
                                                             validEmails));

            return(new PutFreeAccessUsersResult(invalidEmails.ToList()));
        }
Exemplo n.º 17
0
        public async Task WhenPostingUserRegistration_ItShouldIssueRegisterUserCommand()
        {
            var registration = NewRegistrationData();

            var command = new RegisterUserCommand(
                UserId,
                registration.ExampleWork,
                ValidEmail.Parse(registration.Email),
                ValidUsername.Parse(registration.Username),
                ValidPassword.Parse(registration.Password),
                false);

            this.guidCreator.Setup(_ => _.CreateSqlSequential()).Returns(UserId.Value);
            this.registerUser.Setup(v => v.HandleAsync(command)).Returns(Task.FromResult(0));

            var result = await this.controller.PostRegistrationAsync(registration);

            Assert.IsInstanceOfType(result, typeof(OkResult));
            this.registerUser.Verify(v => v.HandleAsync(command));
            this.guidCreator.Verify(v => v.CreateSqlSequential());
        }
Exemplo n.º 18
0
        public async Task WhenNewEmailListIsSame_AndOrderIsDifferent_ItShouldNotModifyEmailsForBlog()
        {
            await this.DatabaseTestAsync(async testDatabase =>
            {
                this.target = new UpdateFreeAccessUsersDbStatement(testDatabase, this.requestSnapshot);

                await this.CreateDataAsync(testDatabase, true);
                await testDatabase.TakeSnapshotAsync();

                await this.target.ExecuteAsync(
                    CreatorId,
                    BlogId,
                    new List <ValidEmail>
                {
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**"),
                    ValidEmail.Parse("*****@*****.**"),
                });

                return(ExpectedSideEffects.None);
            });
        }
        public async Task <UpdateAccountSettingsResult> ExecuteAsync(
            UserId userId,
            ValidUsername newUsername,
            ValidEmail newEmail,
            ValidPassword newPassword,
            FileId newProfileImageFileId,
            string newSecurityStamp)
        {
            userId.AssertNotNull("userId");
            newUsername.AssertNotNull("newUsername");
            newEmail.AssertNotNull("newEmail");

            string passwordHash = null;

            if (newPassword != null)
            {
                passwordHash = this.userManager.PasswordHasher.HashPassword(newPassword.Value);
            }

            var query = new StringBuilder();

            query.AppendLine(@"DECLARE @emailConfirmed bit");

            query.Append(@"
                UPDATE dbo.AspNetUsers 
                SET 
                    Email = @Email, 
                    UserName = @Username, 
                    ProfileImageFileId = @ProfileImageFileId,
                    SecurityStamp = @SecurityStamp,
                    @emailConfirmed =
                    (
                        CASE
                            WHEN 
                                ((EmailConfirmed = 0) OR (Email != @Email))
                            THEN
                                0
                            ELSE
                                1
                        END
                    ),
                    EmailConfirmed = @emailConfirmed");

            if (passwordHash != null)
            {
                query.Append(@", PasswordHash=@PasswordHash");
            }

            query.AppendLine().Append(@"WHERE Id=@UserId").AppendLine();

            query.Append(@"select @emailConfirmed");

            bool emailConfirmed;

            using (var transaction = TransactionScopeBuilder.CreateAsync())
            {
                using (var connection = this.connectionFactory.CreateConnection())
                {
                    emailConfirmed = await connection.ExecuteScalarAsync <bool>(
                        query.ToString(),
                        new
                    {
                        UserId             = userId.Value,
                        Username           = newUsername.Value,
                        Email              = newEmail.Value,
                        PasswordHash       = passwordHash,
                        SecurityStamp      = newSecurityStamp,
                        ProfileImageFileId = newProfileImageFileId == null ? (Guid?)null : newProfileImageFileId.Value
                    });
                }

                await this.requestSnapshot.ExecuteAsync(userId, SnapshotType.Subscriber);

                transaction.Complete();
            }

            return(new UpdateAccountSettingsResult(emailConfirmed));
        }
Exemplo n.º 20
0
 public static RequestPasswordResetCommand NewCommand(PasswordResetRequestData data)
 {
     return(new RequestPasswordResetCommand(
                data.Email == null ? null : ValidEmail.Parse(data.Email),
                data.Username == null ? null : ValidUsername.Parse(data.Username)));
 }
Exemplo n.º 21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            //if (true)
            {
                if (Page.Request.HttpMethod == "POST")
                //if (true)
                {
                    SolicitudValidEmail solicitudEmail = null;
                    string Valor = "";
                    //Leer JSON
                    try
                    {
                        using (var streamReader = new System.IO.StreamReader(Request.GetBufferedInputStream()))
                        {
                            Valor = streamReader.ReadToEnd();
                        }
                        System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        solicitudEmail = jsonSerializer.Deserialize <SolicitudValidEmail>(Valor);
                    }
                    catch (Exception)
                    {
                        Valor = "";
                    }
                    //if (true)
                    if (Valor != "")
                    {
                        ValidEmail info     = new ValidEmail();
                        AppDatos   appDatos = new AppDatos();
                        info.conexion = ConfigurationManager.ConnectionStrings["Conexion_App"].ConnectionString;

                        info.Correo = solicitudEmail.correo;
                        //info.Correo = "*****@*****.**";
                        try
                        {
                            appDatos.ValidEmail(info);
                        }
                        catch (Exception ex)
                        {
                            info.resultado = ex.Message;
                            info.DatosJson = "No se encontró.";
                        }
                        Response.Clear();
                        Response.ContentType = "application/text;";
                        if (info.resultado == "REGOK")
                        {
                            Response.Write(info.DatosJson);
                        }
                        else
                        {
                            Response.Write("Error " + info.resultado);
                        }
                        Response.End();
                    }
                    else
                    {
                        Response.Clear();
                        Response.ContentType = "application/text;";
                        Response.Write("Error ID:000: Valores Incorrectos");
                        Response.End();
                    }
                }
                else
                {
                    Response.Clear();
                    Response.ContentType = "application/text;";
                    Response.Write("Error ID:002 Tipo Incorrecto");
                    Response.End();
                }
            }
        }
        public async Task WhenEmailIsFromFifthweekDomain_ItShouldNotReport()
        {
            await this.target.HandleAsync(new SendIdentifiedUserInformationCommand(Requester.Unauthenticated, false, ValidEmail.Parse("something" + Constants.FifthweekEmailDomain), Name, Username));

            // Test verification handled by strict behaviour.
        }