Ejemplo n.º 1
0
        public void Login___should_return_null___when_password_is_incorrect()
        {
            var password = "******";
            var user     = TestData.User();

            user.Username = "******";
            var hash       = PasswordHasher.GenerateSaltedHash(password, user.Salt);
            var storedHash = PasswordHasher.GenerateSaltedHash("an_incorrect_password", user.Salt);

            var expectedSessionId = Guid.NewGuid();

            _authStore.Setup(a => a.GetUserByName(user.Username))
            .Returns(user);

            _authStore.Setup(a => a.GetPasswordHash(user.Id))
            .Returns(storedHash)
            .Verifiable();

            _authStore.Setup(a => a.CreateNewSession(user.Id))
            .Throws(new Exception("should not create session"));

            var actualSessionId = _authenticationService.Login(user.Username, password);

            Assert.AreEqual(null, actualSessionId);

            _authStore.Verify();
        }
Ejemplo n.º 2
0
        public void Login___should_increment_failed_count___when_password_is_incorrect()
        {
            var password = "******";
            var user     = TestData.User();

            user.Username = "******";
            var hash       = PasswordHasher.GenerateSaltedHash(password, user.Salt);
            var storedHash = PasswordHasher.GenerateSaltedHash("an_incorrect_password", user.Salt);

            var expectedSessionId = Guid.NewGuid();

            user.FailedLoginCount = 0;

            _authStore.Setup(a => a.GetUserByName(user.Username))
            .Returns(user);

            _authStore.Setup(a => a.GetPasswordHash(user.Id))
            .Returns(storedHash)
            .Verifiable();

            _authStore.Setup(a => a.SaveUser(It.Is <User>(s => s.FailedLoginCount == 1)))
            .Verifiable();

            _authenticationService.Login(user.Username, password);

            _authStore.Verify();
        }
Ejemplo n.º 3
0
        public void Login___should_reset_failed_count___when_details_correct_and_fail_count_is_greaterthan_zero()
        {
            var password = "******";
            var user     = TestData.User();

            user.Username = "******";
            var hash = PasswordHasher.GenerateSaltedHash(password, user.Salt);
            var expectedSessionId = Guid.NewGuid();

            user.FailedLoginCount = 1;

            _authStore.Setup(a => a.GetUserByName(user.Username))
            .Returns(user)
            .Verifiable();

            _authStore.Setup(a => a.GetPasswordHash(user.Id))
            .Returns(hash)
            .Verifiable();

            _authStore.Setup(a => a.CreateNewSession(user.Id))
            .Returns(expectedSessionId)
            .Verifiable();

            _authStore.Setup(a => a.SaveUser(It.Is <User>(u => u.FailedLoginCount == 0)))
            .Verifiable();

            var actualSessionId = _authenticationService.Login(user.Username, password);

            Assert.AreEqual(expectedSessionId, actualSessionId);

            _authStore.VerifyAll();
        }
Ejemplo n.º 4
0
        public void Verify___when_valid___should_store_hashed_password_and_generate_salt()
        {
            var existingUser = TestData.User();
            var emailVerify  = existingUser.EmailVerificationPath;
            var twofactor    = existingUser.TwoFactorCode;
            var password     = "******";

            existingUser.Salt = "";

            _authStore.Setup(a => a.GetUserByEmailVerificationPath(emailVerify))
            .Returns(existingUser);

            _authStore.Setup(a =>
                             a.SaveUser(It.Is <User>(u => u.Salt.Length > 0)))
            .Verifiable();

            // ned to get this lazily, as salt is changed by service...
            Func <byte[]> expectedHash = () => PasswordHasher.GenerateSaltedHash(password, existingUser.Salt);

            _authStore.Setup(a =>
                             a.SavePasswordHash(existingUser.Id, It.Is <byte[]>(h => PasswordHasher.CompareByteArrays(expectedHash(), h)))
                             ).Verifiable();


            var result = _authenticationService.Verify(emailVerify, password, twofactor);

            Assert.IsTrue(result);
            _authStore.Verify();
        }
Ejemplo n.º 5
0
        public void Login___should_return_sessionId_from_store___when_details_correct()
        {
            var password = "******";
            var user     = TestData.User();

            user.Username = "******";
            var hash = PasswordHasher.GenerateSaltedHash(password, user.Salt);
            var expectedSessionId = Guid.NewGuid();

            _authStore.Setup(a => a.GetUserByName(user.Username))
            .Returns(user)
            .Verifiable();

            _authStore.Setup(a => a.GetPasswordHash(user.Id))
            .Returns(hash)
            .Verifiable();

            _authStore.Setup(a => a.CreateNewSession(user.Id))
            .Returns(expectedSessionId)
            .Verifiable();

            var actualSessionId = _authenticationService.Login(user.Username, password);

            Assert.AreEqual(expectedSessionId, actualSessionId);

            _authStore.VerifyAll();
        }
Ejemplo n.º 6
0
        public async Task <Users> ChangePassword([FromForm] Users user)
        {
            PasswordHasher hasher            = new PasswordHasher();
            var            submittedPassword = user.Password;
            var            newPassword       = user.PasswordSalt;
            var            dbUser            = await _context.Users.FirstOrDefaultAsync(u => u.UserId == user.UserId);

            if (dbUser == null)
            {
                return(null);
            }


            if (hasher.VerifyHash(submittedPassword, dbUser.PasswordSalt, dbUser.Password))
            {
                dbUser.PasswordSalt = hasher.RandomSalt;
                dbUser.Password     = hasher.GenerateSaltedHash(newPassword);
            }
            else
            {
                return(null);
            }

            await _context.SaveChangesAsync();

            return(user);
        }
