コード例 #1
0
        public void TestUserAddSuccess()
        {
            var provider = new UserProvider();
            var request = new UserBuilder().TestUser().BuildRequest();

            var response = provider.AddUser(request);
            var found = provider.GetUser(response.Id);

            Assert.IsNotNull(found);
        }
コード例 #2
0
ファイル: UserController.cs プロジェクト: brianium/today
        public ActionResult Register(RegisterInput input)
        {
            if (!ModelState.IsValid) return View(input);

            var user = new UserBuilder(input.FirstName, input.LastName, input.Email, input.Password).GetInstance();

            Repo.Store(user);

            return AuthenticateAndRedirect(input.Email);
        }
コード例 #3
0
        public void Create_when_SetPassword_has_not_been_called_throws_InvalidOperationException()
        {
            // arrange
            ICryptoService cryptoService = MockRepository.GenerateStub<ICryptoService>();

            UserBuilder builder = new UserBuilder(cryptoService)
                .SetEmail("Email")
                .SetName("Name")
                .SetSurname("Surname");

            // assert
            Assert.Throws<InvalidOperationException>(() => builder.Create());
        }
コード例 #4
0
        public User Create(string email, string name, string surname, string password)
        {
            UserBuilder builder = new UserBuilder(this.cryptoService);

            User user = builder
                .SetEmail(email)
                .SetName(name)
                .SetSurname(surname)
                .SetPassword(password)
                .Create();

            User createdUser = this.userRepository.Save(user);

            return createdUser;
        }
コード例 #5
0
        public void User_SaveLoad()
        {
            var user = new UserBuilder().Value();

            Repository.Save(user);

            Repository.Flush();
            Repository.Clear();

            var loadedUser = Repository.Load<User>(user.Id);

            loadedUser.Id.Should().Be(user.Id);
            loadedUser.Name.Should().Be(user.Name);
            loadedUser.LastLoggedIn.Should().Be(user.LastLoggedIn);
        }
コード例 #6
0
        public async Task <User> Register(string username, string email, string password)
        {
            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);
            }

            var passwordSalt       = Utils.CreateSalt();
            var saltedPasswordHash = Utils.GenerateHash(password, passwordSalt);

            var user = new UserBuilder()
                       .SetUserData(username, email)
                       .SetPassword(saltedPasswordHash, passwordSalt)
                       .Build();

            database.UserRepository.Add(user);

            if (await database.Complete())
            {
                var registerToken = Token.Create(TokenType.Register);
                user.Tokens.Add(registerToken);

                if (await database.Complete())
                {
                    string encryptedToken = cryptoService.Encrypt(registerToken.Code);
                    string callbackUrl    = $"{Configuration.GetValue<string>(AppSettingsKeys.ServerAddress)}Auth/ConfirmAccount?email={user.Email}&token={encryptedToken}";
                    return(await emailSender.Send(Constants.ActivationAccountEmail(email, username, callbackUrl)) ? user : null);
                }
                return(null);
            }
            else
            {
                Alertify.Push("Creating account failed", AlertType.Error);
                return(null);
            }
        }
コード例 #7
0
        public async Task Login_InvalidPassword_ReturnsNull()
        {
            // Arrange
            const string userName = "******";
            const string password = "******";
            var          user     = new UserBuilder()
                                    .WithName(new Name(userName))
                                    .Build();

            _userRepositoryMock
            .Setup(mock => mock.Get(It.IsAny <Name>()))
            .ReturnsAsync(user);

            // Act
            var claimsPrincipal = await _authenticationService.Login(userName, password);

            // Assert
            Assert.IsNull(claimsPrincipal);
        }
コード例 #8
0
    private static Mock <IBackOfficeSecurityAccessor> CreateMockBackOfficeSecurityAccessor(
        bool currentUserIsAuthenticated, bool currentUserIsApproved)
    {
        var user = new UserBuilder()
                   .WithIsApproved(currentUserIsApproved)
                   .Build();
        var mockBackOfficeSecurity = new Mock <IBackOfficeSecurity>();

        mockBackOfficeSecurity.Setup(x => x.IsAuthenticated()).Returns(currentUserIsAuthenticated);
        if (currentUserIsAuthenticated)
        {
            mockBackOfficeSecurity.Setup(x => x.CurrentUser).Returns(user);
        }

        var mockBackOfficeSecurityAccessor = new Mock <IBackOfficeSecurityAccessor>();

        mockBackOfficeSecurityAccessor.Setup(x => x.BackOfficeSecurity).Returns(mockBackOfficeSecurity.Object);
        return(mockBackOfficeSecurityAccessor);
    }
