public async Task UsersShouldNotBeAbleToRegisterIfNotAllowed()
        {
            var mockUserManager = UsersMockHelper.MockUserManager <IUser>().Object;
            var settings        = new RegistrationSettings {
                UsersCanRegister = UserRegistrationType.NoRegistration
            };
            var mockSiteService = Mock.Of <ISiteService>(ss =>
                                                         ss.GetSiteSettingsAsync() == Task.FromResult(
                                                             Mock.Of <ISite>(s => s.Properties == JObject.FromObject(new { RegistrationSettings = settings }))
                                                             )
                                                         );
            var mockSmtpService = Mock.Of <ISmtpService>();

            var controller = new RegistrationController(
                mockUserManager,
                Mock.Of <IAuthorizationService>(),
                mockSiteService,
                Mock.Of <INotifier>(),
                Mock.Of <IEmailAddressValidator>(),
                Mock.Of <ILogger <RegistrationController> >(),
                Mock.Of <IHtmlLocalizer <RegistrationController> >(),
                Mock.Of <IStringLocalizer <RegistrationController> >());

            var result = await controller.Register();

            Assert.IsType <NotFoundResult>(result);

            // Post
            result = await controller.Register(new RegisterViewModel());

            Assert.IsType <NotFoundResult>(result);
        }
Ejemplo n.º 2
0
        public void Register_Post_Fail_Already_Registered()
        {
            // arrange
            var auth         = new Mock <IAuthenticationService>();
            var notification = new Mock <INotificationService>();
            var redirect     = new RedirectService();
            var controller   = new RegistrationController(auth.Object, notification.Object, redirect);
            var model        = new RegisterUserModel()
            {
                Email           = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******"
            };

            auth.Setup(a => a.ValidateCaptcha()).Returns(true);
            auth.Setup(a => a.RegisterNewUser("*****@*****.**", "password")).Returns(false);

            //act
            controller.Register(model);
            var result = controller.Register(model) as ViewResult;

            //assert
            Assert.That(model, Is.EqualTo(result.ViewData.Model));
            Assert.That(controller.ModelState[""].Errors[0].ErrorMessage, Is.EqualTo("Sorry, user with such email already exist. Please register with different email."));
        }
        private void RegistrationButton_Click(object sender, RoutedEventArgs e)
        {
            RegistrationController controller = new RegistrationController();

            if (Regex.Match(Password.Password, @"^[0-9]+$").Success&&
                Regex.Match(UserName.Text, @"^[а-яА-ЯёЁa-zA-Z]+[а-яА-ЯёЁa-zA-Z0-9]+$").Success&& UserName.Text.Length > 4)
            {
                if (Password.Password.Length >= 6 && Password.Password == PasswordRepit.Password)
                {
                    User user = new User(UserName.Text, Password.Password, Email.Text);
                    controller.Register(user);
                    if (new LoginControl().login(user))
                    {
                        LoginWindow parentWindow = Window.GetWindow(this) as LoginWindow;
                        parentWindow.Close();
                    }
                }
                else
                {
                    MessageBox.Show("Пароли не совпадают или слишком короткий пароль");
                }
            }
            else
            {
                MessageBox.Show("Введены некорректные символы");
            }
        }
Ejemplo n.º 4
0
        public void LoginFailTest_ChecksThatUserCannotLoginBeforeActivatingAccount_VerifiesByReturnedValueAndDatabaseQuerying()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];

            string            username         = "******";
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam("*****@*****.**", username, "123", "Pakistan",
                                                                                                 TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            // Login attempt without Activating Account
            LoginController loginController = (LoginController)_applicationContext["LoginController"];

            httpActionResult = loginController.Login(new LoginParams(username, "123"));
            BadRequestErrorMessageResult badRequest = (BadRequestErrorMessageResult)httpActionResult;

            Assert.IsNotNull(badRequest);

            IUserRepository userRepository = (IUserRepository)_applicationContext["UserRepository"];
            User            userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            // Not logged in yet
            Assert.AreEqual(DateTime.MinValue, userByUserName.LastLogin);
            Assert.IsFalse(userByUserName.IsActivationKeyUsed.Value);
        }
