public void ChangePasswordSuccessTest_ChecksIfThePasswordIsChangedSuccessfully_VeririesThroughTheReturnedValue()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            // Store the Securiyty Keys with the Username of the User at hand
            (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair(
                                                                                           new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true));

            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(new User("*****@*****.**", "linkinpark",
                                                                    passwordEncryptionService.EncryptPassword("burnitdown"), "USA", TimeZone.CurrentTimeZone, "", ""));

            User   userBeforePasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordBeforeChange     = userBeforePasswordChange.Password;

            // Give the API key that is already stored in the Security keys repository mentioned with the User Name
            //UserValidationEssentials userValidationEssentials = new UserValidationEssentials(new Tuple<ApiKey, SecretKey>(
            //    new ApiKey("123456789"), new SecretKey("987654321")), new TimeSpan(0,0,10,0));

            ChangePasswordResponse changePasswordResponse = userApplicationService.ChangePassword(new ChangePasswordCommand(
                                                                                                      "123456789", "burnitdown", "burnitdowntwice"));

            Assert.IsTrue(changePasswordResponse.ChangeSuccessful);
            User   userAfterPasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordAfterChange     = userAfterPasswordChange.Password;

            // Verify the old and new password do not match
            Assert.AreNotEqual(passwordBeforeChange, passwordAfterChange);
        }
        public void DeveEncriptarTexto()
        {
            var texto = Guid.NewGuid().ToString();
            var hash  = new PasswordEncryptionService().EncryptPassword(texto);

            Assert.AreNotEqual(texto, hash);
        }
        public void ActivateAccountFailDueToBlankPasswordTest_MakesSureThatTheAccountIsNotActivatedWhenBlankPasswordIsGiven_VeririesThroughTheReturnedValue()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            // Store the Securiyty Keys with the Username of the User at hand
            (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair(
                                                                                           new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true));

            string activationKey = "123456789";
            string username      = "******";
            string password      = "******";
            User   user          = new User("*****@*****.**", username,
                                            passwordEncryptionService.EncryptPassword(password), "USA", TimeZone.CurrentTimeZone,
                                            "", activationKey);

            user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0));
            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(user);

            userApplicationService.ActivateAccount(new ActivationCommand(activationKey, username, password + "pass"));
        }
Example #4
0
        public void CreateUser_CreatesSuccessfully()
        {
            //Arrange
            string passwordToEncrypt = "thisisencrypted";
            var    encryptedPassword = new PasswordEncryptionService().SetPassword(passwordToEncrypt);
            var    user = new User()
            {
                FirstName    = "John",
                LastName     = "Smith",
                Email        = "*****@*****.**",
                DateOfBirth  = DateTime.Now.AddYears(-20),
                IsSubscribed = false,
                Password     = passwordToEncrypt,
                RoleId       = 3
            };

            mockPasswordEncryptionService
            .Setup(p => p.SetPassword(user.Password))
            .Returns(encryptedPassword);

            //Act
            var result = userRepository.CreateUser(user);

            //Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Id > 0);
            Assert.IsTrue(result.Email == user.Email);
            Assert.IsTrue(result.DateOfBirth == user.DateOfBirth);
            Assert.IsTrue(result.FirstName == user.FirstName);
            Assert.IsTrue(result.LastName == user.LastName);
            Assert.IsTrue(result.Password == user.Password);
            Assert.IsTrue(result.RoleId == user.RoleId);
        }
Example #5
0
        private async Task DoLogin()
        {
            var loginResult = await _edsWebApiService.LoginAsync(Email, SecurePassword);

            if (loginResult != null)
            {
                IsLoggedIn    = true;
                IsNotLoggedIn = false;
                _appSettingsService.GetSettings().Email = Email;
            }
            else
            {
                IsNotLoggedIn = true;
            }

            if ((loginResult != null) && StorePassword)
            {
                _appSettingsService.GetSettings().ProtectedPassword = PasswordEncryptionService.Protect(SecurePassword);
            }
            else
            {
                _appSettingsService.GetSettings().ProtectedPassword = string.Empty;
            }

            _appSettingsService.SaveSettings();
        }