コード例 #9
0
        public void Should_find_player_by_bot_id()
        {
            var user = new UserBuilder().With(u => u.Id, "guid").BuildAndSave();

            new PlayerBuilder()
            .With(p => p.Id, 23)
            .With(p => p.User, user)
            .With(p => p.BotId, 5)
            .BuildAndSave();

            var cmd = new GetPlayerByBotId {
                BotId = 5
            };

            var foundPlayer = DomainRegistry.Repository.FindSingle(cmd);

            Assert.That(foundPlayer.Id, Is.EqualTo(23));
            Assert.That(foundPlayer.BotId, Is.EqualTo(5));
        }
コード例 #10
0
        public void should_throw_exception_when_current_token_is_inactive()
        {
            List <RefreshToken> tokens = new() { new RefreshTokenBuilder().Inactive().Build() };
            User   user        = new UserBuilder().WithRefreshTokens(tokens).Build();
            UserDb userFromDb  = user.Map();
            var    usersFromDb = new List <UserDb> {
                userFromDb
            };
            DateTime now = DateTime.UtcNow;

            _users.Setup(n => n.Get(It.IsAny <Expression <Func <UserDb, bool> > >(), null, "")).Returns(usersFromDb);
            _mapper.Setup(n => n.Map <User>(userFromDb)).Returns(user);
            _dateTimeProvider.Setup(n => n.Now).Returns(now);

            _sut.Invoking(n => n.RefreshToken(tokens.Last().Token, IP_ADDRESS))
            .Should()
            .Throw <Exception>()
            .WithMessage(ApiResponses.InvalidToken);
        }
コード例 #11
0
        public void ShouldLoginUser()
        {
            UserLoginRequest request = CreateRequest();
            var hashedPassword       = "******";
            var user = UserBuilder.Build(email: request.Email.Value, password: hashedPassword);

            userRepository
            .Setup(x => x.FindBy(request.Email))
            .Returns(user);
            var passwordIntent = request.Password.Value + user.Password.SaltProp.Value;

            hashingService
            .Setup(x => x.Hash(passwordIntent))
            .Returns(hashedPassword);

            var result = command.Execute(request);

            Assert.IsTrue(result.IsValid);
        }
コード例 #12
0
        public void Add_Update_Delete_Tokens()
        {
            var user = new UserBuilder().Build();

            UserService.Save(user);

            ExternalLogin[] externalLogins = new[]
            {
                new ExternalLogin("test1", Guid.NewGuid().ToString("N")),
                new ExternalLogin("test2", Guid.NewGuid().ToString("N"))
            };

            ExternalLoginService.Save(user.Key, externalLogins);

            ExternalLoginToken[] externalTokens = new[]
            {
                new ExternalLoginToken(externalLogins[0].LoginProvider, "hello1", "world1"),
                new ExternalLoginToken(externalLogins[0].LoginProvider, "hello1a", "world1a"),
                new ExternalLoginToken(externalLogins[1].LoginProvider, "hello2", "world2"),
                new ExternalLoginToken(externalLogins[1].LoginProvider, "hello2a", "world2a")
            };

            ExternalLoginService.Save(user.Key, externalTokens);

            var tokens = ExternalLoginService.GetExternalLoginTokens(user.Key).OrderBy(x => x.LoginProvider).ToList();

            tokens.RemoveAt(0);                                                                                           // remove the first one
            tokens.Add(new IdentityUserToken(externalLogins[1].LoginProvider, "hello2b", "world2b", user.Id.ToString())); // add a new one
            tokens[0].Value = "abcd123";                                                                                  // update

            // save new list
            ExternalLoginService.Save(user.Key, tokens.Select(x => new ExternalLoginToken(x.LoginProvider, x.Name, x.Value)));

            var updatedTokens = ExternalLoginService.GetExternalLoginTokens(user.Key).OrderBy(x => x.LoginProvider).ToList();

            Assert.AreEqual(4, updatedTokens.Count);
            for (int i = 0; i < updatedTokens.Count; i++)
            {
                Assert.AreEqual(tokens[i].LoginProvider, updatedTokens[i].LoginProvider);
                Assert.AreEqual(tokens[i].Name, updatedTokens[i].Name);
                Assert.AreEqual(tokens[i].Value, updatedTokens[i].Value);
            }
        }
