Beispiel #1
0
        public void InitializeSync()
        {
            if (Manager.SharedInstance.GetDatabase(DatabaseName) == null)
            {
                return;
            }

            UninitializeSync();

            IAuthenticator auth =
                string.IsNullOrWhiteSpace(Username)
                ? null
                : AuthenticatorFactory.CreateBasicAuthenticator(Username, Password);

            pull = Manager.SharedInstance.GetDatabase(DatabaseName).CreatePullReplication(RemoteSyncUrl);
            if (auth != null)
            {
                pull.Authenticator = auth;
            }

            push = Manager.SharedInstance.GetDatabase(DatabaseName).CreatePushReplication(RemoteSyncUrl);
            if (auth != null)
            {
                push.Authenticator = auth;
            }

            pull.Continuous = push.Continuous = true;

            pull.Changed += ReplicationProgress;
            push.Changed += ReplicationProgress;

            pull.Start();
            push.Start();
        }
        /// <summary>
        /// Sets up the scan job.
        /// </summary>
        /// <param name="device">The device.</param>
        protected override void SetupJob(IDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException(nameof(device));
            }

            UpdateStatus(string.Format("Setting up device at address {0} for user {1}", device.Address, ExecutionData.Credential.UserName));

            string entryButtonTitle = "My workflow (FutureSmart)";

            IAuthenticator auth = AuthenticatorFactory.Create(device, ExecutionData.Credential, AuthenticationProvider.Auto);

            auth.WorkflowLogger = WorkflowLogger;

            AuthenticationMode am = (_data.ApplicationAuthentication == false) ? AuthenticationMode.Eager : AuthenticationMode.Lazy;

            if (am.Equals(AuthenticationMode.Eager))
            {
                UpdateStatus("Authenticating by pressing the Sign In button first.");
            }
            else
            {
                UpdateStatus(string.Format("Authenticating by pressing the {0} button first.", entryButtonTitle));
            }

            _hpecApp = HpecFactory.Create(device);
            _hpecApp.WorkflowLogger = WorkflowLogger;

            _hpecApp.Launch(auth, am);
        }
Beispiel #3
0
        /// <summary>
        /// Initializes the authenticator that will be used in the run, including setting up the badgebox if needed.
        /// </summary>
        /// <param name="provider">The authentication provider to create</param>
        /// <param name="device">The device that will be used for the run.</param>
        private IAuthenticator GetAuthenticator(AuthenticationProvider provider, IDevice device)
        {
            IAuthenticator authenticator = AuthenticatorFactory.Create(_deviceInfo.AssetId, device, provider, _executionData);

            authenticator.WorkflowLogger = _workflowLogger;
            return(authenticator);
        }
Beispiel #4
0
        /// <summary>
        /// Starts a replication for the session
        /// </summary>
        /// <param name="username">The username to use for the replication</param>
        /// <param name="password">The password to use for replication auth (optional)</param>
        public static void StartReplication(string username, string password = null)
        {
            var authenticator = default(IAuthenticator);

            if (username != null && password != null)
            {
                authenticator = AuthenticatorFactory.CreateBasicAuthenticator(username, password);
            }

            var db     = AppWideManager.GetDatabase(username);
            var pusher = db.CreatePushReplication(SyncGatewayUrl);

            pusher.Continuous    = true;
            pusher.Authenticator = authenticator;
            pusher.Changed      += HandleReplicationChanged;


            var puller = db.CreatePullReplication(SyncGatewayUrl);

            puller.Continuous    = true;
            puller.Authenticator = authenticator;
            puller.Changed      += HandleReplicationChanged;

            pusher.Start();
            puller.Start();

            _pusher = pusher;
            _puller = puller;
        }
        public void TestGetAuthenticationHeaderValue()
        {
            var username1  = "username1";
            var password1  = "password1";
            var credParam1 = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username1, password1)));

            var auth       = AuthenticatorFactory.CreateBasicAuthenticator(username1, password1);
            var authHeader = AuthUtils.GetAuthenticationHeaderValue(auth, null);

            Assert.IsNotNull(authHeader);
            Assert.AreEqual(credParam1, authHeader.Parameter);

            var username2  = "username2";
            var password2  = "password2";
            var credParam2 = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username2, password2)));

            var userinfo = username2 + ":" + password2;
            var uri      = new Uri("http://" + userinfo + "@couchbase.com");
            var request  = new HttpRequestMessage(HttpMethod.Get, uri);

            authHeader = AuthUtils.GetAuthenticationHeaderValue(auth, request.RequestUri);
            Assert.IsNotNull(authHeader);
            Assert.AreEqual(credParam2, authHeader.Parameter);

            uri        = new Uri("http://www.couchbase.com");
            request    = new HttpRequestMessage(HttpMethod.Get, uri);
            authHeader = AuthUtils.GetAuthenticationHeaderValue(null, request.RequestUri);
            Assert.IsNull(authHeader);

            auth       = AuthenticatorFactory.CreateFacebookAuthenticator("1234");
            authHeader = AuthUtils.GetAuthenticationHeaderValue(auth, null);
            Assert.IsNull(authHeader);
        }