Example #6
0
        public LoginViewModel(IAppSettingsService appSettingsService, IEdsWebApiService edsWebApiService)
        {
            _appSettingsService = appSettingsService;
            _edsWebApiService   = edsWebApiService;

            Email          = _appSettingsService.GetSettings().Email;
            StorePassword  = !string.IsNullOrEmpty(_appSettingsService.GetSettings().ProtectedPassword);
            SecurePassword =
                PasswordEncryptionService.UnProtectToSecureString(_appSettingsService.GetSettings().ProtectedPassword);

            _loginEnabled = this.WhenAnyValue(
                x => x.Email,
                x => x.SecurePassword,
                x => x.IsLoggedIn,
                (email, securePassword, isLoggedIn) =>
                !isLoggedIn &&
                !string.IsNullOrEmpty(email) &&
                (securePassword.Length != 0)).ToProperty(this, x => x.LoginEnabled);

            LoginCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                await DoLogin();
            }, this.WhenAnyValue(x => x.LoginEnabled));

            LoginCommand.ThrownExceptions.Subscribe(ex => MessageBus.Current.SendMessage(ex));
        }
Example #7
0
        public ActionResult Login(AccountLoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = _readOnlyRepository.FirstOrDefault <User>(x => x.Email == model.Email);
                if (user != null)
                {
                    if (PasswordEncryptionService.CheckPassword(user, model.Password))
                    {
                        var ticket = new FormsAuthenticationTicket(1, user.Name, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, user.Email, FormsAuthentication.FormsCookiePath);

                        // Encrypt the ticket.
                        string encTicket = FormsAuthentication.Encrypt(ticket);

                        // Create the cookie.
                        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                            !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            return(Redirect(returnUrl));
                        }
                        return(RedirectToAction("Index", "Synergy"));
                    }
                }
                ModelState.AddModelError("", "The e-mail address or password provided is incorrect.");
            }
            return(View(model));
        }
        public void CancelAccountActivationSuccessfulTest_MakesSureAccountActivationGetsCancelledWhenEverythingIsGivenAsExpected_VerifiesByReturnedValueAndQueryingRepository()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            string activationKey = "123456789";
            string username      = "******";
            string password      = "******";
            User   user          = new User("*****@*****.**", username, passwordEncryptionService.EncryptPassword(password),
                                            "USA", TimeZone.CurrentTimeZone, "", activationKey);

            user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0));
            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(user);

            bool accountActivationCancelled = userApplicationService.CancelAccountActivation(new CancelActivationCommand(activationKey));

            Assert.IsTrue(accountActivationCancelled);

            User userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNull(userByUserName);
        }
        public void LoginSuccessfulTest_ChecksIfTheSecurityKeysAreProperlyReturnedWhileLoggingIn_VerifiesTheReturnedKeysToConfirm()
        {
            IUserRepository userRepository = new MockUserRepository();
            IIdentityAccessPersistenceRepository persistRepository = new MockPersistenceRepository(false);
            ISecurityKeysApplicationService      securityKeysApplicationService = new SecurityKeysApplicationService(new SecurityKeysGenerationService(),
                                                                                                                     persistRepository, null, null);
            IPasswordEncryptionService passwordEncryptionService   = new PasswordEncryptionService();
            IMfaAuthorizationService   mockMfaAuthorizationService = new MockMfaAuthorizationService();
            ILoginApplicationService   loginApplicationService     = new LoginApplicationService(userRepository, passwordEncryptionService,
                                                                                                 securityKeysApplicationService, new MockPersistenceRepository(false), mockMfaAuthorizationService);

            string enteredPassword = "******";
            User   user            = new User("*****@*****.**", "brucewayne", passwordEncryptionService.EncryptPassword(enteredPassword),
                                              "Ninja County", TimeZone.CurrentTimeZone, "", "");

            user.AutoLogout          = new TimeSpan(0, 0, 0, 60);
            user.IsActivationKeyUsed = new IsActivationKeyUsed(true);
            // Add this user to the MockUserRepository
            (userRepository as MockUserRepository).AddUser(user);
            UserValidationEssentials userValidationEssentials = loginApplicationService.Login(
                new LoginCommand("brucewayne", enteredPassword));

            Assert.IsNotNull(userValidationEssentials);
            Assert.IsNotNull(userValidationEssentials.ApiKey);
            Assert.IsNotNull(userValidationEssentials.SecretKey);
            Assert.AreEqual(userValidationEssentials.SessionLogoutTime, user.AutoLogout);
        }
        public void ActivateAccountSuccessTest_ChecksIfTheAccountIsActivatedSuccessfully_VeririesThroughTheReturnedValue()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            // Store the Securiyty Keys with the Username of the User at hand
            (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair(
                                                                                           new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true));

            string activationKey = "123456789";
            string username      = "******";
            string password      = "******";
            User   user          = new User("*****@*****.**", username,
                                            passwordEncryptionService.EncryptPassword(password), "USA", TimeZone.CurrentTimeZone,
                                            "", activationKey);

            user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0));
            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(user);

            bool changeSuccessful = userApplicationService.ActivateAccount(new ActivationCommand(activationKey, username, password));

            Assert.IsTrue(changeSuccessful);
            User user1 = (persistenceRepository as MockPersistenceRepository).GetUser(username);

            Assert.IsNotNull(user1);
            Assert.IsTrue(user1.IsActivationKeyUsed.Value);
            Assert.IsFalse(user1.IsUserBlocked.Value);
        }
        public void DeveReconhecerSenhaEncriptada()
        {
            var texto             = Guid.NewGuid().ToString();
            var encryptionService = new PasswordEncryptionService();
            var hash = encryptionService.EncryptPassword(texto);

            Assert.IsTrue(encryptionService.ComparePasswords(texto, hash));
        }
        public void CancelAccountActivationFailedBecasueNoSuchAccountExists_MakesSureTHisDoesntCreateAnyBreach_VerifiesByExpectingException()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            userApplicationService.CancelAccountActivation(new CancelActivationCommand("123ffdsdsaewr43212"));
        }