コード例 #13
0
        public async Task MustNotifiedUserIsInactiveInUpdateAsync()
        {
            // Given
            var id           = "456DEF";
            var userToUpdate = UserBuilder.New()
                               .WithId(id)
                               .WithEmail(_userRegisterDto.Email)
                               .Build();

            // When
            userToUpdate.Delete(_userLog);
            _userMocks.MockUserGetById(userToUpdate, id);

            // Then
            (await Assert.ThrowsAsync <DomainException>(() =>
                                                        _userRegister.StoreAsync(id, _userRegisterDto.Name, _userRegisterDto.Email,
                                                                                 _userRegisterDto.Password, _userRegisterDto.Permission, _userLog)))
            .WithMessage(UserRegister.UserInactive);
        }
コード例 #14
0
        public ActionResult <object> ConvertUserType([FromBody] UserDto userDto)
        {
            try
            {
                var user = new UserBuilder()
                           .AddName(userDto.Name)
                           .AddSurname(userDto.Surname)
                           .AddCpf(userDto.Cpf)
                           .AddEmail(userDto.Email)
                           .Build();

                return(Ok(user));
            }

            catch (Exception)
            {
                return(BadRequest("Bad request"));
            }
        }
コード例 #15
0
        public async void RemoveColidEntrySubscription_Should_InvokeColidEntrySubscriptionService_Once()
        {
            var colidPidUri = "http://hello.com/how_are_you#123";
            var ceBuilder   = new ColidEntrySubscriptionBuilder().WithColidEntry(colidPidUri);
            var ceList      = new List <ColidEntrySubscription>()
            {
                ceBuilder.WithId(99).Build()
            };
            var userId = Guid.NewGuid();
            var user   = new UserBuilder().WithId(userId).WithEmailAddress("*****@*****.**").WithColidEntrySubscriptions(ceList).Build();

            _mockUserRepository.Setup(x => x.GetOneAsync(userId, It.IsAny <bool>())).ReturnsAsync(user);

            await _userService.RemoveColidEntrySubscriptionAsync(userId, ceBuilder.BuildDto());

            _mockColidEntrySubscriptionService.Verify(x => x.GetOne(It.IsAny <Guid>(), It.IsAny <ColidEntrySubscriptionDto>()), Times.Once);
            _mockColidEntrySubscriptionService.Verify(x => x.Delete(It.IsAny <ColidEntrySubscription>()), Times.Once);
            _mockUserRepository.Verify(x => x.GetOneAsync(userId, It.IsAny <bool>()), Times.Once);
        }
        public void POST_Password_Reset_Email_Is_Not_Sent_When_One_Has_Been_Sent_Within_Last_10_Minutes()
        {
            // Arrange
            User user = new UserBuilder().WithEmailAddress("*****@*****.**").WithPasswordResetCode("code", VirtualDateTime.Now.AddMinutes(-2)).Build();

            var requestFormValues = new Dictionary <string, StringValues>();

            requestFormValues.Add("GovUk_Text_EmailAddress", "*****@*****.**");

            var controllerBuilder = new ControllerBuilder <PasswordResetController>();
            var controller        = controllerBuilder
                                    .WithRequestFormValues(requestFormValues)
                                    .WithDatabaseObjects(user)
                                    .WithMockUriHelper()
                                    .Build();

            // Act
            Assert.Throws <UserRecentlySentPasswordResetEmailWithoutChangingPasswordException>(() => controller.PasswordResetPost(new PasswordResetViewModel()));
        }