Beispiel #6
0
        public void Replication()
        {
            var url  = new Uri("http://127.0.0.1:5984/couchbaseevents-xam");
            var push = db.CreatePushReplication(url);
            var pull = db.CreatePullReplication(url);
            var auth = AuthenticatorFactory.CreateBasicAuthenticator("xamarain", "xamarain");

            push.Authenticator = auth;
            pull.Authenticator = auth;
            push.Continuous    = true;
            pull.Continuous    = true;
            push.Changed      += (sender, e) =>
            {
                // Will be called when the push replication status changes
                Console.WriteLine(e.Username);
                Console.WriteLine(e.ChangesCount);
                Console.WriteLine(e.Status);
            };
            pull.Changed += (sender, e) =>
            {
                // Will be called when the pull replication status changes
                Console.WriteLine(e.Username);
                Console.WriteLine(e.ChangesCount);
                Console.WriteLine(e.Status);
            };
            pull.Start();
            push.Start();
        }
 public IAuthenticator CreateAuthenticator(ReplicationDriverContext context)
 {
     return(AuthenticatorFactory.CreateBasicAuthenticator(
                username: this._credentials.Item1,
                password: this._credentials.Item2
                ));
 }
Beispiel #8
0
        public void TestBasicAuthenticationWrongPassword()
        {
            if (!Boolean.Parse((string)GetProperty("replicationTestsEnabled")))
            {
                Assert.Inconclusive("Server tests disabled.");
                return;
            }
            var username      = "******";
            var password      = "******";
            var wrongPassword = "******";

            AddUser(username, password);

            CreateDocuments(database, 10);

            var url = GetReplicationURLWithoutCredentials();

            var replicator = database.CreatePushReplication(url);

            replicator.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(username, wrongPassword);

            Assert.IsNotNull(replicator);
            Assert.IsNotNull(replicator.Authenticator);
            Assert.IsTrue(replicator.Authenticator is BasicAuthenticator);

            RunReplication(replicator);

            var lastError = replicator.LastError;

            Assert.IsNotNull(lastError);
        }
Beispiel #9
0
        public void TestOpenIDExpiredToken()
        {
            if (_storageType != StorageEngineTypes.SQLite)
            {
                return;
            }

            var remoteUri = new Uri($"http://{GetReplicationServer ()}:{GetReplicationPort ()}/openid_db");

            Assert.IsTrue(OpenIDAuthenticator.ForgetIDTokens(remoteUri));

            var callbackInvoked = false;
            var auth            = (OpenIDAuthenticator)AuthenticatorFactory.CreateOpenIDAuthenticator(manager, (login, authBase, cont) =>
            {
                AssertValidOIDCLogin(login, authBase, remoteUri);
                Assert.IsFalse(callbackInvoked);
                callbackInvoked = true;
                cont(null, null);
            });

            // Set bogus ID and refresh tokens, so first the session check will fail, then the attempt
            // to refresh the ID token will fail.  Finally the callback above will be called.
            auth.IDToken      = "BOGUS_ID";
            auth.RefreshToken = "BOGUS_REFRESH";

            var pullError = PullWithOIDCAuth(remoteUri, auth);

            Assert.IsTrue(callbackInvoked);
            Assert.IsNotNull(pullError);
            Assert.IsInstanceOf(typeof(OperationCanceledException), pullError);
        }