Example #13
0
        public void DeveCriarUsuarioComParametrosPassadosNoContrutorIdEListaDeTelefonesCriada()
        {
            var usuario           = new Usuario(NOME, EMAIL, PASSWORD);
            var encryptedPassword = new PasswordEncryptionService().EncryptPassword(PASSWORD);

            Assert.IsTrue(Guid.Empty != usuario.Id);
            Assert.IsFalse(usuario.Telefones == null);
            Assert.IsFalse(usuario.Telefones.Any());
            Assert.AreEqual(NOME, usuario.Nome);
            Assert.AreEqual(EMAIL, usuario.Email);
            Assert.AreEqual(encryptedPassword, usuario.Senha);
        }
Example #14
0
        public void EncryptPasswordTwiceAndCompareTest_EncryptsAPasswordTwiceAndThenComparesBothToBeTheSame_FailsIfNotEqual()
        {
            PasswordEncryptionService passwordEncryption = new PasswordEncryptionService();
            string password      = "******";
            string hasedPassword = passwordEncryption.EncryptPassword(password);

            Assert.IsNotNull(hasedPassword);

            string samePassword = "******";

            Assert.IsTrue(passwordEncryption.VerifyPassword(samePassword, hasedPassword));
        }
Example #15
0
        public void CompareFalseEncrytionTest_EncryptsAPasswordTwiceAndThenComparesBothToBeDifferentByVerifyMethod_FailsIfTheyAreEqual()
        {
            PasswordEncryptionService passwordEncryption = new PasswordEncryptionService();
            string password       = "******";
            string hashedPassword = passwordEncryption.EncryptPassword(password);

            Assert.IsNotNull(hashedPassword);

            // Last letter is different
            string secondPassword = "******";

            Assert.IsFalse(passwordEncryption.VerifyPassword(secondPassword, hashedPassword));
        }
        public void EncryptTest()
        {
            var service = new PasswordEncryptionService();

            var password = "******";

            var salt = service.GetSalt();

            var encrypted    = service.Encrypt(password, salt);
            var newEncrypted = service.Encrypt("abc", salt);

            Assert.AreEqual(encrypted, encrypted);
        }
Example #17
0
        public void Seed()
        {
            var account = new User
            {
                Email    = "*****@*****.**",
                Name     = "Administrator",
                Password = "******",
                IsAdmin  = true
            };

            PasswordEncryptionService.Encrypt(account);
            _session.Save(account);
        }
