Пример #1
0
        public async Task GetProfileByPhone_Success(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());
            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var phone       = 79000000000;
            var userId      = 1;
            var accessToken = TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_VIEW_USERS);

            var accountMock = Mock.Get(container.Resolve <IAccountRepository>());

            accountMock.Setup(a => a.FindByPhone(phone)).ReturnsAsync(new Account {
                Id = userId, Phone = phone
            });

            var response = await browser.Get(UsersModule.GetUserByPhoneUrl.Replace("{phone}", phone.ToString()), with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
            });

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var result = response.Body.AsDataFormat <UserProfile>(format);

            Assert.Equal(userId, result.Id);
            Assert.Equal(phone.ToString(), result.Phone);
        }
Пример #2
0
        public async Task Email_ClientForceChangeEmailTest()
        {
            var testRequest = new ChangeEmailRequest("ru", "email", 1);

            var accountRepository     = container.Resolve <IAccountRepository>();
            var accountRepositoryMock = Mock.Get(accountRepository);

            accountRepositoryMock
            .Setup(s => s.FindByUserId(It.IsAny <int>()))
            .Returns <int>(x => Task.FromResult(new Account
            {
                Id = x
            }));

            using (var http = new HttpClient())
            {
                var client = new Domain0Client(TEST_URL, http);
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_FORCE_CHANGE_EMAIL));

                await client.ForceChangeEmailAsync(testRequest);

                accountRepositoryMock.Verify(ar =>
                                             ar.Update(It.Is <Account>(a =>
                                                                       a.Id == testRequest.UserId &&
                                                                       a.Email == testRequest.NewEmail)),
                                             Times.Once());
            }
        }
Пример #3
0
        public async Task Sms_ClientGetUserByIdTest()
        {
            var testId    = 1;
            var testPhone = 321;

            var accountRepository     = container.Resolve <IAccountRepository>();
            var accountRepositoryMock = Mock.Get(accountRepository);

            accountRepositoryMock
            .Setup(s => s.FindByUserId(It.IsAny <int>()))
            .Returns <int>(x => Task.FromResult(new Account
            {
                Id    = x,
                Phone = testPhone
            }));

            using (var http = new HttpClient())
            {
                var client = new Domain0Client(TEST_URL, http);
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, testId, TokenClaims.CLAIM_PERMISSIONS_VIEW_USERS));

                var profile = await client.GetUserByIdAsync(testId);

                Assert.Equal(testPhone.ToString(), profile.Phone);
                Assert.Equal(testId, profile.Id);
                accountRepositoryMock.Verify(ar =>
                                             ar.FindByUserId(It.Is <int>(id => id == testId)),
                                             Times.Once());
            }
        }
Пример #4
0
        public async Task GetProfilesByFilter_BadRequest(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());
            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var userId      = 1;
            var accessToken = TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_VIEW_PROFILE);

            var accountMock = Mock.Get(container.Resolve <IAccountRepository>());

            accountMock.Setup(a => a.FindByUserIds(It.IsAny <IEnumerable <int> >())).Returns <IEnumerable <int> >(ids => Task.FromResult(ids.Select(id => new Account {
                Id = id
            }).ToArray()));

            var response = await browser.Post(UsersModule.GetUsersByFilterUrl, with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
                with.JsonBody("{userIds:['qwe','rty']}");
            });

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
Пример #5
0
        public async Task UpdateUser_Success(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());
            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var userUpdate = new UserProfile
            {
                Id          = 343,
                Description = "newDescription",
                Email       = "email",
                Phone       = "412312",
                Name        = "name"
            };

            var accessToken = TestContainerBuilder.BuildToken(
                container,
                userUpdate.Id,
                TokenClaims.CLAIM_PERMISSIONS_EDIT_USERS);

            var accountMock = Mock.Get(container.Resolve <IAccountRepository>());

            accountMock.Setup(a => a.FindByUserId(userUpdate.Id)).ReturnsAsync(
                new Account
            {
                Id          = userUpdate.Id,
                Email       = userUpdate.Email,
                Phone       = decimal.Parse(userUpdate.Phone),
                Name        = userUpdate.Name,
                Description = userUpdate.Description,
            });

            var response = await browser.Post(UsersModule.PostUserUrl.Replace("{id}", userUpdate.Id.ToString()), with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
                with.DataFormatBody(format, userUpdate);
            });

            accountMock.Verify(ar => ar.FindByUserId(userUpdate.Id), Times.Once);
            accountMock.Verify(ar => ar.Update(
                                   It.Is <Account>(a => a.Id == userUpdate.Id &&
                                                   a.Description == userUpdate.Description &&
                                                   a.Email == userUpdate.Email &&
                                                   a.Name == userUpdate.Name &&
                                                   a.Phone.ToString() == userUpdate.Phone)),
                               Times.Once);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var result = response.Body.AsDataFormat <UserProfile>(format);

            Assert.Equal(userUpdate.Id, result.Id);
            Assert.Equal(userUpdate.Description, result.Description);
            Assert.Equal(userUpdate.Email, result.Email);
            Assert.Equal(userUpdate.Phone, result.Phone);
            Assert.Equal(userUpdate.Name, result.Name);
        }