Beispiel #10
0
        public void TestGetAuthenticationHeaderValue()
        {
            var username1  = "username1";
            var password1  = "password1";
            var credParam1 = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username1, password1)));

            var auth       = AuthenticatorFactory.CreateBasicAuthenticator(username1, password1) as BasicAuthenticator;
            var authHeader = auth.AuthorizationHeaderValue;

            Assert.IsNotNull(authHeader);
            Assert.AreEqual(credParam1, authHeader.Split(' ')[1]);

            var username2  = "username2";
            var password2  = "password2";
            var credParam2 = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username2, password2)));

            var userinfo = username2 + ":" + password2;
            var uri      = new Uri("http://" + userinfo + "@couchbase.com");

            auth       = (BasicAuthenticator)AuthenticatorFactory.CreateFromUri(uri);
            authHeader = auth.AuthorizationHeaderValue;
            Assert.IsNotNull(authHeader);
            Assert.AreEqual(credParam2, authHeader.Split(' ')[1]);

            uri  = new Uri("http://www.couchbase.com");
            auth = (BasicAuthenticator)AuthenticatorFactory.CreateFromUri(uri);
            Assert.IsNull(auth);

            var auth2 = AuthenticatorFactory.CreateFacebookAuthenticator("1234") as ICustomHeadersAuthorizer;

            Assert.IsNull(auth2);
        }
        private static Replication SetupReplication(Manager manager, bool continuous, bool createTarget, Uri remoteUri, bool isPull, string user, string password)
        {
            if (remoteUri == null)
            {
                return(null);
            }

            var databaseName  = remoteUri.Segments.Last();
            var authenticator = default(IAuthenticator);

            if (user != null && password != null)
            {
                Console.WriteLine("Setting session credentials for user '{0}'", user);
                authenticator = AuthenticatorFactory.CreateBasicAuthenticator(user, password);
            }

            if (isPull)
            {
                Console.WriteLine("Pulling from <{0}> --> {1}", remoteUri, databaseName);
            }
            else
            {
                Console.WriteLine("Pushing {0} --> <{1}>", databaseName, remoteUri);
            }

            var db = manager.GetExistingDatabase(databaseName);

            if (isPull && db == null)
            {
                db = manager.GetDatabase(databaseName);
            }

            if (db == null)
            {
                Console.Error.WriteLine("Couldn't open database {0}", databaseName);
                return(null);
            }

            var repl = isPull ? db.CreatePullReplication(remoteUri) : db.CreatePushReplication(remoteUri);

            repl.Continuous    = continuous;
            repl.CreateTarget  = createTarget;
            repl.Authenticator = authenticator;
            repl.Changed      += (sender, e) =>
            {
                Console.WriteLine("*** Replicator status changed ({0} {1}/{2}) ***", e.Status, e.CompletedChangesCount, e.ChangesCount);
                if (e.LastError != null)
                {
                    Console.Error.WriteLine("*** Replicator reported error ***", e);
                }
                else if (e.Status == ReplicationStatus.Stopped)
                {
                    Console.WriteLine("*** Replicator finished ***");
                }
            };

            repl.Start();
            return(repl);
        }
Beispiel #12
0
        private InteractiveAuthenticatorBase CreateAuthenticator(string key)
        {
            var af    = new AuthenticatorFactory();
            var parts = key.Split('|');
            var a     = af.CreateInteractiveAuthenticator(parts[0], parts[1]);

            return(a);
        }
Beispiel #13
0
        /// <summary>
        /// Initializes the authenticator that will be used in the run.
        /// </summary>
        /// <param name="provider">The authentication provider to create.</param>
        /// <param name="device">The device that will be used for the run.</param>
        protected void InitializeAuthenticator(AuthenticationProvider provider, IDevice device)
        {
            // Only AutoStore authentication (Lazy) is allowed by the application at this time.
            // Also, card auth is not supported at this time.

            Authenticator = AuthenticatorFactory.Create(device, ExecutionData.Credential, provider);
            Authenticator.WorkflowLogger = WorkflowLogger;
        }
        public void Multiple_Create_calls_should_return_different_authenticators_instances()
        {
            var subject        = new AuthenticatorFactory(() => new PlainAuthenticator(new UsernamePasswordCredential("source", "user", "password"), serverApi: null));
            var authenticator1 = subject.Create();
            var authenticator2 = subject.Create();

            authenticator1.Should().NotBeSameAs(authenticator2);
        }
        public void Create_should_create_authenticator_based_on_the_provided_delegate()
        {
            var subject       = new AuthenticatorFactory(() => new PlainAuthenticator(new UsernamePasswordCredential("source", "user", "password"), serverApi: null));
            var authenticator = subject.Create();

            var typedAuthenticator = authenticator.Should().BeOfType <PlainAuthenticator>().Subject;

            typedAuthenticator.DatabaseName.Should().Be("source");
        }
 private void PerformLogin(object sender, EventArgs e)
 {
     ((Button)sender).IsEnabled = false;
     StartPull(r =>
     {
         var callback    = OpenIDAuthenticator.GetOIDCCallback();
         r.Authenticator = AuthenticatorFactory.CreateOpenIDAuthenticator(Manager.SharedInstance, callback);
         _changedHandler = CheckAuthCodeLoginComplete;
     });
 }