コード例 #17
0
        public async Task Should_not_create_test_api_user_if_matching_number_exists()
        {
            const string EMAIL_STEM = EmailData.FAKE_EMAIL_STEM;

            var firstUser = await Context.Data.SeedUser();

            var request = new UserBuilder(EMAIL_STEM, firstUser.Number)
                          .WithUserType(firstUser.UserType)
                          .ForApplication(firstUser.Application)
                          .BuildRequest();

            var command = new CreateNewUserCommand
                          (
                request.Username, request.ContactEmail, request.FirstName, request.LastName, request.DisplayName,
                request.Number, request.TestType, request.UserType, request.Application, request.IsProdUser
                          );

            Assert.ThrowsAsync <MatchingUserWithNumberExistsException>(() => _commandHandler.Handle(command));
        }
コード例 #18
0
        public void UserApplicationService_Disable()
        {
            var currentUser = new UserBuilder().WithProfile(ProfileType.Administrator).Builder();

            _userRepository.Add(currentUser);
            _unitOfWork.Commit();
            _requestScope.SetUserId(currentUser.Id);

            var user = new UserBuilder().WithProfile(ProfileType.Standard).WithActive(true).Builder();

            _userRepository.Add(user);
            _unitOfWork.Commit();

            _userApplicationService.Disable(user.Id);

            var result = _userRepository.GetById(user.Id);

            result.Active.Should().BeFalse();
        }
コード例 #19
0
    //Visualização para tela de login
    public static User login()
    {
        UserBuilder builder = new UserBuilder();
        string      login, password;

        Console.Clear();
        Utils.showAppTitle();
        Console.WriteLine("\nLOGIN\n");
        Utils.showFooter();
        Console.WriteLine("- Informe o login de usuário:\n");
        login = Console.ReadLine();
        Console.WriteLine("\n- Infome a senha de usuário:\n");
        password = Utils.passwordConsole();

        return(builder
               .login(login)
               .password(password)
               .build());
    }
コード例 #20
0
        public void Question_CreatingWithWrongNumberOfTags_Fails(int tagCount)
        {
            // Arrange
            var user  = new UserBuilder().BuildValidUser().Build();
            var title = "TitleNormal";
            var body  = "BodyNormal";
            var tags  = Builder <Tag>
                        .CreateListOfSize(tagCount)
                        .Build()
                        .ToList();

            var limits      = new LimitsBuilder().Build();
            var voteable    = new Voteable();
            var commentable = new Commentable();

            // Act, Assert
            Assert.Throws <BusinessException>(() =>
                                              Question.Create(user, title, body, tags, limits));
        }
コード例 #21
0
        public async Task GenerateVerificationCode_Should_Return_True_If_countryCode_And_phoneNumber_Are_ValidAsync(string countryCode, string phoneNumber)
        {
            var emailHelperMock               = new Mock <IEmailHelper>();
            var randomNumberProvider          = new Mock <IRandomNumberProvider>();
            var verificationCodeDataStoreMock = new Mock <IVerificationCodeDataStore>();

            var expectedOutput = await UserBuilder.Builder()
                                 .WithPhoneNumber(TEST_NUMBER, TEST_COUNTRY_CODE)
                                 .BuildAsync();

            var userRepositoryMock = new Mock <IUserRepository>();

            userRepositoryMock.Setup(x => x.GetUserByPhoneNumber(It.IsAny <string>())).Returns(Task.FromResult(Result.Ok <User>(expectedOutput)));

            var emailVerificationService = new EmailVerificationService(emailHelperMock.Object, randomNumberProvider.Object, verificationCodeDataStoreMock.Object, userRepositoryMock.Object);
            var result = await emailVerificationService.GenerateVerificationCodeAsync(countryCode, phoneNumber);

            result.IsSuccessed.Should().BeTrue();
        }