Example #18
0
        public void CompareFalseEncrytionTest_EncryptsAPasswordTwiceAndThenComparesBothToBeDifferent_FailsIfTheyAreEqual()
        {
            PasswordEncryptionService passwordEncryption = new PasswordEncryptionService();
            string password        = "******";
            string encryptPassword = passwordEncryption.EncryptPassword(password);

            Assert.IsNotNull(encryptPassword);

            // Last letter is different
            string secondPassword        = "******";
            string secondEncryptPassword = passwordEncryption.EncryptPassword(secondPassword);

            Assert.IsNotNull(secondEncryptPassword);

            Assert.AreNotEqual(encryptPassword, secondEncryptPassword);
        }
        public void DeveGerarHashesIguaisVariasVezes()
        {
            var texto = Guid.NewGuid().ToString();
            var hash1 = new PasswordEncryptionService().EncryptPassword(texto);
            var hash2 = new PasswordEncryptionService().EncryptPassword(texto);

            var passwordEncryptionService = new PasswordEncryptionService();
            var hash3 = passwordEncryptionService.EncryptPassword(texto);
            var hash4 = passwordEncryptionService.EncryptPassword(texto);

            Assert.AreEqual(hash1, hash2, "Hash 1 e 2 são diferentes");
            Assert.AreEqual(hash3, hash4, "Hash 3 e 4 são diferentes");
            Assert.AreEqual(hash1, hash3, "Hash 1 e 3 são diferentes");
            Assert.AreEqual(hash1, hash4, "Hash 1 e 4 são diferentes");
            Assert.AreEqual(hash2, hash3, "Hash 2 e 3 são diferentes");
            Assert.AreEqual(hash2, hash4, "Hash 2 e 4 são diferentes");
        }