Beispiel #17
0
        /// <summary>
        ///     Creates a derived key stream from which a derived key can be read.
        /// </summary>
        /// <param name="key">The key to derive from.</param>
        /// <param name="salt">
        ///     The salt.
        ///     A unique salt means a unique scrypt stream, even if the original key is identical.
        /// </param>
        /// <param name="cost">
        ///     The cost parameter, typically a fairly large number such as 262144.
        ///     Memory usage and CPU time scale approximately linearly with this parameter.
        /// </param>
        /// <param name="blockSize">
        ///     The mixing block size, typically 8.
        ///     Memory usage and CPU time scale approximately linearly with this parameter.
        /// </param>
        /// <param name="parallel">
        ///     The level of parallelism, typically 1.
        ///     CPU time scales approximately linearly with this parameter.
        /// </param>
        /// <param name="maxThreads">
        ///     The maximum number of threads to spawn to derive the key.
        ///     This is limited by the <paramref name="parallel" /> value.
        ///     <c>null</c> will use as many threads as possible.
        /// </param>
        /// <returns>The derived key stream.</returns>
        public static Pbkdf2 GetStream(byte[] key, byte[] salt,
                                       int cost, int blockSize, int parallel, int?maxThreads)
        {
            byte[] B    = GetEffectivePbkdf2Salt(key, salt, cost, blockSize, parallel, maxThreads);
            IMac   hmac = AuthenticatorFactory.CreateHmacPrimitive(HashFunction.Sha256, key, null);
            var    kdf  = new Pbkdf2(hmac, B, 1);

            //Security.Clear(B);
            Array.Clear(B, 0, B.Length);
            return(kdf);
        }
        internal async Task OpenAsync(CancellationToken cancellationToken)
        {
            logger.Debug("Open Session");

            if (authenticator == null)
            {
                authenticator = AuthenticatorFactory.GetAuthenticator(this);
            }

            await authenticator.AuthenticateAsync(cancellationToken).ConfigureAwait(false);
        }
        internal void Open()
        {
            logger.Debug("Open Session");

            if (authenticator == null)
            {
                authenticator = AuthenticatorFactory.GetAuthenticator(this);
            }

            authenticator.Authenticate();
        }
        public void Authentication(string appName)
        {
            // Create Authenticator
            IAuthenticator auth = AuthenticatorFactory.Create(_device, _credential, AuthenticationProvider.Windows);

            var preparationManager = new SiriusUIv2PreparationManager(_device);

            try
            {
                preparationManager.InitializeDevice(true);

                switch (appName)
                {
                case "Sign In":
                    throw new DeviceWorkflowException("Sign In from home screen not supported for this device");

                case "HP AC Secure Pull Print":
                case "My workflow (FutureSmart)":
                case "Pull Print":
                    _device.ControlPanel.PressByValue("Apps");
                    WaitForScreenLabel("view_oxpd_home", TimeSpan.FromSeconds(30));

                    string displayedTitle = GetButtonDisplayedTitle(appName);
                    _device.ControlPanel.ScrollToItemByValue("oxpd_home_table", displayedTitle);
                    _device.ControlPanel.PressByValue(displayedTitle);

                    WaitForScreenLabel("view_sips_form", TimeSpan.FromSeconds(30));
                    auth.Authenticate();
                    break;

                default:
                    AuthenticationHelper.LaunchApp(_device, appName, auth);
                    break;
                }
            }
            catch (Exception ex)
            {
                var currentScreen = _device.ControlPanel.ActiveScreenLabel();
                ExecutionServices.SystemTrace.LogDebug("Active screen = " + currentScreen);
                throw new DeviceInvalidOperationException($"Unable to authenticate: current screen = {currentScreen}", ex);
            }
            finally
            {
                try
                {
                    preparationManager.NavigateHome();
                }
                catch
                {
                    //ignored
                }
            }
        }