Ejemplo n.º 7
0
        public async Task <Users> Post([FromForm] Users user)
        {
            var newUser = user;

            PasswordHasher hasher = new PasswordHasher();

            newUser.PasswordSalt = hasher.RandomSalt;
            newUser.Password     = hasher.GenerateSaltedHash(newUser.Password);

            await _context.Users.AddAsync(newUser);

            await _context.SaveChangesAsync();

            return(newUser);
        }
Ejemplo n.º 8
0
        public void GenerateSaltedHash_NonEmptyPassword_ShouldReturnNonEmptySaltAndHash()
        {
            //  arrange
            var    hasher   = new PasswordHasher();
            var    password = "******";
            string hash;
            string salt;

            // act
            hasher.GenerateSaltedHash(password, out hash, out salt);

            // assert
            Assert.NotNull(hash);
            Assert.NotEmpty(hash);
            Assert.NotNull(salt);
            Assert.NotEmpty(salt);

            _testOutputHelper.WriteLine($"PW: {password} hash: {hash} salt: {salt}");
        }
Ejemplo n.º 9
0
        private static User GetWorkerAccount(PasswordHasher passwordHasher)
        {
            var saltedHash = passwordHasher.GenerateSaltedHash(16, "worker");
            var worker     = new User
            {
                FirstName            = "John",
                LastName             = "Brandon",
                IdentificationNumber = "000111",
                Email              = "*****@*****.**",
                MobileNumber       = "44443254",
                RoleOfUser         = RoleOfWorker.Worker,
                CodeOfVerification = "89x2",
                HashPassword       = saltedHash.Hash,
                Salt        = saltedHash.Salt,
                DateCreated = DateTime.Now,
                IsDeleted   = false
            };

            return(worker);
        }
Ejemplo n.º 10
0
        private static User GetAdminAccount(PasswordHasher passwordHasher)
        {
            var saltedHash = passwordHasher.GenerateSaltedHash(16, "admin");
            var admin      = new User
            {
                FirstName            = "Bohdan",
                LastName             = "Doe",
                IdentificationNumber = "000000",
                Email              = "*****@*****.**",
                MobileNumber       = "458963254",
                RoleOfUser         = RoleOfWorker.Admin,
                CodeOfVerification = "7py2",
                HashPassword       = saltedHash.Hash,
                Salt        = saltedHash.Salt,
                DateCreated = DateTime.Now,
                IsDeleted   = false
            };

            return(admin);
        }
Ejemplo n.º 11
0
        public async Task <RegisterUserDto> RegisterUser(RegisterUserDto registerUserDto)
        {
            PasswordHasher passwordHasher = new PasswordHasher();
            var            password       = passwordHasher.GenerateSaltedHash(16, registerUserDto.Password);
            var            new_user       = new Users(registerUserDto.Name, registerUserDto.Surname,
                                                      registerUserDto.Email, password.Hash, password.Salt, (RoleOfUser)Int32.Parse(registerUserDto.RoleOfUser));
            var check_user = await userRepository.FindByLoginAsync(registerUserDto.Email);

            if (check_user == null)
            {
                userRepository.Create(new_user);
                await userRepository.SaveChangesAsync();

                registerUserDto.CodeOfVerification = new_user.CodeOfVerification;
                emailService.EmailAfterRegistration(registerUserDto);
            }
            else
            {
                return(null);
            }
            return(mapper.Map <RegisterUserDto>(new_user));
        }
Ejemplo n.º 12
0
        public async Task <bool> ResetPassword(string code, ResetPasswordDto resetPassword)
        {
            if (resetPassword.Password != resetPassword.ConfirmPassword)
            {
                return(false);
            }
            var user = await userRepository.FindByCodeOfVerificationAsync(code);

            if (user == null)
            {
                return(false);
            }
            PasswordHasher passwordHasher = new PasswordHasher();
            var            hash_password  = passwordHasher.GenerateSaltedHash(16, resetPassword.Password);

            user.HashPassword       = hash_password.Hash;
            user.Salt               = hash_password.Salt;
            user.CodeOfVerification = user.GetRandomString(128);
            userRepository.Update(user);
            await userRepository.SaveChangesAsync();

            return(true);
        }
Ejemplo n.º 13
0
        public void Login___should_return_null___when_username_does_not_exist()
        {
            var password = "******";
            var user     = TestData.User();

            user.Username = "******";
            var hash = PasswordHasher.GenerateSaltedHash(password, user.Salt);
            var expectedSessionId = Guid.NewGuid();

            _authStore.Setup(a => a.GetUserByName("an_incorrect_username"))
            .Returns <User>(null);

            _authStore.Setup(a => a.GetPasswordHash(It.IsAny <int>()))
            .Throws(new Exception("should not try and fetch password hash"));

            _authStore.Setup(a => a.CreateNewSession(user.Id))
            .Throws(new Exception("should not create session"));

            var actualSessionId = _authenticationService.Login(user.Username, password);

            Assert.AreEqual(null, actualSessionId);

            _authStore.Verify();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// It's function for generate hash password and salt
        /// </summary>
        /// <param name="size"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static HashSalt GenerateSaltedHash(int size, string password)
        {
            var passwordHasher = new PasswordHasher();

            return(passwordHasher.GenerateSaltedHash(size, password));
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Método que recebe a senha do usuário e seta o valor já encriptado com hash
 /// </summary>
 /// <param name="password">Senha do usuário</param>
 public virtual void SetPassword(string password)
 {
     Password = PasswordHasher.GenerateSaltedHash(password);
 }