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);
        }
        /// <summary>
        /// Apply for tier 1 verification
        /// </summary>
        /// <param name="command"></param>
        public void ApplyForTier1Verification(VerifyTier1Command command)
        {
            SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(command.SystemGeneratedApiKey);
            User             user             = _userRepository.GetUserById(securityKeysPair.UserId);

            if (user.GetTierLevelStatus(new Tier(TierLevelConstant.Tier0, TierLevelConstant.Tier0)) == Status.Verified.ToString())
            {
                if (user.GetTierLevelStatus(new Tier(TierLevelConstant.Tier1, TierLevelConstant.Tier1)) == Status.NonVerified.ToString())
                {
                    //add user phone number
                    user.UpdateTier1Information(command.FullName, command.DateOfBirth, command.PhoneNumber);
                    //update user tier 1 status
                    user.UpdateTierStatus(TierLevelConstant.Tier1, Status.Preverified);
                    _persistenceRepository.SaveUpdate(user);
                }
                else
                {
                    throw new InvalidOperationException("Tier 1 already verified or applied for verification");
                }
            }
            else
            {
                throw new InvalidOperationException("Verify Tier Level 0 First");
            }
        }
        public void ActivateAccountFailThenSeccussfulTest_ChecksIfUserCannotLoginUntilAccountIsNotActivatedAndTriesToActivateAgainAndThenLogsIn_VerifiesByExpectingExceptionAndReturnedValue()
        {
            IUserApplicationService         userApplicationService         = (IUserApplicationService)_applicationContext["UserApplicationService"];
            IRegistrationApplicationService registrationApplicationService =
                (IRegistrationApplicationService)_applicationContext["RegistrationApplicationService"];
            IUserRepository userRepository = (IUserRepository)_applicationContext["UserRepository"];

            ILoginApplicationService loginApplicationService = (ILoginApplicationService)_applicationContext["LoginApplicationService"];
            ISecurityKeysRepository  securityKeysRepository  = (ISecurityKeysRepository)_applicationContext["SecurityKeysPairRepository"];

            string username      = "******";
            string email         = "*****@*****.**";
            string password      = "******";
            string activationKey = registrationApplicationService.CreateAccount(new SignupUserCommand(email, username, password, "USA", TimeZone.CurrentTimeZone, ""));

            loginApplicationService.Login(new LoginCommand(username, password));

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

            Assert.IsTrue(accountActivated);
            User userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            Assert.IsTrue(userByUserName.IsActivationKeyUsed.Value);

            UserValidationEssentials userValidationEssentials = loginApplicationService.Login(new LoginCommand(username, password));

            Assert.IsNotNull(userValidationEssentials);
            SecurityKeysPair securityKeysPair = securityKeysRepository.GetByApiKey(userValidationEssentials.ApiKey);

            Assert.IsNotNull(securityKeysPair);
            User receivedUser = userRepository.GetUserByUserName(username);

            Assert.IsTrue(receivedUser.IsActivationKeyUsed.Value);
        }
        /// <summary>
        /// Authenticate the user using TFA if it is subscribed for the given action
        /// Returns Tuple: Item1 = Response, Item2 = Error Message
        /// </summary>
        /// <param name="apiKey"> </param>
        /// <param name="currentAction"></param>
        /// <param name="mfaCode"></param>
        /// <returns></returns>
        public Tuple <bool, string> AuthorizeAccess(string apiKey, string currentAction, string mfaCode)
        {
            SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(apiKey);

            if (securityKeysPair != null)
            {
                // If it is a system generated api key, then we verify it from the user's view point
                if (securityKeysPair.SystemGenerated)
                {
                    int userId = securityKeysPair.UserId;
                    // Get user from repository
                    User user = _userRepository.GetUserById(userId);
                    return(CheckSystemGeneratedKeySubscription(user, userId, currentAction, mfaCode));
                }
                // If it is a user generated api key, then we verify it from the api key's view point only
                else
                {
                    return(CheckUserGeneratedKeySubscription(securityKeysPair, currentAction, mfaCode));
                }
            }
            else
            {
                //throw new NullReferenceException("No SecurityKeysPair instance found for Api Key = " + apiKey);
                return(new Tuple <bool, string>(false, "No SecurityKeysPair instance found for Api Key = " + apiKey));
            }
        }