Beispiel #21
0
        public static void Main(string[] args)
        {
            var syncGatewayUrl = new Uri("http://localhost:4984/db/");

            Manager  manager    = Manager.SharedInstance;
            Database airlineDb  = manager.GetDatabase("airline");
            Database routeDb    = manager.GetDatabase("route");
            Database airportDb  = manager.GetDatabase("airport");
            Database landmarkDb = manager.GetDatabase("landmark");
            Database hotelDb    = manager.GetDatabase("hotel");

            // Total docs: 31591
            var testDbs = new TestDatabase[] {
                new TestDatabase(airlineDb, "airline", "pass", 187),
                new TestDatabase(routeDb, "route", "pass", 24024),
                new TestDatabase(airportDb, "airport", "pass", 1968),
                new TestDatabase(landmarkDb, "landmark", "pass", 4495),
                new TestDatabase(hotelDb, "hotel", "pass", 917),
            };

            // Start continuous push / pull replications for each database
            foreach (var testDb in testDbs)
            {
                IAuthenticator replicationAuth = AuthenticatorFactory.CreateBasicAuthenticator(testDb.UserName, testDb.Password);

                Replication pullReplication = testDb.Database.CreatePullReplication(syncGatewayUrl);
                pullReplication.Authenticator = replicationAuth;
                pullReplication.Continuous    = true;
                pullReplication.Start();

                Replication pushReplication = testDb.Database.CreatePushReplication(syncGatewayUrl);
                pushReplication.Authenticator = replicationAuth;
                pushReplication.Continuous    = true;
                pushReplication.Start();
            }

            // Wait for replication to stop
            var timeout = TimeSpan.FromMinutes(20);

            // Poll until all dbs have the expected number of docs
            WaitForImport(testDbs, timeout);

            // Update each doc via Lite
            TouchAllDocs(testDbs);

            // Run python script to update all the docs via the SDK
            Console.WriteLine("\nWaiting for SDK to perform updates ...");
            var line = Console.ReadLine();

            // Wait for replication to stop
            WaitForSDKUpdates(testDbs, timeout);
        }
Beispiel #22
0
        public void Authentication(string appName)
        {
            // Create Authenticator
            IAuthenticator auth = AuthenticatorFactory.Create(_device, _credential, AuthenticationProvider.Auto);

            try
            {
                var jediWindJammerPrepManager = new JediWindjammerPreparationManager(_device);
                jediWindJammerPrepManager.InitializeDevice(true);

                switch (appName)
                {
                case "Sign In":
                    _device.ControlPanel.PressToNavigate("mSignInButton", "SignInForm", ignorePopups: true);

                    if (_device.ControlPanel.GetControls().Contains("m_RadioButton"))
                    {
                        //Using PressScreen since the small screen doesn't seem to like the mOKButton
                        _device.ControlPanel.PressScreen(250, 250);
                    }

                    auth.Authenticate();
                    break;

                case "Follow-You Printing":
                case "HP AC Secure Pull Print":
                case "My workflow (FutureSmart)":
                case "Pull Print":
                case "Scan To Me":
                case "Scan To My Files":
                case "Scan To Folder":
                case "Public Distributions":
                case "Routing Sheet":
                case "Personal Distributions":
                    _device.ControlPanel.ScrollPressWait("mAccessPointDisplay", "Title", appName, "SignInForm", StringMatch.StartsWith, TimeSpan.FromSeconds(60));
                    auth.Authenticate();
                    break;

                default:
                    AuthenticationHelper.LaunchApp(_device, appName, auth);
                    break;
                }
            }
            catch (Exception ex)
            {
                var    currentScreen = _device.ControlPanel.CurrentForm();
                string message       = $"Unable to authenticate.  Verify EWS authentication configuration and that {appName} button invokes the intended auth method. (current screen: {currentScreen}";
                ExecutionServices.SystemTrace.LogDebug(message + $"; Exception: {ex.Message}");
                throw new DeviceInvalidOperationException(message + ")", ex);
            }
        }