Example #20
0
        public void EncryptPasswordTest_EncryptsTwoPasswordAndCheckifNotNullAndLength_VerifiesThroughHashedValues()
        {
            PasswordEncryptionService passwordEncryption = new PasswordEncryptionService();
            string password        = "******";
            string encryptPassword = passwordEncryption.EncryptPassword(password);

            Assert.IsNotNull(encryptPassword);
            Assert.AreNotEqual(password, encryptPassword);

            string secondPassword        = "******";
            string secondEncryptPassword = passwordEncryption.EncryptPassword(secondPassword);

            Assert.IsNotNull(secondEncryptPassword);
            Assert.AreNotEqual(secondPassword, secondEncryptPassword);

            Assert.AreEqual(encryptPassword.Length, secondEncryptPassword.Length);
        }
        public async Task <bool> ChangePassword(UserChangePassDTO userInfo)
        {
            using (_unitOfWork)
            {
                User user = await _unitOfWork.UserRepository.FindByID(userInfo.UserId);

                if (!PasswordEncryptionService.IsPasswordCorrect(user.Password, userInfo.OldPassword, _appSettings.SaltLength))
                {
                    return(false);
                }

                user.Password = PasswordEncryptionService.EncryptPassword(userInfo.NewPassword, _appSettings.SaltLength);
                _unitOfWork.UserRepository.Update(user);

                return(await _unitOfWork.Save());
            }
        }
        public void LoginFailDueToBlankPasswordTest_MakesSureLoginFailsInCaseOfBlankPassword_VerifiesTheReturnedNullResultToConfirm()
        {
            IUserRepository userRepository = new MockUserRepository();
            IIdentityAccessPersistenceRepository persistRepository = new MockPersistenceRepository(false);
            ISecurityKeysApplicationService      securityKeysApplicationService = new SecurityKeysApplicationService(new SecurityKeysGenerationService(),
                                                                                                                     persistRepository, null, null);
            IPasswordEncryptionService passwordEncryptionService   = new PasswordEncryptionService();
            IMfaAuthorizationService   mockMfaAuthorizationService = new MockMfaAuthorizationService();
            ILoginApplicationService   loginApplicationService     = new LoginApplicationService(userRepository, passwordEncryptionService,
                                                                                                 securityKeysApplicationService, new MockPersistenceRepository(false), mockMfaAuthorizationService);
            string enteredPassword = "******";
            User   user            = new User("*****@*****.**", "brucewayne", passwordEncryptionService.EncryptPassword(enteredPassword),
                                              "Ninja County", TimeZone.CurrentTimeZone, "", "");

            user.AutoLogout = new TimeSpan(0, 0, 0, 60);
            // Add this user to the MockUserRepository
            (userRepository as MockUserRepository).AddUser(user);

            loginApplicationService.Login(new LoginCommand("brucewayne", ""));
        }
        public async Task <UserAuthenticateResponseDTO> AddUserAccount(UserRegisterDTO userInfo)
        {
            using (_unitOfWork)
            {
                if (_unitOfWork.UserRepository.UsernameTaken(userInfo.Username))
                {
                    return(null);
                }

                userInfo.Password = PasswordEncryptionService.EncryptPassword(userInfo.Password, _appSettings.SaltLength);
                User newUser = _mapper.Map <UserRegisterDTO, User>(userInfo);
                await _unitOfWork.UserRepository.Create(newUser);

                await _unitOfWork.Save();

                UserAuthenticateResponseDTO returnUser = _mapper.Map <User, UserAuthenticateResponseDTO>(newUser);
                returnUser.Token = _tokenManager.GenerateToken(newUser.UserId);
                returnUser.UnseenNotifications = _unitOfWork.UserRepository.GetUnseenNotificationNumber(newUser.UserId);
                return(returnUser);
            }
        }
        public async Task <UserAuthenticateResponseDTO> LogUserIn(UserLoginDTO userInfo)
        {
            using (_unitOfWork)
            {
                User user = await _unitOfWork.UserRepository.GetUserByUsername(userInfo.Username);

                if (user == null)
                {
                    return(null);
                }
                if (!PasswordEncryptionService.IsPasswordCorrect(user.Password, userInfo.Password, _appSettings.SaltLength))
                {
                    return(null);
                }

                UserAuthenticateResponseDTO returnUser = _mapper.Map <User, UserAuthenticateResponseDTO>(user);
                returnUser.Token = _tokenManager.GenerateToken(user.UserId);
                returnUser.UnseenNotifications = _unitOfWork.UserRepository.GetUnseenNotificationNumber(user.UserId);
                return(returnUser);
            }
        }
        public void CancelAccountActivationFailedDueToBlankActivationKey_MakesSureAccountActivationDoesNotGetCancelledWhenBlankActivationKeyIsGiven_VerifiesByExpectingException()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            string activationKey = "123456789";
            string username      = "******";
            string password      = "******";
            User   user          = new User("*****@*****.**", username, passwordEncryptionService.EncryptPassword(password),
                                            "USA", TimeZone.CurrentTimeZone, "", activationKey);

            user.AddTierStatus(Status.NonVerified, new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0));
            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(user);

            userApplicationService.CancelAccountActivation(new CancelActivationCommand(""));
        }
        //[ExpectedException(typeof(Exception))]
        public void ChangePasswordFailDueToSessionTimeoutTest_ChecksThePasswordDoesNotGetChangedWhenSessionTimeoutHasExpired_VerifiesByExpectingException()
        {
            IUserRepository                      userRepository            = new MockUserRepository();
            ISecurityKeysRepository              securityKeysRepository    = new MockSecurityKeysRepository();
            IPasswordEncryptionService           passwordEncryptionService = new PasswordEncryptionService();
            IIdentityAccessPersistenceRepository persistenceRepository     = new MockPersistenceRepository(false);
            UserApplicationService               userApplicationService    = new UserApplicationService(userRepository, securityKeysRepository,
                                                                                                        passwordEncryptionService, persistenceRepository, new MockEmailService(), new PasswordCodeGenerationService());

            // Store the Securiyty Keys with the Username of the User at hand
            (securityKeysRepository as MockSecurityKeysRepository).AddSecurityKeysPair(new SecurityKeysPair(
                                                                                           new ApiKey("123456789").Value, new SecretKey("987654321").Value, "desc", 0, true));

            var user = new User("*****@*****.**", "linkinpark", passwordEncryptionService.EncryptPassword("burnitdown"), "USA", TimeZone.CurrentTimeZone, "", "");

            // We need to encrypt the password in the test case ourselves, as we are not registering the user through
            // the proper service here
            (userRepository as MockUserRepository).AddUser(user);

            User   userBeforePasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordBeforeChange     = userBeforePasswordChange.Password;

            // Give the API key that is already stored in the Security keys repository mentioned with the User Name
            //UserValidationEssentials userValidationEssentials = new UserValidationEssentials(new Tuple<ApiKey, SecretKey>(
            //    new ApiKey("123456789"), new SecretKey("987654321")), new TimeSpan(0, 0, 0, 0, 1));
            (userRepository as MockUserRepository).DeleteUser(user);
            user.AutoLogout = new TimeSpan(0, 0, 0, 0, 1);
            (userRepository as MockUserRepository).AddUser(user);

            // Wrong password given
            userApplicationService.ChangePassword(new ChangePasswordCommand("123456789", "burnitdown",
                                                                            "burnitdowntwice"));
            User   userAfterPasswordChange = userRepository.GetUserByUserName("linkinpark");
            string passwordAfterChange     = userAfterPasswordChange.Password;

            // Verify the old and new password do not match
            Assert.AreNotEqual(passwordBeforeChange, passwordAfterChange);
        }