Beispiel #5
0
        public void CreateSecurityKeyPair_PersistAndReadFromDatabaseByApiKey_SavedAndReadInfoShouldBeSame()
        {
            SecurityKeysPair digitalSignatureInfo = new SecurityKeysPair("1", "123456", "secretkey", 1, DateTime.Today.AddDays(1), DateTime.Today.AddDays(-20), DateTime.Today, DateTime.Now, true, null);

            _persistenceRepository.SaveUpdate(digitalSignatureInfo);
            var readInfo = _securityKeysPairRepository.GetByApiKey("123456");

            Assert.NotNull(readInfo);
            Assert.AreEqual(readInfo.KeyDescription, "1");
            Assert.AreEqual(readInfo.ApiKey, "123456");
            Assert.AreEqual(readInfo.SecretKey, "secretkey");
            Assert.AreEqual(readInfo.UserId, digitalSignatureInfo.UserId);
            Assert.AreEqual(readInfo.SystemGenerated, digitalSignatureInfo.SystemGenerated);
            Assert.AreEqual(readInfo.ExpirationDate, digitalSignatureInfo.ExpirationDate);
            Assert.AreEqual(readInfo.StartDate, digitalSignatureInfo.StartDate);
            Assert.AreEqual(readInfo.EndDate, digitalSignatureInfo.EndDate);
        }
        public void CreateSystemGeneratedSecurityPair_IfUserNameIsProvided_VerifyKeyPairIsReturnedAndPersistedSuccessfully()
        {
            ISecurityKeysApplicationService registrationService =
                (ISecurityKeysApplicationService)_applicationContext["SecurityKeysApplicationService"];
            var keys = registrationService.CreateSystemGeneratedKey(1);

            Assert.NotNull(keys);
            Assert.IsNotNullOrEmpty(keys.Item1.Value);
            Assert.IsNotNullOrEmpty(keys.Item2.Value);
            SecurityKeysPair persistedKeysPair = _securityKeysRepository.GetByApiKey(keys.Item1.Value);

            Assert.NotNull(persistedKeysPair);
            Assert.AreEqual(persistedKeysPair.UserId, 1);
            Assert.AreEqual(persistedKeysPair.SystemGenerated, true);
            Assert.AreEqual(persistedKeysPair.ApiKey, keys.Item1.Value);
            Assert.AreEqual(persistedKeysPair.SecretKey, keys.Item2.Value);
            Assert.IsNotNullOrEmpty(persistedKeysPair.KeyDescription);
            Assert.IsNotNullOrEmpty(persistedKeysPair.CreationDateTime.ToString());
        }
 /// <summary>
 /// Authenticates a request
 /// </summary>
 /// <param name="command"></param>
 /// <returns></returns>
 public bool Authenticate(AuthenticateCommand command)
 {
     if (Nonce.IsValid(command.Nonce, command.Counter))
     {
         SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(command.Apikey);
         string           computedHash     = CalculateHash(command.Apikey, command.Uri, securityKeysPair.SecretKey);
         if (Log.IsDebugEnabled)
         {
             Log.Debug("Computed Hash:" + computedHash);
             Log.Debug("Received Hash:" + command.Response);
         }
         if (String.CompareOrdinal(computedHash, command.Response) == 0)
         {
             return(ApiKeyValidation(command));
         }
         throw new InvalidCredentialException("API, URI and Secret Key Hash not found as expected.");
     }
     return(false);
 }
        public void SecurityKeysMfaVerification_ChecksIfMfaSubscriptionsAreAddedAsExpected_VerifiesByQueryingTheDatabase()
        {
            IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"];
            ISecurityKeysRepository    securityKeysRepository          = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"];
            IMfaSubscriptionRepository mfaSubscriptionRepository       = (IMfaSubscriptionRepository)ContextRegistry.GetContext()["MfaSubscriptionRepository"];

            string           apiKey       = "123456";
            SecurityKeysPair originalPair = new SecurityKeysPair("1", apiKey, "secretkey", 1, DateTime.Today.AddDays(1), DateTime.Today.AddDays(-20), DateTime.Today, DateTime.Now, false, null);

            persistenceRepository.SaveUpdate(originalPair);

            SecurityKeysPair retrievedPair = securityKeysRepository.GetByApiKey(apiKey);

            Assert.IsNotNull(retrievedPair);

            IList <MfaSubscription> allSubscriptions = mfaSubscriptionRepository.GetAllSubscriptions();

            Assert.IsNotNull(allSubscriptions);
            Assert.AreEqual(5, allSubscriptions.Count);
            Assert.AreEqual("CancelOrder", allSubscriptions[0].MfaSubscriptionName);
            Assert.AreEqual("Deposit", allSubscriptions[1].MfaSubscriptionName);
            Assert.AreEqual("Login", allSubscriptions[2].MfaSubscriptionName);
            Assert.AreEqual("PlaceOrder", allSubscriptions[3].MfaSubscriptionName);
            Assert.AreEqual("Withdraw", allSubscriptions[4].MfaSubscriptionName);

            IList <Tuple <string, string, bool> > subscriptionsStringList = new List <Tuple <string, string, bool> >();

            foreach (var subscription in allSubscriptions)
            {
                subscriptionsStringList.Add(new Tuple <string, string, bool>(subscription.MfaSubscriptionId,
                                                                             subscription.MfaSubscriptionName, true));
            }
            retrievedPair.AssignMfaSubscriptions(subscriptionsStringList);

            persistenceRepository.SaveUpdate(retrievedPair);

            retrievedPair = securityKeysRepository.GetByApiKey(apiKey);
            Assert.IsNotNull(retrievedPair);
        }
        public void LogoutSuccessTest_TestsIfAUserGetsLogoutAsExpected_FailsIfDoesNot()
        {
            ILoginApplicationService loginApplicationService = (ILoginApplicationService)_applicationContext["LoginApplicationService"];

            Assert.IsNotNull(loginApplicationService);
            IRegistrationApplicationService registrationService = (IRegistrationApplicationService)_applicationContext["RegistrationApplicationService"];;

            // Register
            string username      = "******";
            string password      = "******";
            string activationKey = registrationService.CreateAccount(new SignupUserCommand(
                                                                         "*****@*****.**", username, password, "Wonderland", TimeZone.CurrentTimeZone, ""));

            Assert.IsNotNull(activationKey);

            IUserApplicationService userApplicationService = (IUserApplicationService)_applicationContext["UserApplicationService"];
            IUserRepository         userRepository         = (IUserRepository)_applicationContext["UserRepository"];

            // Activate account
            bool accountActivated = userApplicationService.ActivateAccount(new ActivationCommand(activationKey, username, password));

            Assert.IsTrue(accountActivated);
            User userByUserName = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(userByUserName);
            Assert.IsTrue(userByUserName.IsActivationKeyUsed.Value);

            // Login
            UserValidationEssentials userValidationEssentials = loginApplicationService.Login(new LoginCommand(username, password));

            Assert.IsNotNull(userValidationEssentials);
            Assert.IsNotNull(userValidationEssentials.ApiKey);
            Assert.IsNotNull(userValidationEssentials.SecretKey);
            Assert.IsNotNull(userValidationEssentials.SessionLogoutTime);

            // Logout
            ILogoutApplicationService logoutApplicationService =
                (ILogoutApplicationService)_applicationContext["LogoutApplicationService"];

            Assert.IsNotNull(logoutApplicationService);
            bool logout = logoutApplicationService.Logout(new LogoutCommand(userValidationEssentials.ApiKey));

            Assert.IsTrue(logout);

            ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)_applicationContext["SecurityKeysPairRepository"];
            SecurityKeysPair        securityKeysPair       = securityKeysRepository.GetByApiKey(userValidationEssentials.ApiKey);

            Assert.IsNull(securityKeysPair);
        }
        public void LoginSuccessfulAndCheckSecurityKeysPairTest_ChecksIfAfterUserLoginSecurityPairsValuesAreAsExpected_ChecksByGettingSecurityKeysFromRepo()
        {
            ILoginApplicationService loginApplicationService = (ILoginApplicationService)_applicationContext["LoginApplicationService"];

            Assert.IsNotNull(loginApplicationService);
            IRegistrationApplicationService registrationService = (IRegistrationApplicationService)_applicationContext["RegistrationApplicationService"];
            IUserRepository         userRepository         = (IUserRepository)_applicationContext["UserRepository"];
            ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)_applicationContext["SecurityKeysPairRepository"];

            string username      = "******";
            string email         = "*****@*****.**";
            string password      = "******";
            string activationKey = registrationService.CreateAccount(new SignupUserCommand(
                                                                         email, username, password, "Wonderland", TimeZone.CurrentTimeZone, ""));

            Assert.IsNotNull(activationKey);

            IUserApplicationService userApplicationService = (IUserApplicationService)_applicationContext["UserApplicationService"];
            bool accountActivated = userApplicationService.ActivateAccount(new ActivationCommand(activationKey, "Bob", "alice"));

            Assert.IsTrue(accountActivated);

            UserValidationEssentials userValidationEssentials = loginApplicationService.Login(new LoginCommand(
                                                                                                  username, password));

            Assert.IsNotNull(userValidationEssentials);
            Assert.IsNotNull(userValidationEssentials.ApiKey);
            Assert.IsNotNull(userValidationEssentials.SecretKey);
            Assert.IsNotNull(userValidationEssentials.SessionLogoutTime);

            User user = userRepository.GetUserByUserName(username);

            Assert.IsNotNull(user);
            // Check that the user logged in this same minute and date, as we cannot check the seconds exactly
            Assert.AreEqual(user.LastLogin.Date, DateTime.Today.Date);
            Assert.AreEqual(user.LastLogin.Hour, DateTime.Now.Hour);
            Assert.AreEqual(user.LastLogin.Minute, DateTime.Now.Minute);
            Assert.AreEqual(userValidationEssentials.SessionLogoutTime, user.AutoLogout);

            SecurityKeysPair securityKeysPair = securityKeysRepository.GetByApiKey(userValidationEssentials.ApiKey);

            Assert.IsNotNull(securityKeysPair);
            Assert.AreEqual(userValidationEssentials.SecretKey, securityKeysPair.SecretKey);
        }
        /// <summary>
        /// Request to change Password
        /// </summary>
        /// <param name="changePasswordCommand"> </param>
        /// <returns></returns>
        public ChangePasswordResponse ChangePassword(ChangePasswordCommand changePasswordCommand)
        {
            // Get the SecurityKeyspair instance related to this API Key
            SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(changePasswordCommand.ApiKey.Value);

            // See if the SecurityKeysPair instance exists for this API Key
            if (securityKeysPair != null)
            {
                // Get the User by specifying the Username in the SecurityKeysPair instance
                User user = _userRepository.GetUserById(securityKeysPair.UserId);
                if (user != null)
                {
                    //// Make sure the session has not expired
                    //if (securityKeysPair.CreationDateTime.Add(user.AutoLogout) > DateTime.Now)
                    //{
                    // Check if the old password is the same as new one
                    if (_passwordEncryptionService.VerifyPassword(changePasswordCommand.OldPassword,
                                                                  user.Password))
                    {
                        // Create new password and save for the user in the database
                        string newEncryptedPassword =
                            _passwordEncryptionService.EncryptPassword(changePasswordCommand.NewPassword);
                        user.Password = newEncryptedPassword;
                        _persistenceRepository.SaveUpdate(user);
                        _emailService.SendPasswordChangedEmail(user.Email, user.Username, user.AdminEmailsSubscribed);
                        return(new ChangePasswordResponse(true, "Password Change Successful"));
                    }
                    else
                    {
                        throw new InvalidCredentialException(string.Format("Current password incorrect."));
                    }
                    //}
                    //else
                    //{
                    //    _securityKeysRepository.DeleteSecurityKeysPair(securityKeysPair);
                    //    throw new InvalidOperationException("Session Timeout expired for this API Key.");
                    //}
                }
                else
                {
                    throw new InstanceNotFoundException("User not found for the given SecurityKeysPair's Username.");
                }
            }
            else
            {
                throw new InstanceNotFoundException("SecurityKeysPair not found for the given API Key");
            }
        }
        /// <summary>
        /// Logs the user out
        /// </summary>
        /// <returns></returns>
        public bool Logout(LogoutCommand logoutCommand)
        {
            if (logoutCommand.ApiKey != null &&
                !string.IsNullOrEmpty(logoutCommand.ApiKey.Value))
            {
                SecurityKeysPair securityKeysPair =
                    _securityKeysRepository.GetByApiKey(logoutCommand.ApiKey.Value);

                if (securityKeysPair != null)
                {
                    return(_securityKeysRepository.DeleteSecurityKeysPair(securityKeysPair));
                }
                else
                {
                    throw new InstanceNotFoundException("No SecurityKeysPair found for the given API key.");
                }
            }
            else
            {
                throw new InvalidCredentialException("Invalid or Incomplete Logout Credentials");
            }
        }
 /// <summary>
 /// create new key pair user generated
 /// </summary>
 /// <param name="command"></param>
 /// <param name="apiKey"></param>
 /// <returns></returns>
 public SecurityKeyPair CreateUserGeneratedKey(CreateUserGeneratedSecurityKeyPair command, string apiKey)
 {
     if (command.Validate())
     {
         //get security key pair for user name
         var getSecurityKeyPair = _securityKeysRepository.GetByApiKey(apiKey);
         if (getSecurityKeyPair == null)
         {
             throw new ArgumentException("Invalid api key");
         }
         var keys = _securityKeysGenerationService.GenerateNewSecurityKeys();
         List <SecurityKeysPermission>          permissions = new List <SecurityKeysPermission>();
         SecurityKeyPermissionsRepresentation[] securityKeyPermissionsRepresentations = this.GetPermissions();
         foreach (SecurityKeyPermissionsRepresentation securityKeyPermissionsRepresentation in securityKeyPermissionsRepresentations)
         {
             // Check which permissions have been sent from the frontend that must be included with this User Generated Key
             if (command.SecurityKeyPermissions.Contains(securityKeyPermissionsRepresentation.Permission.PermissionId))
             {
                 securityKeyPermissionsRepresentation.Allowed = true;
             }
         }
         for (int i = 0; i < securityKeyPermissionsRepresentations.Length; i++)
         {
             permissions.Add(new SecurityKeysPermission(keys.Item1, securityKeyPermissionsRepresentations[i].Permission,
                                                        securityKeyPermissionsRepresentations[i].Allowed));
         }
         var keysPair = SecurityKeysPairFactory.UserGeneratedSecurityPair(getSecurityKeyPair.UserId,
                                                                          command.KeyDescription,
                                                                          keys.Item1, keys.Item2, command.EnableExpirationDate, command.ExpirationDateTime,
                                                                          command.EnableStartDate, command.StartDateTime, command.EnableEndDate, command.EndDateTime,
                                                                          permissions,
                                                                          _securityKeysRepository);
         _persistRepository.SaveUpdate(keysPair);
         return(new SecurityKeyPair(keys.Item1, keys.Item2));
     }
     throw new InvalidOperationException("Please assign atleast one permission.");
 }