コード例 #22
0
    public void Does_Not_Persist_Duplicates()
    {
        var user = new UserBuilder().Build();

        UserService.Save(user);

        var providerKey = Guid.NewGuid().ToString("N");

        ExternalLogin[] externalLogins =
        {
            new ExternalLogin("test1", providerKey), new ExternalLogin("test1", providerKey)
        };

        ExternalLoginService.Save(user.Key, externalLogins);

        var logins = ExternalLoginService.GetExternalLogins(user.Key).ToList();

        Assert.AreEqual(1, logins.Count);
    }
        public void POST_Valid_Reset_Code_In_URL_Allows_User_To_Change_Their_Password()
        {
            // Arrange
            User user = new UserBuilder().WithPasswordResetCode("code").Build();

            var requestFormValues = new Dictionary <string, StringValues>();

            requestFormValues.Add("GovUk_Text_NewPassword", "NewPassword1");
            requestFormValues.Add("GovUk_Text_ConfirmNewPassword", "NewPassword1");

            var controllerBuilder = new ControllerBuilder <PasswordResetController>();
            var controller        = controllerBuilder
                                    .WithDatabaseObjects(user)
                                    .WithRequestFormValues(requestFormValues)
                                    .WithMockUriHelper()
                                    .Build();

            // Act
            controller.ChooseNewPasswordPost(new ChooseNewPasswordViewModel {
                ResetCode = "code"
            });

            // Assert
            Assert.AreEqual(Crypto.GetPBKDF2("NewPassword1", Convert.FromBase64String(user.Salt)), user.PasswordHash);
            Assert.IsNull(user.PasswordResetCode);

            Assert.AreEqual(1, controllerBuilder.EmailsSent.Count);

            var email = controllerBuilder.EmailsSent.FirstOrDefault();

            Assert.NotNull(email);
            Assert.AreEqual(EmailTemplates.SendResetPasswordCompletedEmail, email.TemplateId);

            var auditLogs = controllerBuilder.DataRepository.GetAll <AuditLog>();

            Assert.AreEqual(1, auditLogs.Count());

            var log = auditLogs.FirstOrDefault();

            Assert.NotNull(log);
            Assert.AreEqual(AuditedAction.UserChangePassword, log.Action);
        }
コード例 #24
0
        public void ShouldSendMobileVerificationCodeReminderBasedOnCandidateCommunicationPreferences(
            string mobileVerificationCode,
            bool applicationStatusChangePreferencesEnableText,
            bool expiringApplicationPreferencesEnableText,
            bool savedSearchPreferencesEnableText,
            bool marketingPreferencesEnableText,
            bool shouldSendMobileVerificationCode)
        {
            // Arrange.
            var mockSuccessorStrategy    = new Mock <IHousekeepingStrategy>();
            var mockCommunicationService = new Mock <ICommunicationService>();

            var strategy = new SendMobileVerificationCodeReminderStrategyBuilder()
                           .With(mockSuccessorStrategy)
                           .With(mockCommunicationService)
                           .Build();

            var candidateId = Guid.NewGuid();

            var user = new UserBuilder(candidateId).Build();

            var candidate = new CandidateBuilder(candidateId)
                            .PhoneNumber(PhoneNumber)
                            .MobileVerificationCode(mobileVerificationCode)
                            .MobileVerificationCodeDateCreated(UtcYesterday)
                            .EnableApplicationStatusChangeAlertsViaText(applicationStatusChangePreferencesEnableText)
                            .EnableExpiringApplicationAlertsViaText(expiringApplicationPreferencesEnableText)
                            .EnableSavedSearchAlertsViaEmailAndText(savedSearchPreferencesEnableText)
                            .EnableMarketingViaText(marketingPreferencesEnableText)
                            .Build();

            // Act.
            strategy.Handle(user, candidate);

            // Assert.
            mockSuccessorStrategy.Verify(mock => mock.Handle(user, candidate), Times.Once);

            var callCount = shouldSendMobileVerificationCode ? 1 : 0;

            mockCommunicationService.Verify(mock => mock.SendMessageToCandidate(
                                                candidateId, MessageTypes.SendMobileVerificationCodeReminder, It.IsAny <IEnumerable <CommunicationToken> >()), Times.Exactly(callCount));
        }
コード例 #25
0
        private async Task CreateNewUserInTestApi(UserType userType, Application application, TestType testType, bool isProdUser, int newNumber)
        {
            var emailStem = GetEmailStem();

            var request = new UserBuilder(emailStem, newNumber)
                          .WithUserType(userType)
                          .ForApplication(application)
                          .ForTestType(testType)
                          .IsProdUser(isProdUser)
                          .BuildRequest();

            var createNewUserCommand = new CreateNewUserCommand
                                       (
                request.Username, request.ContactEmail, request.FirstName, request.LastName,
                request.DisplayName, request.Number, request.TestType, request.UserType,
                request.Application, request.IsProdUser
                                       );

            await _commandHandler.Handle(createNewUserCommand);
        }