Пример #6
0
        public async Task Admin_ClientRolePermissionOperationsTest()
        {
            var roleId = 333;
            var ids    = new IdArrayRequest(new List <int> {
                1, 2, 3
            });

            var roleRepository     = container.Resolve <IRoleRepository>();
            var roleRepositoryMock = Mock.Get(roleRepository);

            var permissionRepository     = container.Resolve <IPermissionRepository>();
            var permissionRepositoryMock = Mock.Get(permissionRepository);

            permissionRepositoryMock
            .Setup(x => x.FindRolePermissionsByRoleIds(It.IsAny <List <int> >()))
            .ReturnsAsync(
                ids.Ids.Select(x =>
                               new Repository.Model.RolePermission
            {
                Id = x
            })
                .ToArray());

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_ADMIN));
                var client = new Domain0Client(TEST_URL, http);

                await client.AddRolePermissionsAsync(roleId, ids);

                permissionRepositoryMock.Verify(t =>
                                                t.AddRolePermissions(
                                                    roleId,
                                                    It.Is <int[]>(rids => rids.SequenceEqual(ids.Ids))),
                                                Times.Once);

                var rolePermissions = await client.LoadRolePermissionsAsync(roleId);

                Assert.True(ids.Ids.SequenceEqual(rolePermissions.Select(x => x.Id.GetValueOrDefault())));
                permissionRepositoryMock.Verify(t => t.FindRolePermissionsByRoleIds(It.Is <List <int> >(roleIds => roleIds.Contains(roleId))), Times.Once);

                await client.RemoveRolePermissionsAsync(roleId, ids);

                permissionRepositoryMock.Verify(t => t.RemoveRolePermissions(
                                                    roleId,
                                                    It.Is <int[]>(rids => rids.SequenceEqual(ids.Ids))),
                                                Times.Once);
            }
        }
Пример #7
0
        public async Task Sms_ClientForceCreateUserTest()
        {
            var testRequest = new ForceCreateUserRequest(
                true, "customTemplate", "", "ru-RU", "userName", 123456, new List <string> {
                "1", "2", "3"
            });

            var accountRepository     = container.Resolve <IAccountRepository>();
            var accountRepositoryMock = Mock.Get(accountRepository);

            accountRepositoryMock
            .Setup(s => s.FindByPhone(It.IsAny <decimal>()))
            .ReturnsAsync((Account)null);


            var roleRepository     = container.Resolve <IRoleRepository>();
            var roleRepositoryMock = Mock.Get(roleRepository);

            roleRepositoryMock
            .Setup(s => s.GetByRoleNames(It.IsAny <string[]>()))
            .ReturnsAsync(testRequest.Roles.Select(x => new Repository.Model.Role()
            {
                Name = x
            }).ToArray());


            using (var http = new HttpClient())
            {
                var client = new Domain0Client(TEST_URL, http);
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_FORCE_CREATE_USER));

                await client.ForceCreateUserAsync(testRequest);

                accountRepositoryMock.Verify(ar =>
                                             ar.Insert(It.Is <Account>(a =>
                                                                       a.Name == testRequest.Name &&
                                                                       a.Phone == testRequest.Phone)),
                                             Times.Once());

                roleRepositoryMock.Verify(rr =>
                                          rr.GetByRoleNames(It.Is <string[]>(s => testRequest.Roles.SequenceEqual(s))),
                                          Times.Once);
            }
        }
Пример #8
0
        public async Task Admin_ClientUserPermissionOperationsTest()
        {
            var permissionId = 888;
            var userId       = 777;
            var ids          = new IdArrayRequest(new List <int> {
                1, 2, 3
            });

            var permissionRepository     = container.Resolve <IPermissionRepository>();
            var permissionRepositoryMock = Mock.Get(permissionRepository);

            permissionRepositoryMock
            .Setup(x => x.FindUserPermissionsByUserIds(It.IsAny <List <int> >()))
            .ReturnsAsync(new[] { new Repository.Model.UserPermission()
                                  {
                                      Id = permissionId
                                  } });

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_ADMIN));
                var client = new Domain0Client(TEST_URL, http);

                await client.AddUserPermissionsAsync(userId, ids);

                permissionRepositoryMock.Verify(t => t.AddUserPermission(userId, It.IsAny <int[]>()), Times.Once);

                var permissions = await client.LoadPermissionsByUserFilterAsync(new UserPermissionFilter(new List <int> {
                    userId
                }));

                permissionRepositoryMock.Verify(t => t.FindUserPermissionsByUserIds(It.Is <List <int> >(userIds => userIds.Contains(userId))), Times.Once);
                Assert.Equal(permissionId, permissions.FirstOrDefault()?.Id);

                await client.RemoveUserPermissionsAsync(userId, ids);

                permissionRepositoryMock.Verify(t => t.RemoveUserPermissions(userId, It.IsAny <int[]>()), Times.Once);
            }
        }
Пример #9
0
        public async Task GetProfileByUserId_NotFound(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());
            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var userId      = 1;
            var accessToken = TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_VIEW_USERS);

            var accountMock = Mock.Get(container.Resolve <IAccountRepository>());

            accountMock.Setup(a => a.FindByUserId(userId)).ReturnsAsync((Account)null);

            var response = await browser.Get(UsersModule.GetUserByIdUrl.Replace("{id}", userId.ToString()), with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
            });

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
Пример #10
0
        public async Task Sms_ClientGetUserByFilterTest()
        {
            var filter = new UserProfileFilter(new List <int> {
                1, 2, 3
            });

            var accountRepository     = container.Resolve <IAccountRepository>();
            var accountRepositoryMock = Mock.Get(accountRepository);

            accountRepositoryMock
            .Setup(s => s.FindByUserIds(It.IsAny <IEnumerable <int> >()))
            .Returns <IEnumerable <int> >(x => Task.FromResult(
                                              x.Select(id =>
                                                       new Account
            {
                Id    = id,
                Phone = id
            })
                                              .ToArray()));

            using (var http = new HttpClient())
            {
                var client = new Domain0Client(TEST_URL, http);
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_VIEW_PROFILE));

                var profiles = await client.GetUserByFilterAsync(filter);

                Assert.True(profiles.Select(p => p.Id).SequenceEqual(filter.UserIds));

                accountRepositoryMock.Verify(ar =>
                                             ar.FindByUserIds(It.Is <IEnumerable <int> >(ids => ids.SequenceEqual(filter.UserIds))),
                                             Times.Once());
            }
        }