Ejemplo n.º 5
0
        public async Task RegisterTest(HttpStatusCode statusCode, int customerId)
        {
            Customer customer   = new() { FirstName = "Test", Surname = "Test", DoB = DateTime.Now.AddYears(-18), PolicyReference = "AF-123456" };
            var      mocklogger = new Mock <ILogger>();

            var mockRegistrationService = new Mock <IRegistration>();
            var mockRegisterResponse    = new Outcome <int>("Test Error", statusCode, customerId);

            mockRegistrationService.Setup(x => x.Register(It.IsAny <CustomerServiceModel>())).Returns(Task.FromResult(mockRegisterResponse));

            _RegistrationController = new RegistrationController(mockRegistrationService.Object, _mapper, mocklogger.Object);
            var result = await _RegistrationController.Register(customer);

            var okresult = result.Result as ObjectResult;

            if (mockRegisterResponse.StatusCode == HttpStatusCode.OK)
            {
                Assert.AreEqual(mockRegisterResponse.Result, okresult.Value);
            }
            else
            {
                Assert.AreEqual("Test Error", okresult.Value);
            }

            Assert.AreEqual(Convert.ToInt32(mockRegisterResponse.StatusCode), okresult.StatusCode);
        }
        /// <summary>
        /// Register and login
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="applicationContext"></param>
        /// <returns></returns>
        public static UserValidationEssentials RegisterAndLogin(string userName, string email, string password, IApplicationContext applicationContext)
        {
            //register
            RegistrationController registrationController =
                applicationContext["RegistrationController"] as RegistrationController;
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam(email, userName, password, "Pakistan",
                                                                                                 TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            //activate account
            UserController userController = applicationContext["UserController"] as UserController;

            httpActionResult = userController.ActivateUser(new UserActivationParam(userName, password, activationKey));

            //login
            LoginController loginController = applicationContext["LoginController"] as LoginController;

            httpActionResult = loginController.Login(new LoginParams("user", "123"));
            OkNegotiatedContentResult <UserValidationEssentials> keys =
                (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult;

            //return keys
            return(keys.Content);
        }
Ejemplo n.º 7
0
        public void Register_Post_Success_Redirected_To_Dashboard()
        {
            // arrange
            var auth         = new Mock <IAuthenticationService>();
            var notification = new Mock <INotificationService>();
            var redirect     = new RedirectService();
            var controller   = new RegistrationController(auth.Object, notification.Object, redirect);

            var model = new RegisterUserModel()
            {
                Email           = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******"
            };

            auth.Setup(a => a.ValidateCaptcha()).Returns(true);
            auth.Setup(a => a.RegisterNewUser("*****@*****.**", "password")).Returns(true);
            auth.Setup(a => a.Authenticate("*****@*****.**", "password")).Returns(true);

            //act
            var result = controller.Register(model) as RedirectResult;

            //assert (result)
            result.Url.Should().Be("~/user/[email protected]");
        }
Ejemplo n.º 8
0
        public void LoginSuccessfulTest_MakesSureAccountIsCreated_VerifiesAndAssertsTheReturnedValue()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];
            IHttpActionResult      httpActionResult       = registrationController.Register(new SignUpParam("*****@*****.**", "user", "123", "Pakistan",
                                                                                                            TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            UserController userController = (UserController)_applicationContext["UserController"];

            httpActionResult = userController.ActivateUser(new UserActivationParam("user", "123", activationKey));
            OkNegotiatedContentResult <string> okResponseMessage1 =
                (OkNegotiatedContentResult <string>)httpActionResult;

            Assert.AreEqual(okResponseMessage1.Content, "activated");

            LoginController loginController = (LoginController)_applicationContext["LoginController"];

            httpActionResult = loginController.Login(new LoginParams("user", "123"));
            OkNegotiatedContentResult <UserValidationEssentials> keys =
                (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult;

            Assert.IsNotNullOrEmpty(keys.Content.ApiKey);
            Assert.IsNotNullOrEmpty(keys.Content.SecretKey);
            Assert.IsNotNullOrEmpty(keys.Content.SessionLogoutTime.ToString());
        }
        public void Register()
        {
            // Act
            var result = _target.Register();

            // Assert
            var viewResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.Equal("Registration", viewResult.ActionName);
        }
        public void LogoutFailTest_ChecksThatExceptionIsThrownWhenInvalidActivationKeyIsGiven_VerifiesAndAssertsTheReturnedValueAndQueriesDatabase()
        {
            // Register User
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];
            IHttpActionResult      httpActionResult       = registrationController.Register(new SignUpParam("*****@*****.**", "user", "123", "Pakistan",
                                                                                                            TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            // Activate Account
            UserController userController = (UserController)_applicationContext["UserController"];

            httpActionResult = userController.ActivateUser(new UserActivationParam("user", "123", activationKey));
            OkNegotiatedContentResult <string> okResponseMessage1 =
                (OkNegotiatedContentResult <string>)httpActionResult;

            Assert.AreEqual(okResponseMessage1.Content, "activated");

            // Login
            LoginController loginController = (LoginController)_applicationContext["LoginController"];

            httpActionResult = loginController.Login(new LoginParams("user", "123"));
            OkNegotiatedContentResult <UserValidationEssentials> keys =
                (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult;

            Assert.IsNotNullOrEmpty(keys.Content.ApiKey);
            Assert.IsNotNullOrEmpty(keys.Content.SecretKey);
            Assert.IsNotNullOrEmpty(keys.Content.SessionLogoutTime.ToString());

            // Verify that Security Keys are in the database
            ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)_applicationContext["SecurityKeysPairRepository"];
            SecurityKeysPair        securityKeysPair       = securityKeysRepository.GetByApiKey(keys.Content.ApiKey);

            Assert.IsNotNull(securityKeysPair);
            Assert.AreEqual(keys.Content.SecretKey, securityKeysPair.SecretKey);
            Assert.IsTrue(securityKeysPair.SystemGenerated);

            LogoutController logoutController = (LogoutController)_applicationContext["LogoutController"];

            logoutController.Request = new HttpRequestMessage(HttpMethod.Get, "");
            logoutController.Request.Headers.Add("Auth", "123");
            IHttpActionResult            logoutResult     = logoutController.Logout();
            BadRequestErrorMessageResult logoutOkResponse = (BadRequestErrorMessageResult)logoutResult;

            Assert.IsNotNull(logoutOkResponse);

            // Verify that the Security Keys are not in the database
            securityKeysPair = securityKeysRepository.GetByApiKey(keys.Content.ApiKey);
            Assert.IsNotNull(securityKeysPair);
            Assert.AreEqual(keys.Content.SecretKey, securityKeysPair.SecretKey);
            Assert.IsTrue(securityKeysPair.SystemGenerated);
        }
        public void RegisterAccountTest_IfRegisterControllerIsCalled_SignUpShouldBeDoneSuccessfullyAndActivationKeyShouldBeReceived()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];
            IHttpActionResult      httpActionResult       = registrationController.Register(new SignUpParam("*****@*****.**", "user", "123", "Pakistan",
                                                                                                            TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);
        }
        public void RegisterAccountFailTest_ChecksIfTheUserCannotCreateAccountAgainWIthSameEmail_VerifiesReturnedValueAndQueriesDatabase()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];
            string            username         = "******";
            string            email            = "*****@*****.**";
            string            password         = "******";
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam(email, username, password, "Pakistan", TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage = (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            IUserRepository            userRepository            = (IUserRepository)_applicationContext["UserRepository"];
            IPasswordEncryptionService passwordEncryptionService = (IPasswordEncryptionService)_applicationContext["PasswordEncryptionService"];

            User userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            Assert.IsFalse(userByUserName.IsActivationKeyUsed.Value);
            Assert.AreEqual(username, userByUserName.Username);
            Assert.AreEqual(email, userByUserName.Email);

            string username2 = "newUser";
            string password2 = "newPassword";

            httpActionResult = registrationController.Register(new SignUpParam(email, username2, password2, "Pakistan", TimeZone.CurrentTimeZone, ""));
            BadRequestErrorMessageResult badRequest = (BadRequestErrorMessageResult)httpActionResult;

            Assert.IsNotNull(badRequest);

            // Verify that the old credentials are still the same
            userByUserName = userRepository.GetUserByEmail(email);
            Assert.IsNotNull(userByUserName);
            Assert.IsFalse(userByUserName.IsActivationKeyUsed.Value);
            Assert.AreEqual(username, userByUserName.Username);
            Assert.AreEqual(email, userByUserName.Email);
            Assert.IsTrue(passwordEncryptionService.VerifyPassword(password, userByUserName.Password));

            Assert.AreNotEqual(username2, userByUserName.Username);
            Assert.IsFalse(passwordEncryptionService.VerifyPassword(password2, userByUserName.Password));
        }
        public async Task RegistrationController_GET_Register_ViewReturned(String returnUrl)
        {
            Mock <IClient>         client     = new Mock <IClient>();
            RegistrationController controller = new RegistrationController(client.Object);

            IActionResult actionResult = await controller.Register(CancellationToken.None, returnUrl);

            ViewResult viewResult = actionResult.ShouldBeOfType <ViewResult>();

            viewResult.ViewData.Count.ShouldBe(1);
            viewResult.ViewData["ReturnUrl"].ShouldBe(returnUrl);
        }
        public async Task RegistrationController_POST_Register_LoginScreenShown()
        {
            RegisterClubAdministratorViewModel viewModel = new RegisterClubAdministratorViewModel();

            Mock <IClient>         client     = new Mock <IClient>();
            RegistrationController controller = new RegistrationController(client.Object);

            IActionResult result = await controller.Register(viewModel, CancellationToken.None);

            RedirectToActionResult redirect = result.ShouldBeOfType <RedirectToActionResult>();

            redirect.ActionName.ShouldBe("Registered");
        }
        public async Task UsersShouldBeAbleToRegisterIfAllowed()
        {
            var mockUserManager = MockUserManager <IUser>().Object;
            var settings        = new RegistrationSettings {
                UsersCanRegister = true
            };
            var mockSiteService = Mock.Of <ISiteService>(ss =>
                                                         ss.GetSiteSettingsAsync() == Task.FromResult(
                                                             Mock.Of <ISite>(s => s.Properties == JObject.FromObject(new { RegistrationSettings = settings }))
                                                             )
                                                         );
            var mockSmtpService = Mock.Of <ISmtpService>();

            var controller = new RegistrationController(
                Mock.Of <IUserService>(),
                mockUserManager,
                MockSignInManager(mockUserManager).Object,
                Mock.Of <IAuthorizationService>(),
                mockSiteService,
                Mock.Of <INotifier>(),
                mockSmtpService,
                Mock.Of <IShapeFactory>(),
                Mock.Of <IHtmlDisplay>(),
                Mock.Of <ILogger <RegistrationController> >(),
                Mock.Of <IHtmlLocalizer <RegistrationController> >(),
                Mock.Of <IStringLocalizer <RegistrationController> >(),
                Enumerable.Empty <IRegistrationFormEvents>());

            var result = await controller.Register();

            Assert.IsType <ViewResult>(result);

            // Post
            result = await controller.Register(new RegisterViewModel());

            Assert.IsType <ViewResult>(result);
        }
        public async Task RegistrationController_POST_Register_ErrorsDisplayed()
        {
            RegisterClubAdministratorViewModel viewModel = new RegisterClubAdministratorViewModel();

            Mock <IClient>         client     = new Mock <IClient>();
            RegistrationController controller = new RegistrationController(client.Object);

            controller.ModelState.AddModelError("FirstName", "Required");

            IActionResult result = await controller.Register(viewModel, CancellationToken.None);

            ViewResult viewResult = result.ShouldBeOfType <ViewResult>();

            viewResult.ViewData.ModelState.IsValid.ShouldBeFalse();
            viewResult.ViewData.ModelState.ErrorCount.ShouldBe(1);
        }
Ejemplo n.º 17
0
        public void LoginFailThenSuccessfulTest_ChecksThatUserCannotLoginBeforeActivatingAccountAndThenAllowsLoginAfterActivation_VerifiesByReturnedValueAndDatabaseQuerying()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];

            string            username         = "******";
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam("*****@*****.**", username, "123", "Pakistan",
                                                                                                 TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            // Login attempt without Activating Account
            LoginController loginController = (LoginController)_applicationContext["LoginController"];
            int             currentHour     = DateTime.Now.Hour;

            httpActionResult = loginController.Login(new LoginParams(username, "123"));
            BadRequestErrorMessageResult badRequest = (BadRequestErrorMessageResult)httpActionResult;

            Assert.IsNotNull(badRequest);

            // Activate Account
            UserController userController = (UserController)_applicationContext["UserController"];

            httpActionResult = userController.ActivateUser(new UserActivationParam(username, "123", activationKey));
            OkNegotiatedContentResult <string> okResponseMessage1 =
                (OkNegotiatedContentResult <string>)httpActionResult;

            Assert.AreEqual(okResponseMessage1.Content, "activated");

            // Login again
            httpActionResult = loginController.Login(new LoginParams(username, "123"));
            OkNegotiatedContentResult <UserValidationEssentials> okReponse =
                (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult;

            Assert.IsNotNullOrEmpty(okReponse.Content.ApiKey);
            Assert.IsNotNullOrEmpty(okReponse.Content.SecretKey);
            Assert.IsNotNullOrEmpty(okReponse.Content.SessionLogoutTime.ToString());

            IUserRepository userRepository = (IUserRepository)_applicationContext["UserRepository"];
            User            userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            Assert.AreEqual(currentHour, userByUserName.LastLogin.Hour);
            Assert.IsTrue(userByUserName.IsActivationKeyUsed.Value);
        }
Ejemplo n.º 18
0
        public async Task RegisterTestException()
        {
            Customer customer   = new() { FirstName = "Test", Surname = "Test", DoB = DateTime.Now.AddYears(-18), PolicyReference = "AF-123456" };
            var      mocklogger = new Mock <ILogger>();

            var mockRegistrationService = new Mock <IRegistration>();

            mockRegistrationService.Setup(x => x.Register(It.IsAny <CustomerServiceModel>())).Throws(new Exception());

            _RegistrationController = new RegistrationController(mockRegistrationService.Object, _mapper, mocklogger.Object);
            var result = await _RegistrationController.Register(customer);

            var okresult = result.Result as ObjectResult;

            Assert.AreEqual("Error Occurred", okresult.Value);

            Assert.AreEqual(Convert.ToInt32(HttpStatusCode.InternalServerError), okresult.StatusCode);
        }
Ejemplo n.º 19
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            RegistrationController controller = new RegistrationController();

            if (txtPassword.Password.Length >= 6 && txtPassword.Password == txtPasswordRepeat.Password)
            {
                User user = new User(txtUsername.Text, txtPassword.Password, txtUserEmail.Text);
                controller.Register(user);
                if (new LoginControl().login(user))
                {
                    EntryWindow parentWindow = Window.GetWindow(this) as EntryWindow;
                    parentWindow.Close();
                }
            }
            else
            {
                MessageBox.Show("Пароли не совпадают или короткий пароль.");
            }
        }
Ejemplo n.º 20
0
        public void Register_Post_Fail_Unknown_Reason()
        {
            // arrange
            var auth         = new Mock <IAuthenticationService>();
            var notification = new Mock <INotificationService>();
            var redirect     = new RedirectService();
            var controller   = new RegistrationController(auth.Object, notification.Object, redirect);
            var model        = new RegisterUserModel()
            {
                Email           = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******"
            };

            auth.Setup(a => a.ValidateCaptcha()).Returns(true);
            auth.Setup(a => a.RegisterNewUser("*****@*****.**", "password")).Throws(new Exception());

            //act / post
            var result = controller.Register(model) as ViewResult;
        }
        public void RegisterAccountSuccessfulTest_ChecksIfTheUserCreatesAnAccountSuccessfuly_VerifiesRetunredvalueAndQueriesDatabase()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];
            string            username         = "******";
            string            email            = "*****@*****.**";
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam(email, username, "123", "Pakistan",
                                                                                                 TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage = (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            IUserRepository userRepository = (IUserRepository)_applicationContext["UserRepository"];

            User userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            Assert.IsFalse(userByUserName.IsActivationKeyUsed.Value);
            Assert.AreEqual(username, userByUserName.Username);
            Assert.AreEqual(email, userByUserName.Email);
        }
        public void ActivateAccount_IfAccountIsActivatedSuccessfully_TheTier0LevelWillGetVerified()
        {
            RegistrationController registrationController =
                _applicationContext["RegistrationController"] as RegistrationController;
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam("*****@*****.**", "user", "123", "Pakistan",
                                                                                                 TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            UserController userController = _applicationContext["UserController"] as UserController;

            httpActionResult = userController.ActivateUser(new UserActivationParam("user", "123", activationKey));
            OkNegotiatedContentResult <string> okResponseMessage1 =
                (OkNegotiatedContentResult <string>)httpActionResult;

            Assert.AreEqual(okResponseMessage1.Content, "activated");

            LoginController loginController = _applicationContext["LoginController"] as LoginController;

            httpActionResult = loginController.Login(new LoginParams("user", "123"));
            OkNegotiatedContentResult <UserValidationEssentials> keys =
                (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult;

            Assert.IsNotNullOrEmpty(keys.Content.ApiKey);
            Assert.IsNotNullOrEmpty(keys.Content.SecretKey);
            Assert.IsNotNullOrEmpty(keys.Content.SessionLogoutTime.ToString());

            TierController tierController = _applicationContext["TierController"] as TierController;

            tierController.Request = new HttpRequestMessage(HttpMethod.Get, "");
            tierController.Request.Headers.Add("Auth", keys.Content.ApiKey);
            httpActionResult = tierController.GetTierStatuses();
            OkNegotiatedContentResult <UserTierStatusRepresentation[]> statuses = (OkNegotiatedContentResult <UserTierStatusRepresentation[]>)httpActionResult;

            Assert.AreEqual(statuses.Content.Length, 5);
            Assert.AreEqual(statuses.Content[0].Status, Status.Verified.ToString());
        }
Ejemplo n.º 23
0
        public void Register_NewUserRegistered_EmailSent()
        {
            // arrange
            var auth         = new Mock <IAuthenticationService>();
            var notification = new Mock <INotificationService>();
            var redirect     = new RedirectService();
            var controller   = new RegistrationController(auth.Object, notification.Object, redirect);
            var user         = new RegisterUserModel
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            auth.Setup(a => a.ValidateCaptcha()).Returns(true);
            auth.Setup(a => a.RegisterNewUser("*****@*****.**", "111111")).Returns(true);

            //act
            var result = controller.Register(user) as RedirectResult;

            //post
            notification.Verify(n => n.NotifyUserOnRegistration("*****@*****.**", "111111"));
        }
Ejemplo n.º 24
0
        public void LoginSuccessfulTest_MakesSureAccountIsCreatedAndUserLogsin_VerifiesByReturnedValueAndDatabaseQuerying()
        {
            RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"];

            string            username         = "******";
            IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam("*****@*****.**", username, "123", "Pakistan",
                                                                                                 TimeZone.CurrentTimeZone, ""));
            OkNegotiatedContentResult <string> okResponseMessage =
                (OkNegotiatedContentResult <string>)httpActionResult;
            string activationKey = okResponseMessage.Content;

            Assert.IsNotNullOrEmpty(activationKey);

            UserController userController = (UserController)_applicationContext["UserController"];

            httpActionResult = userController.ActivateUser(new UserActivationParam(username, "123", activationKey));
            OkNegotiatedContentResult <string> okResponseMessage1 =
                (OkNegotiatedContentResult <string>)httpActionResult;

            Assert.AreEqual(okResponseMessage1.Content, "activated");

            LoginController loginController = (LoginController)_applicationContext["LoginController"];
            int             currentHour     = DateTime.Now.Hour;

            httpActionResult = loginController.Login(new LoginParams(username, "123"));
            OkNegotiatedContentResult <UserValidationEssentials> keys =
                (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult;

            Assert.IsNotNullOrEmpty(keys.Content.ApiKey);
            Assert.IsNotNullOrEmpty(keys.Content.SecretKey);
            Assert.IsNotNullOrEmpty(keys.Content.SessionLogoutTime.ToString());

            IUserRepository userRepository = (IUserRepository)_applicationContext["UserRepository"];
            User            userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            Assert.AreEqual(currentHour, userByUserName.LastLogin.Hour);
        }
Ejemplo n.º 25
0
        public async Task User_registration_controller()
        {
            //Arrange
            var userManager   = new Mock <FakeUserManager>();
            var signInManager = new Mock <FakeSignInManager>();
            var logger        = new Mock <ILogger <RegistrationController> >();
            var emailSender   = new Mock <IEmailSender>();

            var returnUrl = "http://returnurl.com";

            userManager.SetupCreateUserWithSuccessResult();

            var controller = new RegistrationController(userManager.Object, signInManager.Object, logger.Object, emailSender.Object);

            //Act
            var result = await controller.Register(new RegisterModel2 { Input = new RegisterModel2.InputModel {
                                                                            Email = "*****@*****.**", Password = "******"
                                                                        } }, returnUrl : returnUrl) as ViewResult;

            //Assert
            Assert.Same("ConfirmRegistration", result.ViewName);
            Assert.Same(returnUrl, result.ViewData["ReturnUrl"]);
        }
Ejemplo n.º 26
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            RegistrationController controller = new RegistrationController();

            if (txtPasswordRepeat.Password != txtPassword.Password)
            {
                MessageBox.Show("пароли не совпадают");
                return;
            }
            Client user = new Client(txtUsername.Text, txtPassword.Password, txtUserEmail.Text);

            user.maxCount   = 1;
            user.role       = 0;
            user.ChatId     = 0;
            user.isActive   = false;
            user.key        = GetPhoto.GenRandomString(10);
            user.LastUpdate = DateTime.Parse("01 01 2019");
            controller.Register(user);
            if (new LoginControl().login(user))
            {
                EntryWindow parentWindow = Window.GetWindow(this) as EntryWindow;
                parentWindow.Close();
            }
        }
Ejemplo n.º 27
0
 private void RegisterButton_Click(object sender, RoutedEventArgs e)
 {
     registrationController.Register();
     Frame.Navigate(typeof(PendingApproval), null);
 }
        public async Task UsersShouldBeAbleToRegisterIfAllowed()
        {
            var mockUserManager = UsersMockHelper.MockUserManager <IUser>().Object;
            var settings        = new RegistrationSettings {
                UsersCanRegister = UserRegistrationType.AllowRegistration
            };
            var mockSiteService = Mock.Of <ISiteService>(ss =>
                                                         ss.GetSiteSettingsAsync() == Task.FromResult(
                                                             Mock.Of <ISite>(s => s.Properties == JObject.FromObject(new { RegistrationSettings = settings }))
                                                             )
                                                         );
            var mockSmtpService = Mock.Of <ISmtpService>();

            var controller = new RegistrationController(
                mockUserManager,
                Mock.Of <IAuthorizationService>(),
                mockSiteService,
                Mock.Of <INotifier>(),
                Mock.Of <IEmailAddressValidator>(),
                Mock.Of <ILogger <RegistrationController> >(),
                Mock.Of <IHtmlLocalizer <RegistrationController> >(),
                Mock.Of <IStringLocalizer <RegistrationController> >());

            var mockServiceProvider = new Mock <IServiceProvider>();

            mockServiceProvider
            .Setup(x => x.GetService(typeof(ISmtpService)))
            .Returns(mockSmtpService);
            mockServiceProvider
            .Setup(x => x.GetService(typeof(UserManager <IUser>)))
            .Returns(mockUserManager);
            mockServiceProvider
            .Setup(x => x.GetService(typeof(ISiteService)))
            .Returns(mockSiteService);
            mockServiceProvider
            .Setup(x => x.GetService(typeof(IEnumerable <IRegistrationFormEvents>)))
            .Returns(Enumerable.Empty <IRegistrationFormEvents>());
            mockServiceProvider
            .Setup(x => x.GetService(typeof(IUserService)))
            .Returns(Mock.Of <IUserService>());
            mockServiceProvider
            .Setup(x => x.GetService(typeof(SignInManager <IUser>)))
            .Returns(MockSignInManager(mockUserManager).Object);
            mockServiceProvider
            .Setup(x => x.GetService(typeof(ITempDataDictionaryFactory)))
            .Returns(Mock.Of <ITempDataDictionaryFactory>());
            mockServiceProvider
            .Setup(x => x.GetService(typeof(IObjectModelValidator)))
            .Returns(Mock.Of <IObjectModelValidator>());

            var mockHttpContext = new Mock <HttpContext>();

            mockHttpContext
            .Setup(x => x.RequestServices)
            .Returns(mockServiceProvider.Object);

            controller.ControllerContext.HttpContext = mockHttpContext.Object;

            var result = await controller.Register();

            Assert.IsType <ViewResult>(result);

            // Post
            result = await controller.Register(new RegisterViewModel());

            Assert.IsType <ViewResult>(result);
        }