/// <summary> /// Validate permissions /// </summary> /// <param name="keysPair"></param> /// <param name="permissions"></param> private void ValidatePermissions(SecurityKeysPair keysPair, List <string> permissions) { for (int i = 0; i < permissions.Count; i++) { Assert.IsTrue(keysPair.ValidatePermission(permissions[i])); } }
/// <summary> /// Checks for permissions for the currently requested operation /// </summary> /// <param name="authenticateCommand"></param> /// <param name="securityKeysPair"></param> /// <returns></returns> private bool CheckPermissions(AuthenticateCommand authenticateCommand, SecurityKeysPair securityKeysPair) { bool permissionGained = false; if (authenticateCommand.Uri.Contains("/orders/cancelorder")) { return(securityKeysPair.ValidatePermission(PermissionsConstant.Cancel_Order)); } else if (authenticateCommand.Uri.Contains("/orders/openorders")) { return(securityKeysPair.ValidatePermission(PermissionsConstant.Query_Open_Orders)); } else if (authenticateCommand.Uri.Contains("/orders/closedorders")) { return(securityKeysPair.ValidatePermission(PermissionsConstant.Query_Closed_Orders)); } else if (authenticateCommand.Uri.Contains("/orders/createorder")) { return(securityKeysPair.ValidatePermission(PermissionsConstant.Place_Order)); } else if (authenticateCommand.Uri.Contains("trades/tradehistory") || authenticateCommand.Uri.Contains("trades/querytrades") || authenticateCommand.Uri.Contains("orders/queryorders") || authenticateCommand.Uri.Contains("trades/tradedetails")) { return(securityKeysPair.ValidatePermission(PermissionsConstant.Query_Open_Orders) || securityKeysPair.ValidatePermission(PermissionsConstant.Query_Closed_Orders)); } throw new InvalidOperationException("Permission not allowed for this operation."); }
public void MfaAuthorizationSuccessfulTest_ChecksThatServiceReturnsTrueIfNoMfaSubscriptionIsSubscribed_VerifiesThroughReturnsValue() { IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; ISecurityKeysRepository securityKeysPairRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IMfaCodeSenderService mfaSmsService = (IMfaCodeSenderService)ContextRegistry.GetContext()["MfaSmsService"]; IMfaCodeSenderService mfaEmailService = (IMfaCodeSenderService)ContextRegistry.GetContext()["MfaEmailService"]; IMfaCodeGenerationService mfaCodeGenerationService = (IMfaCodeGenerationService)ContextRegistry.GetContext()["MfaCodeGenerationService"]; IMfaAuthorizationService mfaAuthorizationService = new MfaAuthorizationService(persistenceRepository, userRepository, securityKeysPairRepository, mfaSmsService, mfaEmailService, mfaCodeGenerationService); string apiKey = "123"; string userName = "******"; string phoneNumber = "2233344"; string email = "*****@*****.**"; User user = new User(userName, "asdf", "12345", "xyz", email, Language.English, TimeZone.CurrentTimeZone, new TimeSpan(1, 1, 1, 1), DateTime.Now, "Pakistan", "", phoneNumber, "1234"); persistenceRepository.SaveUpdate(user); user = userRepository.GetUserByUserName(userName); Assert.IsNotNull(user); SecurityKeysPair securityKeysPair = new SecurityKeysPair(user.Id, apiKey, "secret123", true, "#1"); persistenceRepository.SaveUpdate(securityKeysPair); Tuple <bool, string> authorizeAccess = mfaAuthorizationService.AuthorizeAccess(apiKey, MfaConstants.Deposit, ""); Assert.IsTrue(authorizeAccess.Item1); }
public void GetUserIDFromApiKey_IfKeyPairExists_UserIdWillBeReturned() { 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); Assert.AreEqual(_apiKeyInfoAccess.GetUserIdFromApiKey("123456"), 1); }
/// <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)); } }
/// <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"); } }
/// <summary> /// Generates a new API key and Secret Key pair /// </summary> /// <returns></returns> public Tuple <ApiKey, SecretKey, DateTime> CreateSystemGeneratedKey(int userId) { SecurityKeysPair keysPair = SecurityKeysPairFactory.SystemGeneratedSecurityKeyPair(userId, _securityKeysGenerationService); _persistRepository.SaveUpdate(keysPair); return(new Tuple <ApiKey, SecretKey, DateTime>(new ApiKey(keysPair.ApiKey), new SecretKey(keysPair.SecretKey), keysPair.CreationDateTime)); }
public void UserGeneratedKeysQueryClosedOrdersFailTest_TestsIfTheAuthenticationFailsDueToExpirationDate_VerifiesThroughTheReturnedValue() { ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; UserAuthenticationService userAuthenticationService = new UserAuthenticationService(userRepository, securityKeysRepository, persistenceRepository); string nounce = userAuthenticationService.GenerateNonce(); string apiKey = "123456789"; string uri = "www.blancrock.com/orders/cancelorder"; string secretKey = "1234567"; string username = "******"; // Provide the permission List <SecurityKeysPermission> permissionslist = new List <SecurityKeysPermission>(); permissionslist.Add(new SecurityKeysPermission(apiKey, new Permission(PermissionsConstant.Query_Closed_Orders, "Query Closed Orders"), true)); // Here we provide the expiration date for the current moment, which will expire instantly SecurityKeysPair securityKeysPair = new SecurityKeysPair("1", apiKey, secretKey, 1, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, false, permissionslist); securityKeysPair.EnableExpirationDate = true; persistenceRepository.SaveUpdate(securityKeysPair); // Create a user and store it in database, this is the user for whom we have created the key User user = new User("*****@*****.**", username, "abc", "Pakistan", TimeZone.CurrentTimeZone, "", ""); persistenceRepository.SaveUpdate(user); string response = String.Format("{0}:{1}:{2}", apiKey, uri, secretKey).ToMD5Hash(); userAuthenticationService.Authenticate(new AuthenticateCommand("Rtg65s345", nounce, apiKey, uri, response, "1")); }
public void SystemGeneratedKeysSuccessfulTest_TestsIfTheAuthenticationIsSuccessful_VerifiesThroughTheReturnedValue() { ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; UserAuthenticationService userAuthenticationService = new UserAuthenticationService(userRepository, securityKeysRepository, persistenceRepository); string nounce = userAuthenticationService.GenerateNonce(); string apiKey = "123456789"; string uri = "www.blancrock.com/orders/cancelorder"; string secretKey = "1234567"; string username = "******"; // Create a user and store it in database, this is the user for whom we have created the key User user = new User("*****@*****.**", username, "abc", "Pakistan", TimeZone.CurrentTimeZone, "", ""); persistenceRepository.SaveUpdate(user); User userByUserName = userRepository.GetUserByUserName(username); // Create System generated Keys and store in repo. SecurityKeysPair securityKeysPair = new SecurityKeysPair(apiKey, secretKey, "1", userByUserName.Id, true); persistenceRepository.SaveUpdate(securityKeysPair); string response = String.Format("{0}:{1}:{2}", apiKey, uri, secretKey).ToMD5Hash(); bool authenticate = userAuthenticationService.Authenticate(new AuthenticateCommand("Rtg65s345", nounce, apiKey, uri, response, "1")); Assert.IsTrue(authenticate); }
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> /// Apply for tier 2 verification /// </summary> /// <param name="command"></param> public void ApplyForTier2Verification(VerifyTier2Command command) { if (command.ValidateCommand()) { SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(command.SystemGeneratedApiKey); User user = _userRepository.GetUserById(securityKeysPair.UserId); if (user.GetTierLevelStatus(new Tier(TierLevelConstant.Tier1, TierLevelConstant.Tier1)) == Status.Verified.ToString()) { if (user.GetTierLevelStatus(new Tier(TierLevelConstant.Tier2, TierLevelConstant.Tier2)) == Status.NonVerified.ToString()) { //update info user.UpdateTier2Information(command.City, command.State, command.AddressLine1, command.AddressLine2, command.ZipCode); //update tier status user.UpdateTierStatus(TierLevelConstant.Tier2, Status.Preverified); //update user _persistenceRepository.SaveUpdate(user); } else { throw new InvalidOperationException("Tier 2 already verified or applied for verification"); } } else { throw new InvalidOperationException("Verify Tier Level 1 First"); } } }
public void CreateSecurityKeyPair_UpdatePermission_ItShouldGetUpdatedInTheDatabase() { IList <Permission> permissions = _permissionRepository.GetAllPermissions(); IList <SecurityKeysPermission> securityKeysPermissions = new List <SecurityKeysPermission>(); for (int i = 0; i < 7; i++) { SecurityKeysPermission permission = new SecurityKeysPermission("123456", permissions[i], true); securityKeysPermissions.Add(permission); } SecurityKeysPair securityKeys = new SecurityKeysPair("1", "123456", "secretkey", 1, DateTime.Today.AddDays(1), DateTime.Today.AddDays(-20), DateTime.Today, DateTime.Now, true, securityKeysPermissions); _persistenceRepository.SaveUpdate(securityKeys); //update permissions securityKeysPermissions[2].IsAllowed = false; securityKeysPermissions[4].IsAllowed = false; securityKeysPermissions[6].IsAllowed = false; securityKeys.UpdatePermissions(securityKeysPermissions.ToArray()); //save them again _persistenceRepository.SaveUpdate(securityKeys); //read security key pair 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, securityKeys.UserId); Assert.AreEqual(readInfo.SystemGenerated, securityKeys.SystemGenerated); Assert.AreEqual(readInfo.ExpirationDate, securityKeys.ExpirationDate); Assert.AreEqual(readInfo.StartDate, securityKeys.StartDate); Assert.AreEqual(readInfo.EndDate, securityKeys.EndDate); ValidatePermissions(readInfo, securityKeysPermissions.ToArray()); }
/// <summary> /// Validate permissions /// </summary> /// <param name="keysPair"></param> /// <param name="permissions"></param> private void ValidatePermissions(SecurityKeysPair keysPair, SecurityKeysPermission[] permissions) { for (int i = 0; i < permissions.Length; i++) { Assert.AreEqual(permissions[i].IsAllowed, keysPair.ValidatePermission(permissions[i].Permission.PermissionId)); } }
/// <summary> /// Validates the credentials related to the API Key /// </summary> /// <returns></returns> private bool ApiKeyValidation(AuthenticateCommand authenticateCommand) { SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(authenticateCommand.Apikey); if (securityKeysPair != null) { User user = _userRepository.GetUserById(securityKeysPair.UserId); if (user != null) { // If the keys are system generated, then we only need to check the session timeout for the user if (securityKeysPair.SystemGenerated) { // Calculate for how much time is allowed in the session timeout for SystemGenerated key, saved in user //int activeWindow = securityKeysPair.CreationDateTime.AddMinutes(user.AutoLogout.Minutes).Minute; if (securityKeysPair.LastModified.AddMinutes(user.AutoLogout.Minutes) > DateTime.Now) { //update activity time securityKeysPair.LastModified = DateTime.Now; _persistenceRepository.SaveUpdate(securityKeysPair); return(true); } else { _securityKeysRepository.DeleteSecurityKeysPair(securityKeysPair); throw new InvalidOperationException("Session timeout for the API Key."); } } // Else we need to check the expiration date of the keys, and whetehr the user has permissions for // commencing with the desired operation else { if (securityKeysPair.EnableExpirationDate) { if (securityKeysPair.ExpirationDate > DateTime.Now) { return(CheckPermissions(authenticateCommand, securityKeysPair)); } throw new InvalidOperationException("Key Expired"); } else { return(CheckPermissions(authenticateCommand, securityKeysPair)); } } } else { throw new InvalidOperationException(string.Format("{0} {1}", "No user found against userId: ", securityKeysPair.UserId)); } } else { throw new InvalidOperationException(string.Format("{0} {1}", "No SecurityKeysPair found against the given API Key.")); } return(false); }
public void LogoutFailTest_ChecksThatExceptionIsThrownWhenInvalidActivationKeyIsGiven_VerifiesAndAssertsTheReturnedValueAndQueriesDatabase() { // Register User RegistrationController registrationController = (RegistrationController)_applicationContext["RegistrationController"]; IHttpActionResult httpActionResult = registrationController.Register(new SignUpParam("*****@*****.**", "user", "123", "Pakistan", TimeZone.CurrentTimeZone, "")); OkNegotiatedContentResult <string> okResponseMessage = (OkNegotiatedContentResult <string>)httpActionResult; string activationKey = okResponseMessage.Content; Assert.IsNotNullOrEmpty(activationKey); // Activate Account UserController userController = (UserController)_applicationContext["UserController"]; httpActionResult = userController.ActivateUser(new UserActivationParam("user", "123", activationKey)); OkNegotiatedContentResult <string> okResponseMessage1 = (OkNegotiatedContentResult <string>)httpActionResult; Assert.AreEqual(okResponseMessage1.Content, "activated"); // Login LoginController loginController = (LoginController)_applicationContext["LoginController"]; httpActionResult = loginController.Login(new LoginParams("user", "123")); OkNegotiatedContentResult <UserValidationEssentials> keys = (OkNegotiatedContentResult <UserValidationEssentials>)httpActionResult; Assert.IsNotNullOrEmpty(keys.Content.ApiKey); Assert.IsNotNullOrEmpty(keys.Content.SecretKey); Assert.IsNotNullOrEmpty(keys.Content.SessionLogoutTime.ToString()); // Verify that Security Keys are in the database ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)_applicationContext["SecurityKeysPairRepository"]; SecurityKeysPair securityKeysPair = securityKeysRepository.GetByApiKey(keys.Content.ApiKey); Assert.IsNotNull(securityKeysPair); Assert.AreEqual(keys.Content.SecretKey, securityKeysPair.SecretKey); Assert.IsTrue(securityKeysPair.SystemGenerated); LogoutController logoutController = (LogoutController)_applicationContext["LogoutController"]; logoutController.Request = new HttpRequestMessage(HttpMethod.Get, ""); logoutController.Request.Headers.Add("Auth", "123"); IHttpActionResult logoutResult = logoutController.Logout(); BadRequestErrorMessageResult logoutOkResponse = (BadRequestErrorMessageResult)logoutResult; Assert.IsNotNull(logoutOkResponse); // Verify that the Security Keys are not in the database securityKeysPair = securityKeysRepository.GetByApiKey(keys.Content.ApiKey); Assert.IsNotNull(securityKeysPair); Assert.AreEqual(keys.Content.SecretKey, securityKeysPair.SecretKey); Assert.IsTrue(securityKeysPair.SystemGenerated); }
public void CreateSystemGeneratedSecurityKeysPair_IfUserNameIsProvided_TheSecurityPairShouldHaveBeenCreated() { SecurityKeysPair pair = SecurityKeysPairFactory.SystemGeneratedSecurityKeyPair(1, this); Assert.NotNull(pair); Assert.AreEqual(pair.UserId, 1); Assert.AreEqual(pair.SystemGenerated, true); Assert.IsNotNullOrEmpty(pair.ApiKey); Assert.IsNotNullOrEmpty(pair.SecretKey); Assert.IsNotNullOrEmpty(pair.KeyDescription); Assert.IsNotNullOrEmpty(pair.CreationDateTime.ToString()); }
public void MfaAuthorizationFailTest_ChecksThatServiceReturnsTrueIfMfaCodesDontMatch_VerifiesThroughReturnsValue() { IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; ISecurityKeysRepository securityKeysPairRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IMfaCodeSenderService mfaSmsService = (IMfaCodeSenderService)ContextRegistry.GetContext()["MfaSmsService"]; IMfaCodeSenderService mfaEmailService = (IMfaCodeSenderService)ContextRegistry.GetContext()["MfaEmailService"]; IMfaCodeGenerationService mfaCodeGenerationService = (IMfaCodeGenerationService)ContextRegistry.GetContext()["MfaCodeGenerationService"]; IMfaSubscriptionRepository mfaSubscriptionRepository = (IMfaSubscriptionRepository)ContextRegistry.GetContext()["MfaSubscriptionRepository"]; IMfaAuthorizationService mfaAuthorizationService = new MfaAuthorizationService(persistenceRepository, userRepository, securityKeysPairRepository, mfaSmsService, mfaEmailService, mfaCodeGenerationService); string apiKey = "123"; string userName = "******"; string phoneNumber = "2233344"; string email = "*****@*****.**"; User user = new User(userName, "asdf", "12345", "xyz", email, Language.English, TimeZone.CurrentTimeZone, new TimeSpan(1, 1, 1, 1), DateTime.Now, "Pakistan", "", phoneNumber, "1234"); persistenceRepository.SaveUpdate(user); user = userRepository.GetUserByUserName(userName); Assert.IsNotNull(user); SecurityKeysPair securityKeysPair = new SecurityKeysPair(user.Id, apiKey, "secret123", true, "#1"); persistenceRepository.SaveUpdate(securityKeysPair); Tuple <bool, string> authorizeAccess = mfaAuthorizationService.AuthorizeAccess(apiKey, MfaConstants.Deposit, ""); Assert.IsTrue(authorizeAccess.Item1); IList <MfaSubscription> allSubscriptions = mfaSubscriptionRepository.GetAllSubscriptions(); IList <Tuple <string, string, bool> > mfaSubscriptions = new List <Tuple <string, string, bool> >(); foreach (var subscription in allSubscriptions) { mfaSubscriptions.Add(new Tuple <string, string, bool>(subscription.MfaSubscriptionId, subscription.MfaSubscriptionName, true)); } user.AssignMfaSubscriptions(mfaSubscriptions); persistenceRepository.SaveUpdate(user); authorizeAccess = mfaAuthorizationService.AuthorizeAccess(apiKey, MfaConstants.Deposit, null); Assert.IsFalse(authorizeAccess.Item1); // The Stub Implementation always generates and returns the same MFA Code. We manuipulate it so that the code is // incorrect string mfaCode = mfaCodeGenerationService.GenerateCode(); authorizeAccess = mfaAuthorizationService.AuthorizeAccess(apiKey, MfaConstants.Deposit, mfaCode + "1"); Assert.IsFalse(authorizeAccess.Item1); }
public void UpdateUserGeneratedSecurityPair_UpdatePermissionsAndSomeDescription_VerifyKeyPairIsReturnedAndPersistedSuccessfully() { ISecurityKeysApplicationService registrationService = (ISecurityKeysApplicationService)_applicationContext["SecurityKeysApplicationService"]; var systemGeneratedKey = registrationService.CreateSystemGeneratedKey(1); List <string> securityKeyPermissions = new List <string>(); IList <Permission> permissions = _permissionRepository.GetAllPermissions(); for (int i = 0; i < permissions.Count; i++) { securityKeyPermissions.Add(permissions[i].PermissionId); } CreateUserGeneratedSecurityKeyPair command = new CreateUserGeneratedSecurityKeyPair(securityKeyPermissions, DateTime.Today.AddDays(1).ToString(), DateTime.Today.AddDays(-2).ToString(), DateTime.Today.AddDays(-1).ToString(), true, true, true, "123"); var keys = registrationService.CreateUserGeneratedKey(command, systemGeneratedKey.Item1.Value); List <SecurityKeyPermissionsRepresentation> securityKeyPermissions2 = new List <SecurityKeyPermissionsRepresentation>(); for (int i = 0; i < permissions.Count; i++) { if (i % 2 == 0) { securityKeyPermissions2.Add(new SecurityKeyPermissionsRepresentation(false, permissions[i])); } else { securityKeyPermissions2.Add(new SecurityKeyPermissionsRepresentation(true, permissions[i])); } } UpdateUserGeneratedSecurityKeyPair update = new UpdateUserGeneratedSecurityKeyPair(keys.ApiKey, "456", false, false, true, "", "", securityKeyPermissions2.ToArray(), DateTime.Today.AddDays(3).ToString()); registrationService.UpdateSecurityKeyPair(update, keys.ApiKey); Assert.NotNull(keys); Assert.IsNotNullOrEmpty(keys.ApiKey); Assert.IsNotNullOrEmpty(keys.SecretKey); SecurityKeysPair persistedKeysPair = _securityKeysRepository.GetByApiKey(keys.ApiKey); Assert.NotNull(persistedKeysPair); Assert.AreEqual(persistedKeysPair.UserId, 1); Assert.AreEqual(persistedKeysPair.SystemGenerated, false); Assert.AreEqual(persistedKeysPair.ApiKey, keys.ApiKey); Assert.AreEqual(persistedKeysPair.SecretKey, keys.SecretKey); Assert.AreEqual(persistedKeysPair.KeyDescription, "456"); Assert.IsNotNullOrEmpty(persistedKeysPair.CreationDateTime.ToString()); Assert.AreEqual(persistedKeysPair.EnableStartDate, false); Assert.AreEqual(persistedKeysPair.EnableEndDate, false); Assert.AreEqual(persistedKeysPair.EnableExpirationDate, true); Assert.AreEqual(persistedKeysPair.ExpirationDate, DateTime.Today.AddDays(3)); }
/// <summary> /// Verify the Tier level for a certain user /// </summary> /// <param name="tierLevelCommand"> </param> /// <returns></returns> public VerifyTierLevelResponse VerifyTierLevel(VerifyTierLevelCommand tierLevelCommand) { SecurityKeysPair keysPair = _securityKeysRepository.GetByApiKey(tierLevelCommand.ApiKey); if (keysPair != null) { User user = _userRepository.GetUserById(keysPair.UserId); if (user != null) { foreach (UserTierLevelStatus userTierLevelStatuse in user.GetAllTiersStatus()) { if (userTierLevelStatuse.Tier.TierLevel == tierLevelCommand.TierLevel) { if (userTierLevelStatuse.Status == Status.Preverified) { userTierLevelStatuse.Status = Status.Verified; _persistenceRepository.SaveUpdate(user); return(new VerifyTierLevelResponse(true, "Tier level " + tierLevelCommand.TierLevel + " verified")); } else { if (userTierLevelStatuse.Status == Status.NonVerified) { throw new InvalidOperationException(string.Format("Please apply for {0} first", tierLevelCommand.TierLevel)); } else { throw new InvalidOperationException(string.Format("{0} is already verified.", tierLevelCommand.TierLevel)); } } } } throw new InstanceNotFoundException(string.Format("The provided Tier Level not found. Account ID = {0}, " + "Tier Level = {1}", tierLevelCommand.ApiKey, tierLevelCommand.TierLevel)); } else { throw new InstanceNotFoundException(string.Format("No user found for the user ID")); } } else { throw new InstanceNotFoundException(string.Format("No Security Key found for the API key: {0}", tierLevelCommand.TierLevel)); } }
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); }
/// <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> /// Check and validate Mfa Subscription for the given action in the case of a user generated key /// </summary> /// <returns></returns> public Tuple <bool, string> CheckUserGeneratedKeySubscription(SecurityKeysPair securityKeysPair, string currentAction, string mfaCode) { if (securityKeysPair != null) { // Check if the user has asked for the TFA for the current given action for this Api Key if (securityKeysPair.CheckMfaSubscriptions(currentAction)) { if (!string.IsNullOrEmpty(securityKeysPair.MfaCode)) { if (!string.IsNullOrEmpty(mfaCode)) { // If the given code matches the user's stored mfa code, then return true if (securityKeysPair.VerifyMfaCode(mfaCode)) { return(new Tuple <bool, string>(true, "Verification Successful")); } else { Log.Error(string.Format("MFA code could not be verified: Api Key = {0}, Action = {1}", securityKeysPair.ApiKey, currentAction)); //throw new InvalidOperationException("MFA code could not be verified"); return(new Tuple <bool, string>(false, "Mfa Code is incorrect")); } } else { return(new Tuple <bool, string>(false, string.Format("Given Mfa code is null"))); } } else { return(new Tuple <bool, string>(false, string.Format("No MfaPassword is assigned to the Api Key = {0}", securityKeysPair.ApiKey))); } } // If the user has not subscribed TFA for any action, then let the user go ahead without any more checks else { Log.Debug(string.Format("MFA not enabled: Action = {0}. Request will proceed", currentAction)); return(new Tuple <bool, string>(true, "No MFA subscription enabled")); } } else { return(new Tuple <bool, string>(false, "SecurityKeysPair instance is null")); } }
/// <summary> /// Get user tier status /// </summary> /// <param name="apiKey"></param> /// <returns></returns> public UserTierStatusRepresentation[] GetTierLevelStatuses(string apiKey) { List <UserTierStatusRepresentation> representations = new List <UserTierStatusRepresentation>(); SecurityKeysPair keysPair = _securityKeysRepository.GetByApiKey(apiKey); if (keysPair != null) { User user = _userRepository.GetUserById(keysPair.UserId); UserTierLevelStatus[] getLevelStatuses = user.GetAllTiersStatus(); for (int i = 0; i < getLevelStatuses.Length; i++) { representations.Add(new UserTierStatusRepresentation(getLevelStatuses[i].Status.ToString(), getLevelStatuses[i].Tier)); } return(representations.ToArray()); } throw new InvalidOperationException("Invalid apiKey"); }
public void CreateSecurityKeyPair_PersistAndReadFromDatabaseByDescriptionKey_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.GetByKeyDescriptionAndUserId("1", 1); 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); }
/// <summary> /// Submit Mfa Subscription settings for user /// </summary> /// <returns></returns> public SubmitMfaSettingsResponse SubmitMfaSettings(MfaSettingsCommand mfaSettingsCommand) { // Find security keys SecurityKeysPair securityKeysPair = _securityKeysRepository.GetByApiKey(mfaSettingsCommand.ApiKey); if (securityKeysPair != null) { // If the securityKeysPair instance is system generated, then assign the TFA susbcriptions to the user instance if (securityKeysPair.SystemGenerated) { // Find user User user = _userRepository.GetUserById(securityKeysPair.UserId); if (user != null) { user.AssignMfaSubscriptions(mfaSettingsCommand.MfaSettingsList); _persistenceRepository.SaveUpdate(user); return(new SubmitMfaSettingsResponse(true, "Mfa Subscription successful")); } // If user is not found else { Log.Error(string.Format("No user instance found for UserId = {0}", securityKeysPair.UserId)); throw new NullReferenceException(string.Format("No user instance found for UserId = {0}", securityKeysPair.UserId)); } } // If the securityKeysPair instance is user generated, them assign the TFA subscriptions to the SecurityKeysPair instance else { securityKeysPair.AssignMfaSubscriptions(mfaSettingsCommand.MfaSettingsList); securityKeysPair.AssignMfaCode(mfaSettingsCommand.ApiKeyPassword); _persistenceRepository.SaveUpdate(securityKeysPair); return(new SubmitMfaSettingsResponse(true, "Mfa Subscription successful")); } } // If security keys pair instance is not found else { Log.Error(string.Format("No Security keys pair instance found for Api Key = {0}", mfaSettingsCommand.ApiKey)); throw new NullReferenceException(string.Format("No Security keys pair instance found for Api Key = {0}", mfaSettingsCommand.ApiKey)); } }
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); }
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 UserGeneratedKeysCancelOrderSuccessfulTest_TestsIfTheAuthenticationIsSuccessful_VerifiesThroughTheReturnedValue() { ISecurityKeysRepository securityKeysRepository = (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"]; IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"]; IIdentityAccessPersistenceRepository persistenceRepository = (IIdentityAccessPersistenceRepository)ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"]; UserAuthenticationService userAuthenticationService = new UserAuthenticationService(userRepository, securityKeysRepository, persistenceRepository); string nounce = userAuthenticationService.GenerateNonce(); string apiKey = "123456789"; string uri = "www.blancrock.com/orders/cancelorder"; string secretKey = "1234567"; string username = "******"; List <SecurityKeysPermission> permissionslist = new List <SecurityKeysPermission>(); permissionslist.Add(new SecurityKeysPermission(apiKey, new Permission(PermissionsConstant.Cancel_Order, "Query Cancel Orders"), true)); // Create System generated Keys and store in repo //SecurityKeysPairFactory.UserGeneratedSecurityPair(username, "1", apiKey, secretKey, true, "", // false, DateTime.Now, false, DateTime.Now, permissionslist, securityKeysRepository); // Create a user and store it in database, this is the user for whom we have created the key User user = new User("*****@*****.**", username, "abc", "Pakistan", TimeZone.CurrentTimeZone, "", ""); user.AutoLogout = new TimeSpan(0, 0, 10, 0); persistenceRepository.SaveUpdate(user); // Get the user from the database, to confirm the user.Id generated by the database User userByUserName = userRepository.GetUserByUserName(username); SecurityKeysPair securityKeysPair = new SecurityKeysPair("1", apiKey, secretKey, userByUserName.Id, DateTime.Now.AddHours(2), DateTime.Now, DateTime.Now, DateTime.Now, false, permissionslist); securityKeysPair.EnableExpirationDate = true; persistenceRepository.SaveUpdate(securityKeysPair); string response = String.Format("{0}:{1}:{2}", apiKey, uri, secretKey).ToMD5Hash(); bool authenticate = userAuthenticationService.Authenticate(new AuthenticateCommand("Rtg65s345", nounce, apiKey, uri, response, "1")); Assert.IsTrue(authenticate); }
/// <summary> /// Get tier 3 details of the user /// </summary> /// <param name="apiKey"></param> /// <returns></returns> public Tier3Details GetTier3Details(string apiKey) { SecurityKeysPair keysPair = _securityKeysRepository.GetByApiKey(apiKey); if (keysPair != null) { User user = _userRepository.GetUserById(keysPair.UserId); if (user.GetTierLevelStatus(new Tier(TierLevelConstant.Tier2, TierLevelConstant.Tier2)) == Status.Verified.ToString()) { if (user.GetTierLevelStatus(new Tier(TierLevelConstant.Tier3, TierLevelConstant.Tier3)) == Status.NonVerified.ToString()) { throw new InvalidOperationException("Tier 3 details are not submitted yet."); } return(new Tier3Details(user.SocialSecurityNumber, user.NationalIdentificationNumber)); } throw new InvalidOperationException("First verify Tier 2"); } throw new InvalidOperationException("Key doesnot exist"); }