Пример #11
0
        public async Task Admin_ClientMessageTemplateOperationsTest()
        {
            var testMessageTemplate = new Api.Client.MessageTemplate(
                "description",
                123,
                321,
                "en",
                "template",
                "{0}{1}",
                "sms");


            var messageTemplateRepository     = container.Resolve <IMessageTemplateRepository>();
            var messageTemplateRepositoryMock = Mock.Get(messageTemplateRepository);

            messageTemplateRepositoryMock
            .Setup(x => x.Insert(It.IsAny <Repository.Model.MessageTemplate>()))
            .ReturnsAsync(testMessageTemplate.Id.GetValueOrDefault());

            messageTemplateRepositoryMock
            .Setup(x => x.FindByIds(It.IsAny <IEnumerable <int> >()))
            .ReturnsAsync(new []
            {
                new Repository.Model.MessageTemplate
                {
                    Id          = testMessageTemplate.Id.GetValueOrDefault(),
                    Description = testMessageTemplate.Description,
                    Locale      = testMessageTemplate.Locale,
                    Name        = testMessageTemplate.Name,
                    Template    = testMessageTemplate.Template,
                    Type        = testMessageTemplate.Type
                }
            });

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_ADMIN));
                var client = new Domain0Client(TEST_URL, http);

                var id = await client.CreateMessageTemplateAsync(testMessageTemplate);

                Assert.Equal(testMessageTemplate.Id, id);

                messageTemplateRepositoryMock.Verify(t =>
                                                     t.Insert(It.Is <Repository.Model.MessageTemplate>(x =>
                                                                                                       x.Id == testMessageTemplate.Id &&
                                                                                                       x.Description == testMessageTemplate.Description &&
                                                                                                       x.Locale == testMessageTemplate.Locale &&
                                                                                                       x.Name == testMessageTemplate.Name &&
                                                                                                       x.Template == testMessageTemplate.Template &&
                                                                                                       x.Type == testMessageTemplate.Type)),
                                                     Times.Once);

                var templates = await client.LoadMessageTemplateAsync(testMessageTemplate.Id.GetValueOrDefault());

                Assert.Single(templates);
                Assert.Equal(templates[0].Id, testMessageTemplate.Id);
                Assert.Equal(templates[0].Description, testMessageTemplate.Description);
                Assert.Equal(templates[0].Locale, testMessageTemplate.Locale);
                Assert.Equal(templates[0].Name, testMessageTemplate.Name);
                Assert.Equal(templates[0].Template, testMessageTemplate.Template);
                Assert.Equal(templates[0].Type, testMessageTemplate.Type);
                messageTemplateRepositoryMock.Verify(mt =>
                                                     mt.FindByIds(It.Is <IEnumerable <int> >(x => x.Contains(testMessageTemplate.Id.GetValueOrDefault()))),
                                                     Times.Once);

                templates = await client.LoadMessageTemplatesByFilterAsync(
                    new MessageTemplateFilter(new List <int>(testMessageTemplate.Id.GetValueOrDefault())));

                messageTemplateRepositoryMock.Verify(mt =>
                                                     mt.FindByIds(It.Is <IEnumerable <int> >(x => x.Contains(testMessageTemplate.Id.GetValueOrDefault()))),
                                                     Times.Once);
                Assert.Single(templates);
                Assert.Equal(templates[0].Id, testMessageTemplate.Id);
                Assert.Equal(templates[0].Description, testMessageTemplate.Description);
                Assert.Equal(templates[0].Locale, testMessageTemplate.Locale);
                Assert.Equal(templates[0].Name, testMessageTemplate.Name);
                Assert.Equal(templates[0].Template, testMessageTemplate.Template);
                Assert.Equal(templates[0].Type, testMessageTemplate.Type);

                await client.RemoveMessageTemplateAsync(testMessageTemplate.Id.GetValueOrDefault());

                messageTemplateRepositoryMock.Verify(mt =>
                                                     mt.Delete(It.Is <int>(x => x == testMessageTemplate.Id.GetValueOrDefault())),
                                                     Times.Once);

                var changedMessageTemplate = new Api.Client.MessageTemplate(
                    "changed",
                    123,
                    321,
                    "en",
                    "template",
                    "{0}{1}",
                    "sms");


                await client.UpdateMessageTemplateAsync(changedMessageTemplate);

                messageTemplateRepositoryMock.Verify(t =>
                                                     t.Update(It.Is <Repository.Model.MessageTemplate>(x =>
                                                                                                       x.Id == changedMessageTemplate.Id &&
                                                                                                       x.Description == changedMessageTemplate.Description &&
                                                                                                       x.Locale == changedMessageTemplate.Locale &&
                                                                                                       x.Name == changedMessageTemplate.Name &&
                                                                                                       x.Template == changedMessageTemplate.Template &&
                                                                                                       x.Type == changedMessageTemplate.Type)),
                                                     Times.Once);
            }
        }
Пример #12
0
        public async Task Admin_ClientPasswordOperationsTest()
        {
            var userId = 85;

            var accountRepository     = container.Resolve <IAccountRepository>();
            var accountRepositoryMock = Mock.Get(accountRepository);

            var tokenRegistryRepository     = container.Resolve <ITokenRegistrationRepository>();
            var tokenRegistryRepositoryMock = Mock.Get(tokenRegistryRepository);

            var passwordGenerator = container.Resolve <IPasswordGenerator>();
            var passwordMock      = Mock.Get(passwordGenerator);

            passwordMock.Setup(p => p.CheckPassword(
                                   It.IsAny <string>(),
                                   It.IsAny <string>()))
            .Returns(true);

            var messageTemplateRepository = container.Resolve <IMessageTemplateRepository>();
            var messageTemplateMock       = Mock.Get(messageTemplateRepository);

            messageTemplateMock
            .Setup(r => r.GetTemplate(
                       It.IsAny <MessageTemplateName>(),
                       It.IsAny <CultureInfo>(),
                       It.IsAny <MessageTemplateType>(),
                       It.IsAny <int>()))
            .Returns <MessageTemplateName, CultureInfo, MessageTemplateType, int>((n, l, t, e) => Task.FromResult("{0} {1}"));


            accountRepositoryMock
            .Setup(x => x.FindByUserId(It.IsAny <int>()))
            .ReturnsAsync(new Account {
                Id = userId
            });

            accountRepositoryMock
            .Setup(x => x.FindByPhone(It.IsAny <decimal>()))
            .Returns <decimal>(x =>
                               Task.FromResult(new Account {
                Phone = x
            }));

            accountRepositoryMock
            .Setup(x => x.FindByLogin(It.IsAny <string>()))
            .Returns <string>(x =>
                              Task.FromResult(new Account {
                Login = x
            }));


            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_BASIC));

                var client = new Domain0Client(TEST_URL, http);

                await client.ChangePasswordAsync(new ChangePasswordRequest("new", "old"));

                accountRepositoryMock
                .Verify(x =>
                        x.FindByUserId(It.Is <int>(id => id == userId)),
                        Times.Once);
                tokenRegistryRepositoryMock.Verify(x => x.RevokeByUserId(userId), Times.Exactly(1));

                await client.ChangeMyPasswordAsync(new ChangePasswordRequest("new", "old"));

                accountRepositoryMock
                .Verify(x =>
                        x.FindByUserId(It.Is <int>(id => id == userId)),
                        Times.Exactly(2));
                tokenRegistryRepositoryMock.Verify(x => x.RevokeByUserId(userId), Times.Exactly(2));

                var resetPhone = 123;
                await client.RequestResetPasswordAsync(resetPhone);

                accountRepositoryMock
                .Verify(x => x.FindByPhone(It.Is <decimal>(phone => phone == resetPhone)), Times.Once);

                var resetEmail = "email";
                await client.RequestResetPasswordByEmailAsync(new RegisterRequest("email"));

                accountRepositoryMock
                .Verify(x => x.FindByLogin(It.Is <string>(email => email == resetEmail)), Times.Once);
            }
        }