Beispiel #23
0
        protected void RunDiscreteVectorTest(int number, DiscreteVectorDigestTestCase testCase)
        {
            var hashFunctionEnum = testCase.Primitive;

            IHash authenticator = AuthenticatorFactory.CreateHashPrimitive(hashFunctionEnum);

            authenticator.BlockUpdate(testCase.Message, 0, testCase.Message.Length);
            var output = new byte[authenticator.OutputSize];

            authenticator.DoFinal(output, 0);

            Assert.IsTrue(testCase.Output.SequenceEqualShortCircuiting(output),
                          "Test #{0} (\"{1}\") failed!", number, testCase.Name);
        }
        private void StartReplications()
        {
            _pull = _db.CreatePullReplication(CreateSyncUri());
            _push = _db.CreatePushReplication(CreateSyncUri());
            var authenticator = AuthenticatorFactory.CreateBasicAuthenticator(User, Password);

            _pull.Authenticator = authenticator;
            _push.Authenticator = authenticator;
            _pull.Continuous    = true;
            _push.Continuous    = true;
            //       _pull.Start();
            //       _push.Start();
            _push.Changed += OnPushChanged;
        }
Beispiel #25
0
        public static void KeyExchange(ArraySegment <byte> sharedKey, ArraySegment <byte> publicKey, ArraySegment <byte> privateKey, bool naclCompat = false)
        {
            if (sharedKey.Array == null)
            {
                throw new ArgumentNullException("sharedKey.Array");
            }
            if (publicKey.Array == null)
            {
                throw new ArgumentNullException("publicKey.Array");
            }
            if (privateKey.Array == null)
            {
                throw new ArgumentNullException("privateKey");
            }
            if (sharedKey.Count != SharedKeySizeInBytes)
            {
                throw new ArgumentException("sharedKey.Count != 32");
            }
            if (publicKey.Count != PublicKeySizeInBytes)
            {
                throw new ArgumentException("publicKey.Count != 32");
            }
            if (privateKey.Count != ExpandedPrivateKeySizeInBytes)
            {
                throw new ArgumentException("privateKey.Count != 64");
            }

            FieldElement montgomeryX, edwardsY, edwardsZ, sharedMontgomeryX;

            FieldOperations.fe_frombytes(out edwardsY, publicKey.Array, publicKey.Offset);
            FieldOperations.fe_1(out edwardsZ);
            Curve25519.EdwardsToMontgomeryX(out montgomeryX, ref edwardsY, ref edwardsZ);

            IHash hasher = AuthenticatorFactory.CreateHashPrimitive(HashFunction.Sha512);

            hasher.BlockUpdate(privateKey.Array, privateKey.Offset, 32);
            byte[] h = new byte[64];
            hasher.DoFinal(h, 0);
            ScalarOperations.sc_clamp(h, 0);
            MontgomeryOperations.scalarmult(out sharedMontgomeryX, h, 0, ref montgomeryX);
            h.SecureWipe();
            FieldOperations.fe_tobytes(sharedKey.Array, sharedKey.Offset, ref sharedMontgomeryX);

            if (naclCompat)
            {
                Curve25519.KeyExchangeOutputHashNaCl(sharedKey.Array, sharedKey.Offset);
            }
        }
Beispiel #26
0
        public virtual void StartReplicationSyncWithFacebookLogin(string accessToken, string
                                                                  email)
        {
            Authenticator facebookAuthenticator = AuthenticatorFactory.CreateFacebookAuthenticator
                                                      (accessToken);

            Replication[] replications = CreateReplications();
            Replication   pullRep      = replications[0];
            Replication   pushRep      = replications[1];

            pullRep.SetAuthenticator(facebookAuthenticator);
            pushRep.SetAuthenticator(facebookAuthenticator);
            pullRep.Start();
            pushRep.Start();
            Log.V(Tag, "Start Replication Sync ...");
        }
Beispiel #27
0
        /// <summary>
        /// Creates a new instance of the <see cref="ApiAccessorBase" /> class
        /// with the API endpoint relative path, base API path
        /// and the API configuration is specified (or use <see cref="Configuration.Default" />).
        /// </summary>
        /// <param name="relativePath">The API endpoint relative path.</param>
        /// <param name="basePath">The base API path.</param>
        /// <param name="configuration">The API configuration.</param>
        public ApiAccessorBase(string relativePath, string basePath = null, Configuration configuration = null)
        {
            Configuration        = configuration ?? Configuration.Default;
            Path                 = relativePath ?? throw new ArgumentNullException(nameof(relativePath));
            ExceptionFactory     = Configuration.DefaultExceptionFactory;
            AuthenticatorFactory = Configuration.DefaultAuthenticatorFactory;

            if (Uri.TryCreate(basePath, UriKind.Absolute, out var baseUrl))
            {
                _restClient = new RestClient(baseUrl);
            }
            else
            {
                _restClient = new RestClient(Configuration.DEFAULT_BASE_PATH);
            }
        }
