/// <summary>
 /// parameterized constructor
 /// </summary>
 /// <param name="userRepository"></param>
 /// <param name="securityKeysRepository"></param>
 /// <param name="persistenceRepository"></param>
 public UserTierLevelApplicationService(IUserRepository userRepository, ISecurityKeysRepository securityKeysRepository, IIdentityAccessPersistenceRepository persistenceRepository, IDocumentPersistence documentPersistence)
 {
     _userRepository         = userRepository;
     _securityKeysRepository = securityKeysRepository;
     _persistenceRepository  = persistenceRepository;
     _documentPersistence    = documentPersistence;
 }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            //return Json format
            //var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/json");
            //config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
            var json = config.Formatters.JsonFormatter;

            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.DependencyResolver = new SpringDependencyResolver(ContextRegistry.GetContext());
            ISecurityKeysRepository securityKeysRepository =
                (ISecurityKeysRepository)ContextRegistry.GetContext()["SecurityKeysPairRepository"];
            IUserRepository userRepository = (IUserRepository)ContextRegistry.GetContext()["UserRepository"];
            IIdentityAccessPersistenceRepository _persistenceRepository =
                (IIdentityAccessPersistenceRepository)
                ContextRegistry.GetContext()["IdentityAccessPersistenceRepository"];

            //Add authentication handler
            config.MessageHandlers.Add(new AuthenticationHandler(new UserAuthenticationService(userRepository,
                                                                                               securityKeysRepository, _persistenceRepository)));

            log.Info("Application Initialized.");
        }
        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 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);
        }
Ejemplo n.º 6
0
        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"));
        }
 /// <summary>
 /// Initializes the service for operating operations for the DigitalSignatures
 /// </summary>
 public SecurityKeysApplicationService(ISecurityKeysGenerationService securityKeysGenerationService,
                                       IIdentityAccessPersistenceRepository persistenceRepository, ISecurityKeysRepository securityKeysRepository, IPermissionRepository permissionRepository)
 {
     _securityKeysGenerationService = securityKeysGenerationService;
     _persistRepository             = persistenceRepository;
     _securityKeysRepository        = securityKeysRepository;
     _permissionRepository          = permissionRepository;
 }
        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 Setup()
        {
            _applicationContext = ContextRegistry.GetContext();
            var connection = ConfigurationManager.ConnectionStrings["MySql"].ToString();

            _securityKeysRepository = _applicationContext["SecurityKeysPairRepository"] as ISecurityKeysRepository;
            _permissionRepository   = _applicationContext["PermissionRespository"] as IPermissionRepository;
            _databaseUtility        = new DatabaseUtility(connection);
            _databaseUtility.Create();
            _databaseUtility.Populate();
        }
 /// <summary>
 /// Initializes with the User Repository
 /// </summary>
 public UserApplicationService(IUserRepository userRepository, ISecurityKeysRepository securityKeysRepository,
                               IPasswordEncryptionService passwordEncryptionService, IIdentityAccessPersistenceRepository persistenceRepository,
                               IEmailService emailService, IPasswordCodeGenerationService passwordCodeGenerationService)
 {
     _userRepository            = userRepository;
     _securityKeysRepository    = securityKeysRepository;
     _passwordEncryptionService = passwordEncryptionService;
     _persistenceRepository     = persistenceRepository;
     _emailService = emailService;
     _passwordCodeGenerationService = passwordCodeGenerationService;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public MfaAuthorizationService(IIdentityAccessPersistenceRepository persistenceRepository, IUserRepository userRepository,
                                ISecurityKeysRepository securityKeysRepository, IMfaCodeSenderService smsService, IMfaCodeSenderService emailService,
                                IMfaCodeGenerationService codeGenerationService)
 {
     _persistenceRepository  = persistenceRepository;
     _userRepository         = userRepository;
     _securityKeysRepository = securityKeysRepository;
     _smsService             = smsService;
     _emailService           = emailService;
     _codeGenerationService  = codeGenerationService;
 }
        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 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);
        }
Ejemplo n.º 15
0
        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);
        }
        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);
        }
 /// <summary>
 /// Initializes with the Secrutiy Keys Repository
 /// </summary>
 /// <param name="userRepository"> </param>
 /// <param name="securityKeysRepository"></param>
 public UserAuthenticationService(IUserRepository userRepository, ISecurityKeysRepository securityKeysRepository, IIdentityAccessPersistenceRepository persistenceRepository)
 {
     _securityKeysRepository = securityKeysRepository;
     _userRepository         = userRepository;
     _persistenceRepository  = persistenceRepository;
 }
        /// <summary>
        /// Create user generated api key
        /// </summary>
        /// <returns></returns>
        public static SecurityKeysPair UserGeneratedSecurityPair(int userId, string keyDescription, string apiKey, string secretKey, bool enableExpirationDate, string expirationDate, bool enableStartDate, string startDate, bool enableEndDate, string endDate, List <SecurityKeysPermission> keysPermissions, ISecurityKeysRepository repository)
        {
            //check if key description already exist
            if (repository.GetByKeyDescriptionAndUserId(keyDescription, userId) != null)
            {
                throw new ArgumentException("The key description already exist");
            }
            SecurityKeysPair securityKeysPair = new SecurityKeysPair(apiKey, secretKey, keyDescription, userId, false, keysPermissions);

            if (enableExpirationDate)
            {
                securityKeysPair.ExpirationDate = Convert.ToDateTime(expirationDate);
            }
            else
            {
                securityKeysPair.ExpirationDate = null;
            }
            if (enableStartDate)
            {
                securityKeysPair.StartDate = Convert.ToDateTime(startDate);
            }
            else
            {
                securityKeysPair.StartDate = null;
            }
            if (enableEndDate)
            {
                securityKeysPair.EndDate = Convert.ToDateTime(endDate);
            }
            else
            {
                securityKeysPair.EndDate = null;
            }
            securityKeysPair.EnableStartDate      = enableStartDate;
            securityKeysPair.EnableEndDate        = enableEndDate;
            securityKeysPair.EnableExpirationDate = enableExpirationDate;
            return(securityKeysPair);
        }
 /// <summary>
 /// Parameterized Constructor
 /// </summary>
 /// <param name="securityKeysRepository"></param>
 public LogoutApplicationService(ISecurityKeysRepository securityKeysRepository)
 {
     _securityKeysRepository = securityKeysRepository;
 }