Пример #13
0
        public async Task Admin_ClientApplicationsOperationsTest()
        {
            var applicationId      = 11;
            var testApplication    = new Api.Client.Application("description", applicationId, "name");
            var updatedApplication = new Api.Client.Application("update description", applicationId, "name");

            var applicationRepository     = container.Resolve <IApplicationRepository>();
            var applicationRepositoryMock = Mock.Get(applicationRepository);

            applicationRepositoryMock
            .Setup(x => x.Insert(It.IsAny <Application>()))
            .ReturnsAsync(applicationId);

            applicationRepositoryMock
            .Setup(x => x.FindByIds(It.IsAny <IEnumerable <int> >()))
            .Returns <IEnumerable <int> >(x =>
                                          Task.FromResult(x.Select(a => new Application {
                Id = a
            }).ToArray()));

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer",
                                                  TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_ADMIN));

                var client = new Domain0Client(TEST_URL, http);

                var id = await client.CreateApplicationAsync(testApplication);

                Assert.Equal(id, applicationId);
                applicationRepositoryMock.Verify(x => x.Insert(It.IsAny <Application>()), Times.Once());

                var loadedApplications = await client.LoadApplicationAsync(applicationId);

                Assert.Contains(loadedApplications, a => a.Id == applicationId);
                applicationRepositoryMock.Verify(x => x.FindByIds(It.IsAny <IEnumerable <int> >()), Times.Once());

                await client.UpdateApplicationAsync(updatedApplication);

                applicationRepositoryMock.Verify(x =>
                                                 x.Update(It.Is <Application>(a =>
                                                                              a.Id == updatedApplication.Id &&
                                                                              a.Description == updatedApplication.Description)),
                                                 Times.Once());

                var filteredApplications = await client.LoadApplicationsByFilterAsync(new ApplicationFilter(new List <int> {
                    3
                }));

                Assert.Contains(filteredApplications, a => a.Id == 3);
                applicationRepositoryMock.Verify(x =>
                                                 x.FindByIds(
                                                     It.Is <IEnumerable <int> >(e => e.Contains(3))),
                                                 Times.Once());

                await client.RemoveApplicationAsync(applicationId);

                applicationRepositoryMock.Verify(x =>
                                                 x.Delete(It.Is <int>(deletedId => deletedId == applicationId)),
                                                 Times.Once());
            }
        }
Пример #14
0
        public async Task ForceCreateUser_SendEmail_StandardTemplate(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());
            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var userId = 1;
            var email  = "email";
            var roles  = new List <string> {
                "role1", "role2"
            };
            var accessToken = TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_FORCE_CREATE_USER);

            var accountRepository = container.Resolve <IAccountRepository>();
            var accountMock       = Mock.Get(accountRepository);
            var registers         = new Dictionary <string, Account>();

            accountMock
            .Setup(a => a.Insert(It.IsAny <Account>()))
            .Callback <Account>(a => registers[a.Email] = a)
            .Returns(Task.FromResult(1));
            accountMock
            .Setup(a => a.FindByLogin(email))
            .Returns <string>(p =>
                              Task.FromResult(registers.TryGetValue(p, out var acc)
                        ? acc
                        : null));

            var roleRepository = container.Resolve <IRoleRepository>();
            var roleMock       = Mock.Get(roleRepository);

            roleMock.Setup(r => r.GetByRoleNames(It.IsAny <string[]>())).ReturnsAsync(roles.Select(role => new Repository.Model.Role {
                Name = role
            }).ToArray());

            var passwordGenerator = container.Resolve <IPasswordGenerator>();
            var passwordMock      = Mock.Get(passwordGenerator);

            passwordMock.Setup(p => p.GeneratePassword()).Returns("password");

            var messageTemplateRepository = container.Resolve <IMessageTemplateRepository>();
            var messageTemplate           = Mock.Get(messageTemplateRepository);

            messageTemplate.Setup(r =>
                                  r.GetTemplate(
                                      MessageTemplateName.WelcomeTemplate,
                                      It.IsAny <CultureInfo>(),
                                      It.IsAny <MessageTemplateType>(),
                                      It.IsAny <int>()))
            .ReturnsAsync("hello {1} {0}!");
            messageTemplate.Setup(r =>
                                  r.GetTemplate(
                                      MessageTemplateName.WelcomeSubjectTemplate,
                                      It.IsAny <CultureInfo>(),
                                      It.IsAny <MessageTemplateType>(),
                                      It.IsAny <int>()))
            .ReturnsAsync("Subject!");

            var response = await browser.Put(
                EmailModule.ForceCreateUserUrl,
                with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
                with.DataFormatBody(
                    format,
                    new ForceCreateEmailUserRequest
                {
                    BlockEmailSend = false,
                    Email          = email,
                    Name           = "test",
                    Roles          = roles,
                });
            });

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var emailClient = container.Resolve <IEmailClient>();
            var emailMock   = Mock.Get(emailClient);

            emailMock.Verify(s => s.Send("Subject!", email, "hello password " + email + "!"));

            var environmentRepositoryMock = Mock.Get(container.Resolve <IEnvironmentRepository>());

            environmentRepositoryMock
            .Verify(
                callTo => callTo.SetUserEnvironment(It.IsAny <int>(), 123),
                Times.Once);
        }