Example #27
0
 public ActionResult Register(AccountRegisterModel model)
 {
     if (ModelState.IsValid)
     {
         var testEmail = _readOnlyRepository.FirstOrDefault <User>(x => x.Email == model.Email);
         if (testEmail != null)
         {
             ModelState.AddModelError("", "An account with that e-mail address already exists!");
             return(View(model));
         }
         var newUser = new User
         {
             Email    = model.Email,
             Name     = model.Name,
             Password = model.Password,
             IsAdmin  = false
         };
         PasswordEncryptionService.Encrypt(newUser);
         _writeOnlyRepository.Create(newUser);
         return(RedirectToAction("Login"));
     }
     return(View(model));
 }
Example #28
0
 public void Init()
 {
     passwordEncryptionService = new PasswordEncryptionService();
 }
Example #29
0
 public void AlterarSenha(string novaSenha)
 {
     Senha = new PasswordEncryptionService().EncryptPassword(novaSenha);
 }
        internal bool LoadData(ECommerceContextDb context, bool isUnitTest = false)
        {
            try
            {
                if (context.Categories.Count() == 0)
                {
                    var listCategories = new List <Category>()
                    {
                        new Category {
                            Id = 1, CategoryName = "New Releases"
                        },
                        new Category {
                            Id = 2, CategoryName = "Men"
                        },
                        new Category {
                            Id = 3, CategoryName = "Women"
                        },
                        new Category {
                            Id = 4, CategoryName = "Unisex"
                        },
                    };

                    listCategories.ForEach(p => context.Categories.Add(p));
                    context.SaveChanges();
                }

                if (context.Brands.Count() == 0)
                {
                    var listBrands = new List <Brand>()
                    {
                        new Brand {
                            Id = 1, BrandName = "Nike"
                        },
                        new Brand {
                            Id = 2, BrandName = "Adidas"
                        },
                        new Brand {
                            Id = 3, BrandName = "Onnit"
                        }
                    };

                    listBrands.ForEach(p => context.Brands.Add(p));
                    context.SaveChanges();
                }

                if (context.OrderStatus.Count() == 0)
                {
                    var listOrderStatus = new List <OrderStatus>()
                    {
                        new OrderStatus {
                            Id = 1, Status = "Ongoing"
                        },
                        new OrderStatus {
                            Id = 2, Status = "Completed"
                        },
                        new OrderStatus {
                            Id = 3, Status = "Abandoned"
                        }
                    };

                    listOrderStatus.ForEach(p => context.OrderStatus.Add(p));
                    context.SaveChanges();
                }

                if (context.ProductTypes.Count() == 0)
                {
                    var listProductType = new List <ProductType>()
                    {
                        new ProductType {
                            Id = 1, ProductTypeName = "Shoes"
                        },
                        new ProductType {
                            Id = 2, ProductTypeName = "Headwear"
                        },
                        new ProductType {
                            Id = 3, ProductTypeName = "T-Shirts"
                        }
                    };

                    listProductType.ForEach(p => context.ProductTypes.Add(p));
                    context.SaveChanges();
                }

                if (!isUnitTest)
                {
                    if (context.Products.Count() == 0)
                    {
                        var listProducts = new List <Product>()
                        {
                            new Product {
                                Id         = 1, Brand = context.Brands.SingleOrDefault(p => p.Id == 1), HeroImage = GetHeroImage(1), HeroTitle = "Nike Air Zoom Pegasus 37", Title = "Nike Air Zoom Pegasus 37", Description = GetDescription(1),
                                CategoryId = 1, Gender = GenderEnum.Male.ToString(),
                                Images     = GetImages(1), ProductType = context.ProductTypes.SingleOrDefault(p => p.Id == 1), Sizes = GetProductSizes(1), Price = 200
                            },
                            new Product {
                                Id         = 2, Brand = context.Brands.SingleOrDefault(p => p.Id == 1), HeroImage = GetHeroImage(2), HeroTitle = "Nike Mercurial Superfly 7 Elite MDS FG", Title = "Nike Mercurial Superfly 7 Elite MDS FG", Description = GetDescription(2),
                                CategoryId = 2, Gender = GenderEnum.Male.ToString(),
                                Images     = GetImages(2), ProductType = context.ProductTypes.SingleOrDefault(p => p.Id == 1), Sizes = GetProductSizes(2), Price = 370
                            },
                            new Product {
                                Id         = 3, Brand = context.Brands.SingleOrDefault(p => p.Id == 1), HeroImage = GetHeroImage(3), HeroTitle = "Nike Zoom Pegasus Turbo 2", Title = "Nike Zoom Pegasus Turbo 2", Description = GetDescription(3),
                                CategoryId = 3, Gender = GenderEnum.Male.ToString(),
                                Images     = GetImages(3), ProductType = context.ProductTypes.SingleOrDefault(p => p.Id == 1), Sizes = GetProductSizes(3), Price = 260
                            },

                            //TODO : Add these later - let's just get the site up and running with data
                            //new Product { Id = 4, Brand = context.Brands.Where(p => p.Id == 2).SingleOrDefault(), HeroImage = "", HeroTitle = "", Images = GetImages(4) },
                            //new Product { Id = 5, Brand = context.Brands.Where(p => p.Id == 2).SingleOrDefault(), HeroImage = "", HeroTitle = "", Images = GetImages(5) },
                            //new Product { Id = 6, Brand = context.Brands.Where(p => p.Id == 2).SingleOrDefault(), HeroImage = "", HeroTitle = "", Images = GetImages(6) },

                            //new Product { Id = 7, Brand = context.Brands.Where(p => p.Id == 3).SingleOrDefault(), HeroImage = "", HeroTitle = "", Images = GetImages(7) },
                            //new Product { Id = 8, Brand = context.Brands.Where(p => p.Id == 3).SingleOrDefault(), HeroImage = "", HeroTitle = "", Images = GetImages(8) },
                            //new Product { Id = 9, Brand = context.Brands.Where(p => p.Id == 3).SingleOrDefault(), HeroImage = "", HeroTitle = "", Images = GetImages(9) },
                        };

                        listProducts.ForEach(p => context.Products.Add(p));
                        context.SaveChanges();
                    }
                }

                if (context.Roles.Count() == 0)
                {
                    var listRoles = new List <Role>()
                    {
                        new Role {
                            Id = 1, RoleName = "Administrator"
                        },
                        new Role {
                            Id = 2, RoleName = "SuperUser"
                        },
                        new Role {
                            Id = 3, RoleName = "User"
                        }
                    };

                    listRoles.ForEach(p => context.Roles.Add(p));
                    context.SaveChanges();
                }

                var passwordEncryptionService = new PasswordEncryptionService();

                if (context.Users.Count() == 0)
                {
                    var listUsers = new List <User>()
                    {
                        new User {
                            Id = 1, Email = "*****@*****.**", CreatedDate = DateTime.Now, DateOfBirth = DateTime.Now, FirstName = "Admin", LastName = "ECommerce", IsSubscribed = false, Password = passwordEncryptionService.SetPassword("thisisencrypted"), RoleId = 1
                        },
                        new User {
                            Id = 2, Email = "*****@*****.**", CreatedDate = DateTime.Now, DateOfBirth = DateTime.Now, FirstName = "Superuser", LastName = "ECommerce", IsSubscribed = false, Password = passwordEncryptionService.SetPassword("thisisencrypted"), RoleId = 2
                        }
                    };

                    listUsers.ForEach(p => context.Users.Add(p));
                    context.SaveChanges();
                }

                return(true);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }