public void CreateTokenTest()
        {
            // poco mock object
            var userId = 1;
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var guid = new Guid("892821c7-ea89-40b7-abe0-2c8c4a521349");
            var encryptedGuid = "encrypted-guid";
            var encryptedUserId = "dummy-encrypted-user-id";
            var accessToken = new AccessToken();
            var issuedAt = new DateTime(2014, 11, 21, 14, 55, 33);

            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            
            // declare mocks
            var mockContainer = MockRepository.GenerateStub<IContainer>();
            var mockPasswordHash = MockRepository.GenerateStub<IPasswordHash>();
            var mockTokenStorage = MockRepository.GenerateStub<ITokenStorage>();
            var mockDateHelper = MockRepository.GenerateStub<IDateHelper>();
            var mockOpenGuid = MockRepository.GenerateStub<IOpenGuid>();
            var mockEcrypter = MockRepository.GenerateStub<IEncrypter>();
            
            // stub all mock calls
            mockContainer.Stub(x => x.GetInstance<IAccessToken>()).Return(accessToken);
            mockContainer.Stub(x => x.GetInstance<IPasswordHash>()).Return(mockPasswordHash);
            mockOpenGuid.Stub(x => x.New()).Return(guid);
            mockPasswordHash.Stub(x => x.CreateHash(guid.ToString())).Return(hashedToken);
            mockEcrypter.Stub(x => x.GetSalt()).Return(userIdSalt);
            mockEcrypter.Stub(x => x.Encrypt("1", userIdSalt)).Return(encryptedUserId);
            mockTokenStorage.Stub(x => x.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt)).Return(true);
            mockDateHelper.Stub (x => x.Now).Return (issuedAt);
            
            // create test object and call test method
            var accessTokenCreator = new AccessTokenCreator(mockContainer, mockTokenStorage, mockEcrypter, mockDateHelper, mockOpenGuid);
            var accessTokenResult = accessTokenCreator.Create(1);

            // verify stub methods are called
            mockContainer.AssertWasCalled(x => x.GetInstance<IAccessToken>());
            mockContainer.AssertWasCalled(x => x.GetInstance<IPasswordHash>());
            mockOpenGuid.AssertWasCalled(x => x.New());
            mockPasswordHash.AssertWasCalled(x => x.CreateHash(guid.ToString()));
            mockEcrypter.AssertWasCalled(x => x.GetSalt());
            mockEcrypter.AssertWasCalled(x => x.Encrypt("1", userIdSalt));
            mockTokenStorage.AssertWasCalled(x => x.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt));

            // asserts
            Assert.AreEqual(encryptedGuid, accessTokenResult.Token);
            Assert.AreEqual(issuedAt, accessTokenResult.IssuedAt);

        }
        public void StoreAndRetrieveTokenTest()
        {
            TestHelper.DeleteTestData();
            TestHelper.InsertTestData();

            var dataConnection = new DataConnection();
            var dateHelper = new DateHelper();

            var tokenStorage = new TokenStorage(dataConnection, dateHelper);

            var userId = 1;
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var encryptedGuid = "encrypted-guid";
            var encryptedUserId = "dummy-encrypted-user-id";
            var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33);

            
            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            Assert.IsTrue(tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt));
            
            PasswordHash.HashInfo hashedTokenResult;
            string encryptedUserIdResult;
            byte[] userIdSaltResult;
            DateTime issuedAtResult;
            DateTime refreshedResult;
            var retrieveTokenSuccess = tokenStorage.RetrieveToken(encryptedUserId, out hashedTokenResult, out encryptedUserIdResult, out userIdSaltResult, out issuedAtResult, out refreshedResult);

            Assert.IsTrue(retrieveTokenSuccess);
            Assert.AreEqual(hashedToken.Salt, hashedTokenResult.Salt);
            Assert.AreEqual(hashedToken.Hash, hashedTokenResult.Hash);
            Assert.AreEqual(hashedToken.Method, hashedTokenResult.Method);
            Assert.AreEqual(encryptedUserId, encryptedUserIdResult);
            Assert.AreEqual(userIdSalt, userIdSaltResult);
            Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), issuedAtResult);
            Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), refreshedResult);            
           
        }
        public void HashPasswordTest()
        {
            string orgPassword = "******";
            var passwordHash = new PasswordHash();
            var hashedPassword = passwordHash.CreateHash(orgPassword);

            StringBuilder sb = new StringBuilder(); 
            foreach(char c in hashedPassword.ToString()){
                sb.Append(c);
            }

            var enteredPassword = sb.ToString();
            var validateResult = passwordHash.ValidatePassword("org-password", hashedPassword.ToString());

            Assert.AreEqual(hashedPassword.ToString(), enteredPassword);
            Assert.IsTrue(validateResult);

            PasswordHash.HashInfo hi = new PasswordHash.HashInfo(hashedPassword.ToString());
            Assert.AreEqual("sha1", hi.Method);
            Assert.AreEqual(PasswordHash.PBKDF2_ITERATIONS, hi.Iterations);

            Assert.AreEqual(hashedPassword.ToString().Split(':')[0], hi.Method);
            Assert.AreEqual(Int32.Parse(hashedPassword.ToString().Split(':')[1]), hi.Iterations);
            Assert.AreEqual(hashedPassword.ToString().Split(':')[2], hi.Salt);
            Assert.AreEqual(hashedPassword.ToString().Split(':')[3], hi.Hash);

            hi.Dispose();
            Assert.AreEqual(":0::", hi.ToString());

            PasswordHash.HashInfo hi2 = new PasswordHash.HashInfo
            {
                Method = "sha1",
                Iterations = 1000,
                Salt = "salt",
                Hash = "hash"
            };

            Assert.AreEqual("sha1:1000:salt:hash", hi2.ToString());
            hi2.Dispose();
            Assert.AreEqual(":0::", hi2.ToString());
            

        }
        public void StoreExceptionTest()
        {
            var dataConnection = MockRepository.GenerateStub<IDataConnection>();
            var dateHelper = new DateHelper();

            var tokenStorage = new TokenStorage(dataConnection, dateHelper);

            var userId = 1;
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var encryptedGuid = "encrypted-guid";
            var encryptedUserId = "dummy-encrypted-user-id";
            var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33);

            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            // stub fake calls
            dataConnection.Stub(x => x.Execute(null, null)).Throw(new Exception()).IgnoreArguments();

            Assert.Throws<Exception>(() => tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt));
        }
        public void RefreshTokenTest()
        {
            var dataConnection = new DataConnection();
            var dateHelper = new DateHelper();

            var tokenStorage = new TokenStorage(dataConnection, dateHelper);

            var userId = 101;
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var encryptedGuid = "encrypted-guid";
            var encryptedUserId = "dummy-encrypted-user-id";
            var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33);
            
            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            Assert.IsTrue(tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt));

            Assert.IsTrue(tokenStorage.RefreshToken(userId, hashedToken.Hash, new DateTime(2014, 11, 21, 15, 55, 22)));

            PasswordHash.HashInfo hashedTokenResult;
            string encryptedUserIdResult;
            byte[] userIdSaltResult;
            DateTime issuedAtResult;
            DateTime refreshedResult;
            var retrieveTokenSuccess = tokenStorage.RetrieveToken(encryptedUserId, out hashedTokenResult, out encryptedUserIdResult, out userIdSaltResult, out issuedAtResult, out refreshedResult);

            Assert.IsTrue(retrieveTokenSuccess);
            Assert.AreEqual(hashedToken.Salt, hashedTokenResult.Salt);
            Assert.AreEqual(hashedToken.Hash, hashedTokenResult.Hash);
            Assert.AreEqual(hashedToken.Method, hashedTokenResult.Method);
            Assert.AreEqual(encryptedUserId, encryptedUserIdResult);
            Assert.AreEqual(userIdSalt, userIdSaltResult);
            Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), issuedAtResult);
            Assert.AreEqual(new DateTime(2014, 11, 21, 15, 55, 22), refreshedResult);

            // check if using a wrong id/encryptid fails (it should fail)
            Assert.IsFalse(tokenStorage.RefreshToken(102, hashedToken.Hash, new DateTime(2014, 11, 21, 15, 55, 22)));
            Assert.IsFalse(tokenStorage.RefreshToken(userId, hashedToken.Hash + 'a', new DateTime(2014, 11, 21, 15, 55, 22)));
        }
        public void VerifyTokenExistenceTest()
        {
            TestHelper.DeleteTestData();
            TestHelper.InsertTestData();

            //VerifyTokenExistence
            var dataConnection = new DataConnection();
            var dateHelper = new DateHelper();

            var tokenStorage = new TokenStorage(dataConnection, dateHelper);

            var userId = 101;
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var encryptedGuid = "encrypted-guid";
            var encryptedUserId = "dummy-encrypted-user-id";
            var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33);
            
            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            Assert.IsTrue(tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt));

            string hashedTokenResult;
            DateTime issuedAtResult;
            DateTime refreshedResult;
            var verifyTokenSuccess = tokenStorage.VerifyTokenExistence(userId, out hashedTokenResult, out issuedAtResult, out refreshedResult);

            Assert.IsTrue(verifyTokenSuccess);
            Assert.AreEqual(encryptedGuid, hashedTokenResult);
            Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), issuedAtResult);
            Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), refreshedResult);

            verifyTokenSuccess = tokenStorage.VerifyTokenExistence(102, out hashedTokenResult, out issuedAtResult, out refreshedResult);

            Assert.IsFalse(verifyTokenSuccess);
            Assert.AreEqual(null, hashedTokenResult);
            Assert.AreEqual(new DateTime(), issuedAtResult);
            Assert.AreEqual(new DateTime(), refreshedResult);
        }
        public void CreateTokenUnknownExceptionTest()
        {
            // poco mock object
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var guid = new Guid("892821c7-ea89-40b7-abe0-2c8c4a521349");
            var encryptedGuid = "encrypted-guid";
            var encryptedUserId = "dummy-encrypted-user-id";
            var accessToken = new AccessToken();
            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };


            // declare mocks
            var mockContainer = MockRepository.GenerateStub<IContainer>();
            var mockPasswordHash = MockRepository.GenerateStub<IPasswordHash>();
            var mockTokenStorage = MockRepository.GenerateStub<ITokenStorage>();
            var mockDateHelper = MockRepository.GenerateStub<IDateHelper>();
            var mockOpenGuid = MockRepository.GenerateStub<IOpenGuid>();
            var mockEcrypter = MockRepository.GenerateStub<IEncrypter>();

            // stub all mock calls
            mockContainer.Stub(x => x.GetInstance<IAccessToken>()).Return(accessToken);
            mockContainer.Stub(x => x.GetInstance<IPasswordHash>()).Return(mockPasswordHash);
            mockOpenGuid.Stub(x => x.New()).Return(guid);
            mockPasswordHash.Stub(x => x.CreateHash(guid.ToString())).Throw(new Exception("Unknown exception"));
           
            // create test object and call test method
            var accessTokenCreator = new AccessTokenCreator(mockContainer, mockTokenStorage, mockEcrypter, mockDateHelper, mockOpenGuid);
            Assert.Throws<Exception>(() => accessTokenCreator.Create(1));
            
            // verify stub methods are called
            // verify stub methods are called
            mockContainer.AssertWasCalled(x => x.GetInstance<IAccessToken>());
            mockContainer.AssertWasCalled(x => x.GetInstance<IPasswordHash>());
            mockOpenGuid.AssertWasCalled(x => x.New());
            mockPasswordHash.AssertWasCalled(x => x.CreateHash(guid.ToString()));
        }
        public void ReAuthenticateFailsTest()
        {
            // poco mock object
            var userId = 1;
            var userIdSalt = new byte[24];
            var tokenSalt = new byte[24];
            var guid = new Guid("892821c7-ea89-40b7-abe0-2c8c4a521349");
            var guid2 = new Guid("792821c7-ea89-40b7-abe0-2c8c4a521349");
            var encryptedGuid = "encrypted-guid";
            var encryptedGuid2 = "encrypted-guid2";
            var encryptedUserId = "dummy-encrypted-user-id";
            var encryptedUserId2 = "dummy-encrypted-user-id2";
            var accessToken = new AccessToken();
            var accessToken2 = new AccessToken();
            var issuedAt = new DateTime(2014, 11, 21, 13, 55, 33);
            var now = new DateTime(2014, 11, 21, 14, 55, 33);

            var hashedToken = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            var hashedToken2 = new PasswordHash.HashInfo
            {
                Hash = encryptedGuid2,
                Iterations = 1000,
                Method = "sha1",
                Salt = Convert.ToBase64String(tokenSalt)
            };

            // declare mocks
            var mockContainer = MockRepository.GenerateStub<IContainer>();
            var mockPasswordHash = MockRepository.GenerateStub<IPasswordHash>();
            var mockTokenStorage = MockRepository.GenerateStub<ITokenStorage>();
            var mockDateHelper = MockRepository.GenerateStub<IDateHelper>();
            var mockOpenGuid = MockRepository.GenerateStub<IOpenGuid>();
            var mockEcrypter = MockRepository.GenerateStub<IEncrypter>();

            string tokenIdOut;
            var issuedAtOutRef = new DateTime(2014, 11, 21, 13, 55, 33);
            var refreshedOutRef = new DateTime(2014, 11, 21, 13, 55, 33);
            DateTime issuedAtOut, refreshedOut;

            // stub all mock calls
            mockContainer.Stub(x => x.GetInstance<IAccessToken>()).Return(accessToken).Repeat.Once();
            mockContainer.Stub(x => x.GetInstance<IPasswordHash>()).Return(mockPasswordHash).Repeat.Times(2);

            mockTokenStorage.Stub(x => x.VerifyTokenExistence(userId, out tokenIdOut, out issuedAtOut, out refreshedOut))
                                        .OutRef(new object[] { encryptedUserId, issuedAtOutRef, refreshedOutRef })
                                        .Return(false).Repeat.Once();
            mockOpenGuid.Stub(x => x.New()).Return(guid).Repeat.Once();
            mockPasswordHash.Stub(x => x.CreateHash(guid.ToString())).Return(hashedToken).Repeat.Once();
            mockEcrypter.Stub(x => x.GetSalt()).Return(userIdSalt).Repeat.Once();
            mockEcrypter.Stub(x => x.Encrypt("1", userIdSalt)).Return(encryptedUserId).Repeat.Once();
            mockDateHelper.Stub(x => x.Now).Return(issuedAt).Repeat.Once();
            mockTokenStorage.Stub(x => x.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt)).Return(true).Repeat.Once();
            
            mockContainer.Stub(x => x.GetInstance<IAccessToken>()).Return(accessToken2).Repeat.Once();
            mockTokenStorage.Stub(x => x.VerifyTokenExistence(userId, out tokenIdOut, out issuedAtOut, out refreshedOut))
                                        .OutRef(new object[] { encryptedUserId, issuedAtOutRef, refreshedOutRef })
                                        .Return(true).Repeat.Once();
            mockDateHelper.Stub(x => x.IsWithinTimeOutLimit(refreshedOutRef)).Return(false).Repeat.Once();
            mockDateHelper.Stub(x => x.Now).Return(now).Repeat.Once();
            mockOpenGuid.Stub(x => x.New()).Return(guid2).Repeat.Once();
            mockPasswordHash.Stub(x => x.CreateHash(guid2.ToString())).Return(hashedToken2).Repeat.Once();
            mockEcrypter.Stub(x => x.GetSalt()).Return(userIdSalt).Repeat.Once();
            mockEcrypter.Stub(x => x.Encrypt("1", userIdSalt)).Return(encryptedUserId2).Repeat.Once();
            mockDateHelper.Stub(x => x.Now).Return(now).Repeat.Once();
            mockTokenStorage.Stub(x => x.StoreToken(userId, hashedToken2, encryptedUserId2, userIdSalt, now)).Return(true).Repeat.Once();
            
            // create test object and call test method
            var accessTokenCreator = new AccessTokenCreator(mockContainer, mockTokenStorage, mockEcrypter, mockDateHelper, mockOpenGuid);
            var accessTokenResult = accessTokenCreator.Create(1);

            // verify stub methods are called
            mockContainer.AssertWasCalled(x => x.GetInstance<IAccessToken>());
            mockContainer.AssertWasCalled(x => x.GetInstance<IPasswordHash>());
            mockTokenStorage.AssertWasCalled(x => x.VerifyTokenExistence(userId, out tokenIdOut, out issuedAtOut, out refreshedOut));
            mockOpenGuid.AssertWasCalled(x => x.New());
            mockPasswordHash.AssertWasCalled(x => x.CreateHash(guid.ToString()));
            mockEcrypter.AssertWasCalled(x => x.GetSalt());
            mockEcrypter.AssertWasCalled(x => x.Encrypt("1", userIdSalt));
            mockTokenStorage.AssertWasCalled(x => x.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt));

            // asserts
            Assert.AreEqual(encryptedGuid, accessTokenResult.Token);
            Assert.AreEqual(issuedAt, accessTokenResult.IssuedAt);

            var accessTokenResult2 = accessTokenCreator.Create(1);
            // verify stub methods are called
            mockContainer.AssertWasCalled(x => x.GetInstance<IAccessToken>());
            mockContainer.AssertWasCalled(x => x.GetInstance<IPasswordHash>());
            mockTokenStorage.AssertWasCalled(x => x.VerifyTokenExistence(userId, out tokenIdOut, out issuedAtOut, out refreshedOut));
            mockOpenGuid.AssertWasCalled(x => x.New());
            mockPasswordHash.AssertWasCalled(x => x.CreateHash(guid2.ToString()));
            mockEcrypter.AssertWasCalled(x => x.GetSalt());
            mockEcrypter.AssertWasCalled(x => x.Encrypt("1", userIdSalt));
            mockTokenStorage.AssertWasCalled(x => x.StoreToken(userId, hashedToken2, encryptedUserId2, userIdSalt, now));

            mockOpenGuid.VerifyAllExpectations();

            Assert.AreNotEqual(accessTokenResult2.Token, accessTokenResult.Token);
            Assert.AreNotEqual(accessTokenResult2.IssuedAt, accessTokenResult.IssuedAt);

            Assert.AreEqual(encryptedGuid2, accessTokenResult2.Token);
            Assert.AreEqual(now, accessTokenResult2.IssuedAt);
        }
        public bool RetrieveToken(string id, out PasswordHash.HashInfo hashedToken, out string encryptedUserId, out byte[] userIdSalt, out DateTime issuedAt, out DateTime refreshed)
        {
            try
            {
                var sql = @"SELECT [id]
                              ,[id_salt]
                              ,[token_hash]
                              ,[token_salt]
                              ,[token_method]
                              ,[token_iterations]
                              ,[issued_at]
                              ,[refreshed]
                          FROM [TokenStorage]
                          WHERE [id] = @id";


                var results = dataConnection.Query<TokenStorageDb>(sql, new { id = id });

                // get the first out of the result set and throw exception if there is more
                var token = results.Single();

                issuedAt = token.issued_at;
                refreshed = token.refreshed;
                hashedToken = new PasswordHash.HashInfo
                {
                    Hash = token.token_hash,
                    Iterations = token.token_iterations,
                    Method = token.token_method,
                    Salt = token.token_salt
                };
                encryptedUserId = token.id;
                userIdSalt = Convert.FromBase64String(token.id_salt);

                return true;

            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }         
            
            // set all information on null or default
            hashedToken = null;
            encryptedUserId = null;
            userIdSalt = null;
            issuedAt = new DateTime();
            refreshed = new DateTime();

            return false;
        }