Пример #15
0
        public async Task RequestChangeEmail_Success(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());

            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var accountId   = 321;
            var userId      = 1;
            var email       = "email";
            var newEmail    = "newEmail";
            var password    = "******";
            var pin         = "333";
            var accessToken = TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_BASIC);

            var account = new Account {
                Id = accountId, Login = email, Email = email, Password = password
            };
            var accountMock = Mock.Get(container.Resolve <IAccountRepository>());

            accountMock.Setup(a => a.FindByUserId(userId)).ReturnsAsync(account);

            var emailRequestRepository = Mock.Get(container.Resolve <IEmailRequestRepository>());

            emailRequestRepository
            .Setup(sr => sr.PickByUserId(
                       It.Is <int>(x => x == userId)))
            .ReturnsAsync(new EmailRequest
            {
                Email    = newEmail,
                UserId   = userId,
                Password = pin
            });

            var authGenerator = Mock.Get(container.Resolve <IPasswordGenerator>());

            authGenerator.Setup(a =>
                                a.CheckPassword(It.IsAny <string>(), It.IsAny <string>())).Returns <string, string>((pasd, hash) => pasd == hash);
            authGenerator.Setup(a => a.GeneratePassword())
            .Returns(pin);

            var messageTemplate = Mock.Get(container.Resolve <IMessageTemplateRepository>());

            messageTemplate
            .Setup(r => r.GetTemplate(
                       It.IsAny <MessageTemplateName>(),
                       It.IsAny <CultureInfo>(),
                       It.IsAny <MessageTemplateType>(),
                       It.IsAny <int>()))
            .Returns <MessageTemplateName, CultureInfo, MessageTemplateType, int>((n, l, t, e) =>
            {
                if (n == MessageTemplateName.RequestEmailChangeTemplate)
                {
                    return(Task.FromResult("Your password is: {0} will valid for {1} min"));
                }

                if (n == MessageTemplateName.RequestEmailChangeSubjectTemplate)
                {
                    return(Task.FromResult("Subject"));
                }

                throw new NotImplementedException();
            });

            var emailClient = Mock.Get(container.Resolve <IEmailClient>());

            var responseToChangeRequest = await browser.Post(
                EmailModule.RequestChangeEmailUrl,
                with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
                with.DataFormatBody(format,
                                    new ChangeEmailUserRequest
                {
                    Password = password,
                    Email    = newEmail
                });
            });

            Assert.Equal(HttpStatusCode.NoContent, responseToChangeRequest.StatusCode);

            authGenerator.Verify(ag =>
                                 ag.CheckPassword(
                                     It.Is <string>(x => x == password),
                                     It.Is <string>(x => x == password)),
                                 Times.Once);

            emailRequestRepository.Verify(
                srr => srr.Save(
                    It.Is <EmailRequest>(r =>
                                         r.UserId == userId &&
                                         r.Email == newEmail &&
                                         r.Password == pin)),
                Times.Once);

            messageTemplate.Verify(mtr =>
                                   mtr.GetTemplate(
                                       It.Is <MessageTemplateName>(mt => mt == MessageTemplateName.RequestEmailChangeTemplate),
                                       It.IsAny <CultureInfo>(),
                                       It.Is <MessageTemplateType>(mtt => mtt == MessageTemplateType.email),
                                       It.IsAny <int>()),
                                   Times.Once);

            emailClient.Verify(sc =>
                               sc.Send(
                                   It.IsAny <string>(),
                                   It.Is <string>(x => x == newEmail),
                                   It.IsAny <string>()),
                               Times.Once);


            var responseToCommitRequest = await browser.Post(
                EmailModule.CommitChangeEmailUrl,
                with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
                with.Query("code", pin);
            });

            Assert.Equal(HttpStatusCode.NoContent, responseToCommitRequest.StatusCode);

            accountMock.Verify(ar =>
                               ar.Update(
                                   It.Is <Account>(a =>
                                                   a.Id == accountId &&
                                                   a.Login == newEmail &&
                                                   a.Email == newEmail)),
                               Times.Once);
        }