コード例 #26
0
        public async Task Get_WhenAnimalNotFound_ShouldReturnNotFound()
        {
            var animal = AnimalBuilder.NewInstance()
                         .WithId(1)
                         .WithCode(2)
                         .Build();
            var user = UserBuilder.NewInstance()
                       .WithId(1)
                       .WithUsername("fakeuser")
                       .AddAnimal(animal)
                       .Build();
            var controller = GetUserAnimalsController();

            A.CallTo(() => _userRepository.GetByIdAsync(A <int> ._)).Returns(Task.FromResult <User>(user));

            var result = await controller.Get(1, 2);

            Assert.NotNull(result);
            Assert.IsType <NotFoundResult>(result);
        }
コード例 #27
0
ファイル: AddAttendanceTests.cs プロジェクト: Ethoths/Eventer
        public void CallingAddAttendanceTwiceByUsernameOnlyAddsTheAttendanceOnceAndUpdatesTheArrivalAndDeparture()
        {
            // Arrange
            var user       = new UserBuilder().Build();
            var arrival1   = DateTime.Now;
            var departure1 = arrival1.AddMinutes(20);
            var arrival2   = arrival1.AddMinutes(Randomiser.Int(10));
            var departure2 = arrival2.AddMinutes(Randomiser.Int(10, 60));
            var attendance = new AttendanceBuilder().User(user).Arrival(arrival1).Departure(departure1).Build();

            // Act
            var happening = new EventBuilder().AddAttendance(attendance).Build();

            happening.AddAttendance(new AttendanceBuilder().User(new UserBuilder().Username(user.Username).Build()).Arrival(arrival2).Departure(departure2).Build());

            // Assert
            Assert.AreEqual(1, happening.Attendances.Count);
            Assert.AreEqual(arrival2, happening.Start);
            Assert.AreEqual(departure2, happening.End);
        }
コード例 #28
0
        public async Task post_member_to_capability_through_api_returns_expected_status_code_on_success()
        {
            using (var clientBuilder = new HttpClientBuilder())
            {
                var dummyUser = new UserBuilder().Build();

                var client = clientBuilder
                             .WithService <ICapabilityServiceClient>(new StubCapabilityServiceClient(member: dummyUser))
                             .Build();

                var dummyContent = new JsonContent(new { Email = "*****@*****.**" });

                var response = await client.PostAsync("/api/capabilities/1/members", dummyContent);

                Assert.Equal(
                    expected: HttpStatusCode.NoContent,
                    actual: response.StatusCode
                    );
            }
        }
コード例 #29
0
        public void UserApplicationService_Delete()
        {
            var currentUser = new UserBuilder().WithProfile(ProfileType.Administrator).Builder();

            _userRepository.Add(currentUser);
            _unitOfWork.Commit();
            _requestScope.SetUserId(currentUser.Id);

            var user = new UserBuilder().WithProfile(ProfileType.Standard).Builder();

            _userRepository.Add(user);
            _unitOfWork.Commit();

            _userApplicationService.Delete(user.Id);

            var result = _userRepository.Get(new Filter());

            result.totalItems.Should().Be(1);
            result.entities.Should().HaveCount(1);
        }
コード例 #30
0
        public async Task ConfirmEmailRegister_Should_activate_user_and_reset_pemisiontoken()
        {
            // arrange
            var user = UserBuilder.Create()
                       .WithEmail(HealthyJuicesConstants.DEFAULT_USER_LOGIN)
                       .WithPermissionsToken(RandomString, DateTime.Today.AddDays(1))
                       .Build(ArrangeRepositoryContext);

            var controller = new AuthorizationController(Mediator);

            // act
            await controller.ConfirmRegisterAsync(HealthyJuicesConstants.DEFAULT_USER_LOGIN, user.PermissionsToken.Token);

            // assert
            var subject = AssertRepositoryContext.Users.FirstOrDefault();

            subject.Should().NotBeNull();
            subject.IsActive.Should().BeTrue();
            subject.PermissionsToken.Should().BeNull();
        }