Beispiel #28
0
        public void TestReplicatorErrorStatus()
        {
            var email       = "*****@*****.**";
            var accessToken = "fake_access_token";
            var remoteUrl   = GetReplicationURL().ToString();

            FacebookAuthorizer.RegisterAccessToken(accessToken, email, remoteUrl);

            var replicator = database.CreatePullReplication(GetReplicationURL());

            replicator.Authenticator = AuthenticatorFactory.CreateFacebookAuthenticator(accessToken);

            RunReplication(replicator);

            Assert.IsNotNull(replicator.LastError);
        }
        /// <summary>
        /// Selects a control panel activity to run and calls the appropriate method to run it
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private PluginExecutionResult RunControlPanelActivity(IDevice device)
        {
            UpdateStatus("Running Control Panel Activity...");
            PluginExecutionResult controlPanelActivityResult = new PluginExecutionResult(PluginResult.Failed);

            //Initializing the authenticator
            IAuthenticator authenticator = AuthenticatorFactory.Create(device, ExecutionData.Credential);

            authenticator.WorkflowLogger = WorkflowLogger;

            object controlPanelData = null;
            //Selecting a random control Panel activity.
            Type ControlPanelActivityToRun = SelectRandomActivity(_data.SelectedControlPanelActivities);

            Attribute[] attributes = Attribute.GetCustomAttributes(ControlPanelActivityToRun);
            foreach (Attribute attr in attributes)
            {
                if (attr is ControlPanelActivity)
                {
                    ControlPanelActivity controlPanelAttribute = (ControlPanelActivity)attr;
                    switch (controlPanelAttribute.ActivityName)
                    {
                    case "Copy":
                        //Copy activity is selected
                        UpdateStatus("Selected Control Panel Activity: Copy");
                        controlPanelData           = _data.SelectedControlPanelActivities.OfType <CopyActivityData>().Single();
                        controlPanelActivityResult = ExecuteCopy(device, controlPanelData, authenticator);
                        break;

                    case "Scan":
                        //Scan activity is selected
                        controlPanelData           = _data.SelectedControlPanelActivities.OfType <ScanActivityData>().Single();
                        controlPanelActivityResult = ExecuteScan(device, controlPanelData, authenticator);
                        break;

                    case "Fax":
                        //Fax activity is selected
                        UpdateStatus("Selected Control Panel Activity: Fax");
                        controlPanelData           = _data.SelectedControlPanelActivities.OfType <FaxActivityData>().Single();
                        controlPanelActivityResult = ExecuteFax(device, controlPanelData, authenticator);
                        break;
                    }
                }
            }

            return(controlPanelActivityResult);
        }
        public void TestBasicAuthenticationWrongPassword()
        {
            if (!Boolean.Parse((string)Runtime.Properties["replicationTestsEnabled"]))
            {
                Assert.Inconclusive("Server tests disabled.");
                return;
            }
            var username      = "******";
            var password      = "******";
            var wrongPassword = "******";

            AddUser(username, password);

            var url = GetReplicationURLWithoutCredentials();
            var httpClientFactory = new CouchbaseLiteHttpClientFactory(new CookieStore());

            manager.DefaultHttpClientFactory = httpClientFactory;

            var replicator = database.CreatePushReplication(url);

            replicator.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(username, wrongPassword);

            Assert.IsNotNull(replicator);
            Assert.IsNotNull(replicator.Authenticator);
            Assert.IsTrue(replicator.Authenticator is BasicAuthenticator);

            replicator.Start();

            var doneEvent = new ManualResetEvent(false);

            Task.Factory.StartNew(() =>
            {
                var timeout = DateTime.UtcNow + TimeSpan.FromSeconds(30);
                var stop    = false;
                while (DateTime.UtcNow < timeout && !stop)
                {
                    stop |= replicator.Status != ReplicationStatus.Active;
                    Sleep(TimeSpan.FromMilliseconds(10));
                }
                doneEvent.Set();
            });
            doneEvent.WaitOne(TimeSpan.FromSeconds(10));
            Sleep(1000);
            var lastError = replicator.LastError;

            Assert.IsNotNull(lastError);
        }