Пример #16
0
        public async Task ForceResetPassword_Success(DataFormat format)
        {
            var container = TestContainerBuilder.GetContainer(builder =>
                                                              builder.RegisterType <SymmetricKeyTokenGenerator>().As <ITokenGenerator>().SingleInstance());
            var bootstrapper = new Domain0Bootstrapper(container);
            var browser      = new Browser(bootstrapper);

            var userId      = 1;
            var email       = "email";
            var password    = "******";
            var accessToken = TestContainerBuilder.BuildToken(container, userId, TokenClaims.CLAIM_PERMISSIONS_FORCE_PASSWORD_RESET);

            var tokenRegistrationRepository = container.Resolve <ITokenRegistrationRepository>();
            var tokenRegistrationMock       = Mock.Get(tokenRegistrationRepository);

            var accountRepository = container.Resolve <IAccountRepository>();
            var accountMock       = Mock.Get(accountRepository);

            accountMock
            .Setup(a => a.FindByLogin(email))
            .ReturnsAsync(new Account
            {
                Id       = userId,
                Email    = email,
                Login    = email,
                Password = password
            });

            var passwordGenerator = container.Resolve <IPasswordGenerator>();
            var passwordMock      = Mock.Get(passwordGenerator);

            passwordMock.Setup(p => p.GeneratePassword()).Returns(password);
            passwordMock.Setup(a => a.HashPassword(It.IsAny <string>())).Returns <string>(p => p);

            var messageTemplateRepository = container.Resolve <IMessageTemplateRepository>();
            var messageTemplate           = Mock.Get(messageTemplateRepository);

            messageTemplate.Setup(r =>
                                  r.GetTemplate(
                                      MessageTemplateName.ForcePasswordResetTemplate,
                                      It.IsAny <CultureInfo>(),
                                      It.IsAny <MessageTemplateType>(),
                                      It.IsAny <int>())
                                  )
            .ReturnsAsync("hello, your new password is {0}!");
            messageTemplate.Setup(r =>
                                  r.GetTemplate(
                                      MessageTemplateName.ForcePasswordResetSubjectTemplate,
                                      It.IsAny <CultureInfo>(),
                                      It.IsAny <MessageTemplateType>(),
                                      It.IsAny <int>()))
            .ReturnsAsync("subject");

            var response = await browser.Post(
                UsersModule.ForceResetUserPasswordUrl,
                with =>
            {
                with.Accept(format);
                with.Header("Authorization", $"Bearer {accessToken}");
                with.DataFormatBody(
                    format,
                    new ForceResetPasswordRequest
                {
                    Email = email
                });
            });

            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);

            accountMock.Verify(am => am.FindByLogin(email));
            accountMock.Verify(am => am.Update(
                                   It.Is <Account>(a => a.Password == password)));
            messageTemplate.Verify(mt => mt.GetTemplate(
                                       MessageTemplateName.ForcePasswordResetTemplate,
                                       It.IsAny <CultureInfo>(),
                                       MessageTemplateType.email,
                                       It.IsAny <int>()));
            messageTemplate.Verify(mt => mt.GetTemplate(
                                       MessageTemplateName.ForcePasswordResetSubjectTemplate,
                                       It.IsAny <CultureInfo>(),
                                       MessageTemplateType.email,
                                       It.IsAny <int>()));

            var emaClient = container.Resolve <IEmailClient>();
            var smsMock   = Mock.Get(emaClient);

            smsMock.Verify(s =>
                           s.Send("subject", email, "hello, your new password is password!"));

            tokenRegistrationMock.Verify(x => x.RevokeByUserId(userId), Times.Once);
        }