コード例 #31
0
        public void AuthenticateApplicationService_Authenticate_invalid_password()
        {
            var user = new UserBuilder().WithEmail("*****@*****.**").WithPassword("qwe123").Builder();

            _userRepository.Add(user);
            _unitOfWork.Commit();

            var model = new AuthenticateModel
            {
                Email    = user.Email,
                Password = "******"
            };

            var result = _authenticateApplicationService.Authenticate(model);

            result.Token.Should().BeNullOrEmpty();
            result.User.Should().BeNull();
            DomainNotificationHandler.HasNotifications().Should().BeTrue();
            DomainNotificationHandler.GetNotifications.First().Value.Should().Be(DomainError.InvalidPassoword);
        }
コード例 #32
0
        public void should_get_player_stats()
        {
            var owner = new UserBuilder()
                        .With(u => u.Id, "abcde")
                        .BuildAndSave();

            new StatBuilder()
            .With(i => i.Id, 245)
            .With(i => i.Owner, owner)
            .With(i => i.AchievementType, "surfing")
            .BuildAndSave();

            var stats = DomainRegistry.Repository.Find(new GetPlayerStats {
                OwnerId = owner.Id
            }).ToList();

            Assert.That(stats, Has.Exactly(1).Items);
            Assert.That(stats.First().Id, Is.EqualTo(245));
            Assert.That(stats.First().AchievementType, Is.EqualTo("surfing"));
        }
コード例 #33
0
        public async Task ShouldRemoveRoleFromUser()
        {
            SchoolManagementContext    context         = new ContextBuilder().BuildClean();
            Mock <UserManager <User> > userManagerMock = UserManagerMoq.Get();
            ClaimsPrincipal            claimsPrincipal = new ClaimsPrincipalBuilder().AddPermissionClaim(Permissions.Anchors.Remove).Build();
            var user = new UserBuilder(context).WithEmail("*****@*****.**").BuildAndSave();

            userManagerMock.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(user);
            Command cmd = new Command
            {
                RoleName        = Roles.Anchor,
                UserId          = Guid.NewGuid().ToString(),
                ClaimsPrincipal = claimsPrincipal
            };

            await new Handler(userManagerMock.Object).Handle(cmd, CancellationToken.None);

            userManagerMock.Verify(x => x.FindByIdAsync(It.IsAny <string>()), Times.Once);
            userManagerMock.Verify(x => x.RemoveFromRoleAsync(It.IsAny <User>(), It.IsAny <string>()), Times.Once);
        }
コード例 #34
0
        public void RegisteringExistingUnactivatedExpiredUserIsValid()
        {
            const string emailAddress = "*****@*****.**";
            const string password     = "******";
            var          candidateId  = Guid.NewGuid();

            var candidate = new CandidateBuilder(candidateId).EmailAddress(emailAddress).Build();
            var user      = new UserBuilder(emailAddress, candidateId).Activated(false).Build();

            user.ActivateCodeExpiry = DateTime.UtcNow.AddMonths(-2);

            var userReadRepository = new Mock <IUserReadRepository>();

            userReadRepository.Setup(r => r.Get(emailAddress, false)).Returns(user);
            var strategy = new RegisterCandidateStrategyBuilder().With(userReadRepository).Build();

            Action action = () => strategy.RegisterCandidate(candidate, password);

            action.ShouldNotThrow <CustomException>();
        }
コード例 #35
0
        public async Task DeletedEntity_ReturnsError()
        {
            // Arrange
            var user = await UserBuilder.Instance()
                       .WithName("Baz", "Qux")
                       .AsDeleted()
                       .PersistAndBuild(DataContext);

            // Act
            var result = await Mediator.HandleAsync(new EditTestRequest
            {
                Id        = user.Id,
                FirstName = "Foo",
                LastName  = "Bar",
                Role      = Roles.Admin
            });

            // Assert
            result.HasError($"User with ID {user.Id} not found.", "Id");
        }
コード例 #36
0
        public void Execute()
        {
            SecurityConfigurator.Configure(configuration =>
            {
                /**************************************
                 Simulation assigning role via userbuilder
                 This module will progressively evolve once we have all pieces into place
                 1.Get the user authenticated, get its login name
                 2.Check this user in the entity list
                 3.Get its roles for (now we are using application role but we need to use application permission which is the lowest granularity)
                 4. Set all config for all controller/action 
                 * 
                *****************************************/
                // 1. Use the User Query to get the current user from DB
                //UserEFContainer dbcontext = new UserEFContainer();
                //var CurrUser = _query.GetOne(user => user.Username == HttpContext.Current.User.Identity.Name);
                 
                // Note: To verify this actually works, try changing role other than ADMIN and you should not get access to any UserController action
                //Also to add, list of constant that represent each CODE of role and others
                List<ApplicationRole> adminApplicationRole = new ApplicationRoleReferenceDataSource().Where(x => x.Code == "ADMIN").ToList();
                 User myUser = new UserBuilder(1).WithApplicationRoles(adminApplicationRole);
                                                //.WithUserName("UITPC\\underscoreit7");
                
               
                //2. Check whether the current user is authenticated
                // Let Fluent Security know how to get the authentication status of the current user
                configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
                
                //3. Get its roles , NOTE: it won t be application role but the list of application permission 
                //var LstRoles = dbcontext.Users.Single(x => x.Id == 1).Roles.ToList().Select(x => x.RoleName);
                //configuration.GetRolesFrom(() => dbcontext.Users.Single(x => x.Loginname == HttpContext.Current.User.Identity.Name).Roles.ToList().Select(x => x.RoleName));
               configuration.GetRolesFrom(() => myUser.ApplicationRoles.Select(x => x.Code)) ;

                // This is where you set up the policies you want Fluent Security to enforce on your controllers and actions
                configuration.ForAllControllers().DenyAnonymousAccess();

                // ADMIN SECTION *************************************************
                configuration.For<UserController>().RequireRole("ADMIN");
                
                // DEAL SECTION *************************************************
                //configuration.For<DealController>(x => x.Index()).RequireRole("DealLeader");

                // ASSET SECTION *************************************************
                //configuration.For<AssetController>(x => x.Index()).RequireRole("DealLeader");

                // XXX SECTION *************************************************
                //configuration.For<XXXController>(x => x.Index()).RequireRole("XXX");


                configuration.ResolveServicesUsing(type =>
                {
                    var objects = new List<object>();

                    if (type == typeof(IPolicyViolationHandler))
                        objects.Add(new RequireRolePolicyViolationHandler());

                    return objects;
                });
            });
            
            GlobalFilters.Filters.Add(new HandleSecurityAttribute(), 0);
        }
コード例 #37
0
ファイル: UserBuilderTest.cs プロジェクト: brianium/today
 public void EmptyConstructorGetInstanceReturnsUser()
 {
     var user = new UserBuilder().GetInstance();
     Assert.IsInstanceOf<User>(user);
 }
コード例 #38
0
ファイル: UserBuilderTest.cs プロジェクト: brianium/today
 public void ConstructedWithDateTimeSetsDateTime()
 {
     var user = new UserBuilder("brian", "scaturro", "*****@*****.**", "password", new DateTime(2012, 6, 20)).GetInstance();
     Assert.AreEqual(new DateTime(2012,6,20),user.DateAdded);
 }
コード例 #39
0
 public void ShouldBeAbleToSaveAndLoadUser()
 {
     var user = new UserBuilder().Build();
     VerifySaveLoad(user);
 }
コード例 #40
0
        public void Create_given_required_fluent_parameters_returns_new_User()
        {
            // arrange
            ICryptoService cryptoService = MockRepository.GenerateStub<ICryptoService>();
            cryptoService.Expect(x => x.GenerateSalt("password")).Return("salt");
            cryptoService.Expect(x => x.ComputeHash("salt", "password")).Return("hash");

            // act
            User user = new UserBuilder(cryptoService)
                .SetEmail("Email")
                .SetName("Name")
                .SetSurname("Surname")
                .SetPassword("password")
                .Create();

            // assert
            Assert.That(user, Is.Not.Null);
            Assert.That(user.Email == "Email");
            Assert.That(user.Name == "Name");
            Assert.That(user.Surname == "Surname");
            Assert.That(user.PasswordSalt == "salt");
            Assert.That(user.PasswordHash == "hash");

            cryptoService.VerifyAllExpectations();
        }