Ejemplo n.º 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req,
            [StorageAccount("StorageConnectionString")] CloudStorageAccount storageAccount,
            TraceWriter log
            )
        {
            var    client       = storageAccount.CreateCloudTableClient();
            string partitionKey = await Authenticator.Authenticate(client, req);

            if (string.IsNullOrEmpty(partitionKey))
            {
                return(new UnauthorizedResult());
            }


            var itemTable = client.GetTableReference(PartitionV2.TableName);
            await itemTable.CreateIfNotExistsAsync();

            var query   = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
            var exQuery = new TableQuery <PartitionV2>().Where(query);

            var domainPartitions = await QueryHelper.ListAll(itemTable, exQuery);

            var partitions = domainPartitions
                             .Select(p => new PartitionResponse {
                Partition = p.RowKey.Replace(partitionKey, ""), IsActive = p.IsActive
            })
                             .ToList();


            log.Info($"A total of {partitions.Count} partitions were returned");
            return(new OkObjectResult(partitions));
            //return req.CreateResponse(HttpStatusCode.OK, partitions, Json.JsonFormatter);
        }
        public async Task <string> Get()
        {
            var authenticator = new Authenticator();
            var response      = await authenticator.Authenticate();

            return(await response.Content.ReadAsStringAsync());
        }
        /// <summary>
        /// List documents.
        ///
        /// Lists documents that have been submitted for translation.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <returns><see cref="DocumentList" />DocumentList</returns>
        public bool ListDocuments(Callback <DocumentList> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ListDocuments`");
            }

            RequestObject <DocumentList> req = new RequestObject <DocumentList>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbGET,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "ListDocuments"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;

            req.OnResponse = OnListDocumentsResponse;

            Connector.URL = GetServiceUrl() + "/v3/documents";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
Ejemplo n.º 4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            [StorageAccount("StorageConnectionString")] CloudStorageAccount storageAccount,
            TraceWriter log
            )
        {
            try {
                var    client  = storageAccount.CreateCloudTableClient();
                string userKey = await Authenticator.Authenticate(client, req);

                if (string.IsNullOrEmpty(userKey))
                {
                    return(new UnauthorizedResult());
                }

                var subPartition = req.Query["partition"];

                if (string.IsNullOrWhiteSpace(subPartition))
                {
                    return(new BadRequestObjectResult("The query parameter \"partition\" empty or missing"));
                }

                log.Info($"User {userKey} has requested an item download for sub partition {subPartition}");
                var itemTable = client.GetTableReference(ItemV2.TableName);

                var query = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,
                                                               userKey + "-" + subPartition);
                var exQuery = new TableQuery <ItemV2>().Where(query);

                var unfilteredItems = await QueryHelper.ListAll(itemTable, exQuery);

                var filteredItems = unfilteredItems.Where(m => m.IsActive).ToList();
                log.Info($"A total of {filteredItems.Count} items were returned");


                var deleted = await GetDeletedItems(userKey + subPartition, client);

                log.Info($"A total of {deleted.Count} items were marked for deletion");

                if (filteredItems.Count > 80)
                {
                    log.Info($"Disabling partition {subPartition} for {userKey} (may already be disabled)");
                    var table = client.GetTableReference(PartitionV2.TableName);
                    await table.CreateIfNotExistsAsync();

                    DisablePartition(userKey, subPartition, table);
                }

                var result = new DownloadResponse {
                    Items   = filteredItems.Select(m => Map(userKey, m)).ToList(),
                    Removed = deleted
                };

                return(new OkObjectResult(result));
            }
            catch (Exception ex) {
                log.Error(ex.Message, ex);
                return(new ExceptionResult(ex, false));
            }
        }
Ejemplo n.º 5
0
 private void DoAuthentication()
 {
     if (Authenticator != null)
     {
         Authenticator.Authenticate(this, null);
     }
 }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            Authenticator auth = Authenticator.Instance;

            auth.Authenticate(authUrl, clientId, clientSecret);                                                               //Pass auth url, username, and password to authenticate to auth server

            foreach (Endpoint e in auth.GetEndpoints(providerId))                                                             //For the provided endpoint
            {
                XPress xPress = new XPress(e.href);                                                                           //Pass endpoint info to data API (token, href)

                foreach (XLeaType l in xPress.GetXLeas().Data)                                                                //Iterate through each xLea
                {
                    for (int i = 1; i <= xPress.GetLastPage(ServicePath.GetXRostersByXLea, l.refId, navigationPageSize); i++) //Get max page size for rosters by lea
                    {
                        foreach (XRosterType r in xPress.GetXRostersByXLea(l.refId, i, navigationPageSize).Data)              //Get each roster for each lea refId w/ paging
                        {
                            Console.WriteLine("courseTitle: " + r.courseTitle);
                            foreach (XPersonReferenceType p in r.students.studentReference) //Students for each course
                            {
                                Console.WriteLine("refId: " + p.refId);
                                Console.WriteLine("localId: " + p.localId);
                                Console.WriteLine("givenName: " + p.givenName);
                                Console.WriteLine("familyName: " + p.familyName);
                            }
                        }
                        Console.WriteLine("######## PAGE " + i + " ########");
                    }
                }
            }

            Console.Read();
        }
Ejemplo n.º 7
0
        private async Task ReconnectImpl()
        {
            await CloseProto();

            Debug.WriteLine("Creating new transport..");
            if (ClientSettings.Session.AuthKey == null)
            {
                Step3_Response result = await Authenticator.Authenticate(ClientSettings.Session.ServerAddress, ClientSettings.Session.Port);

                ClientSettings.Session.AuthKey    = result.authKey;
                ClientSettings.Session.TimeOffset = result.timeOffset;
                ClientSettings.Session.Salt       = result.serverSalt;
            }

            _protoSender = new MtProtoSender(ClientSettings.Session);

            Subscribe();
            _protoSender.Start();

            var request = new InitConnectionAndGetConfigRequest(s_apiLayer, ClientSettings.AppId, _deviceInfo);

            await SendRpcRequest(request);

            _configuration = request.config;
            _dcOptions     = new DcOptionsCollection(request.config.dcOptions);

            OnConnectionStateChanged(ConnectionStateEventArgs.Connected());
        }
        /// <summary>
        /// List classifiers.
        ///
        /// Returns an empty array if no classifiers are available.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <returns><see cref="ClassifierList" />ClassifierList</returns>
        public bool ListClassifiers(Callback <ClassifierList> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ListClassifiers`");
            }

            RequestObject <ClassifierList> req = new RequestObject <ClassifierList>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbGET,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("natural_language_classifier", "V1", "ListClassifiers"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }


            req.OnResponse = OnListClassifiersResponse;

            Connector.URL = GetServiceUrl() + "/v1/classifiers";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
 public void Setup()
 {
     var authenticator = new Authenticator();
     authenticator.Authenticate("test");
     var serviceProvider = new GoogleDriveServiceProvider(authenticator);
     this.testee = new FolderSynchronizer(new FilesGetter(serviceProvider), new FileDownloader(serviceProvider));
 }
 public void Setup()
 {
     var driveAuthenticator = new Authenticator();
     driveAuthenticator.Authenticate("test");
     this.googleDriveServiceProvider = new GoogleDriveServiceProvider(driveAuthenticator);
     this.testee = new FileDownloader(this.googleDriveServiceProvider);
 }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            Authenticator auth = Authenticator.Instance;

            auth.Authenticate(authUrl, clientId, clientSecret);

            //Get endpoints by provider
            foreach (Endpoint e in auth.GetEndpoints(providerId))
            {
                XPress xPress = new XPress(e.href);

                //Staff
                //xPress.CreateXStaffUsers(SCHOOL_REFID);
                //xPress.DeleteXStaffUsers(SCHOOL_REFID);
                //xPress.DeleteXStaffUsernamesPasswords(SCHOOL_REFID);
                //XStaffs_GetXStaffsAccounts(xPress);

                //Student
                //xPress.CreateXStudentUsers(SCHOOL_REFID);
                //xPress.DeleteXStudentUsers(SCHOOL_REFID);
                //xPress.DeleteXStudentUsernamesPasswords(SCHOOL_REFID);
                //XStudents_GetXStudentsAccounts(xPress);

                Console.Read();
            }
        }
 protected virtual void AuthenticateIfNeeded(IRestRequest request)
 {
     if (Authenticator != null)
     {
         Authenticator.Authenticate(request);
     }
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Analyze customer-engagement tone.
        ///
        /// Use the customer-engagement endpoint to analyze the tone of customer service and customer support
        /// conversations. For each utterance of a conversation, the method reports the most prevalent subset of the
        /// following seven tones: sad, frustrated, satisfied, excited, polite, impolite, and sympathetic.
        ///
        /// If you submit more than 50 utterances, the service returns a warning for the overall content and analyzes
        /// only the first 50 utterances. If you submit a single utterance that contains more than 500 characters, the
        /// service returns an error for that utterance and does not analyze the utterance. The request fails if all
        /// utterances have more than 500 characters. Per the JSON specification, the default character encoding for
        /// JSON content is effectively always UTF-8.
        ///
        /// **See also:** [Using the customer-engagement
        /// endpoint](https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utco#utco).
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="utterances">An array of `Utterance` objects that provides the input content that the service is
        /// to analyze.</param>
        /// <param name="contentLanguage">The language of the input text for the request: English or French. Regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input
        /// content must match the specified language. Do not submit content that contains both languages. You can use
        /// different languages for **Content-Language** and **Accept-Language**.
        /// * **`2017-09-21`:** Accepts `en` or `fr`.
        /// * **`2016-05-19`:** Accepts only `en`. (optional, default to en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use
        /// different languages for **Content-Language** and **Accept-Language**. (optional, default to en)</param>
        /// <returns><see cref="UtteranceAnalyses" />UtteranceAnalyses</returns>
        public bool ToneChat(Callback <UtteranceAnalyses> callback, List <Utterance> utterances, string contentLanguage = null, string acceptLanguage = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ToneChat`");
            }
            if (utterances == null)
            {
                throw new ArgumentNullException("`utterances` is required for `ToneChat`");
            }

            RequestObject <UtteranceAnalyses> req = new RequestObject <UtteranceAnalyses>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("tone_analyzer", "V3", "ToneChat"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"]   = VersionDate;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";

            if (!string.IsNullOrEmpty(contentLanguage))
            {
                req.Headers["Content-Language"] = contentLanguage;
            }

            if (!string.IsNullOrEmpty(acceptLanguage))
            {
                req.Headers["Accept-Language"] = acceptLanguage;
            }

            JObject bodyObject = new JObject();

            if (utterances != null && utterances.Count > 0)
            {
                bodyObject["utterances"] = JToken.FromObject(utterances);
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));

            req.OnResponse = OnToneChatResponse;

            Connector.URL = GetServiceUrl() + "/v3/tone_chat";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
Ejemplo n.º 14
0
        public ActionResult Login(string username, string password, string captcha)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                return(View("Index"));
            }

            ViewBag.Username = username;

            // check possible brute-force attacks
            int failedtries = 1;

            if (HttpContext.Session.GetInt32(FAILED_ATTEMPTS).HasValue)
            {
                failedtries = HttpContext.Session.GetInt32(FAILED_ATTEMPTS).Value;
            }
            else
            {
                HttpContext.Session.SetInt32(FAILED_ATTEMPTS, 0);
            }

            if (failedtries >= 2)
            {
                if (Authenticator.CheckCaptcha(captcha))
                {
                    if (Authenticator.Authenticate(username, password))
                    {
                        HttpContext.Session.SetInt32(FAILED_ATTEMPTS, 0);
                        return(View("Success"));
                    }
                    else
                    {
                        ViewBag.ShowCaptcha = true;
                        ViewBag.Result      = "Username or password is wrong, please enter again!";
                    }
                }
                else
                {
                    ViewBag.ShowCaptcha = true;
                    ViewBag.Result      = "Please enter correct CAPTCHA!";
                }
            }
            else
            {
                if (Authenticator.Authenticate(username, password))
                {
                    HttpContext.Session.SetInt32(FAILED_ATTEMPTS, 0);
                    return(View("Success"));
                }
                else
                {
                    failedtries = HttpContext.Session.GetInt32(FAILED_ATTEMPTS).Value;
                    HttpContext.Session.SetInt32(FAILED_ATTEMPTS, ++failedtries);
                    ViewBag.Result = "Username or password is wrong, please enter again!";
                }
            }

            return(View("Index"));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Update a classifier.
        ///
        /// Update a custom classifier by adding new positive or negative classes or by adding new images to existing
        /// classes. You must supply at least one set of positive or negative examples. For details, see [Updating
        /// custom
        /// classifiers](https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-customizing#updating-custom-classifiers).
        ///
        /// Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier
        /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters.
        ///
        /// **Tips about retraining:**
        ///
        /// - You can't update the classifier if the **X-Watson-Learning-Opt-Out** header parameter was set to `true`
        /// when the classifier was created. Training images are not stored in that case. Instead, create another
        /// classifier. For more information, see [Data collection](#data-collection).
        ///
        /// - Don't make retraining calls on a classifier until the status is ready. When you submit retraining requests
        /// in parallel, the last request overwrites the previous requests. The `retrained` property shows the last time
        /// the classifier retraining finished.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="classifierId">The ID of the classifier.</param>
        /// <param name="positiveExamples">A dictionary that contains the value for each classname. The value is a .zip
        /// file of images that depict the visual subject of a class in the classifier. The positive examples create or
        /// update classes in the classifier. You can include more than one positive example file in a call.
        ///
        /// Specify the parameter name by appending `_positive_examples` to the class name. For example,
        /// `goldenretriever_positive_examples` creates the class `goldenretriever`. The string cannot contain the
        /// following characters: ``$ * - { } \ | / ' " ` [ ]``.
        ///
        /// Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels.
        /// The maximum number of images is 10,000 images or 100 MB per .zip file.
        ///
        /// Encode special characters in the file name in UTF-8. (optional)</param>
        /// <param name="negativeExamples">A .zip file of images that do not depict the visual subject of any of the
        /// classes of the new classifier. Must contain a minimum of 10 images.
        ///
        /// Encode special characters in the file name in UTF-8. (optional)</param>
        /// <param name="negativeExamplesFilename">The filename for negativeExamples. (optional)</param>
        /// <returns><see cref="Classifier" />Classifier</returns>
        public bool UpdateClassifier(Callback <Classifier> callback, string classifierId, Dictionary <string, System.IO.MemoryStream> positiveExamples = null, System.IO.MemoryStream negativeExamples = null, string negativeExamplesFilename = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `UpdateClassifier`");
            }
            if (string.IsNullOrEmpty(Version))
            {
                throw new ArgumentNullException("`Version` is required");
            }
            if (string.IsNullOrEmpty(classifierId))
            {
                throw new ArgumentNullException("`classifierId` is required for `UpdateClassifier`");
            }

            RequestObject <Classifier> req = new RequestObject <Classifier>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "UpdateClassifier"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (positiveExamples != null && positiveExamples.Count > 0)
            {
                foreach (KeyValuePair <string, System.IO.MemoryStream> entry in positiveExamples)
                {
                    var partName = string.Format("{0}_positive_examples", entry.Key);
                    req.Forms[partName] = new RESTConnector.Form(entry.Value, entry.Key + ".zip", "application/octet-stream");
                }
            }
            if (negativeExamples != null)
            {
                req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamples, negativeExamplesFilename, "application/octet-stream");
            }
            if (!string.IsNullOrEmpty(Version))
            {
                req.Parameters["version"] = Version;
            }

            req.OnResponse = OnUpdateClassifierResponse;

            Connector.URL = GetServiceUrl() + string.Format("/v3/classifiers/{0}", classifierId);
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
Ejemplo n.º 16
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
            [StorageAccount("StorageConnectionString")] CloudStorageAccount storageAccount,
            TraceWriter log
            )
        {
            var    client       = storageAccount.CreateCloudTableClient();
            string partitionKey = await Authenticator.Authenticate(client, req);

            if (string.IsNullOrEmpty(partitionKey))
            {
                return(new UnauthorizedResult());
            }

            string json = await req.ReadAsStringAsync();

            var items = JsonConvert.DeserializeObject <List <ItemJson> >(json);

            if (items == null)
            {
                return(new BadRequestObjectResult("Could not correctly parse the request parameters"));
            }
            else if (items.Count > 100)
            {
                return(new BadRequestObjectResult("Too many items to store, maximum 100 per call"));
            }
            else if (items.Count <= 0)
            {
                return(new BadRequestObjectResult("No items to store"));
            }

            var partition = await PartionUtility.GetUploadPartitionV2(log, client, partitionKey);

            log.Info($"Received a request from {partitionKey} to upload {items.Count} items to {partition.RowKey}");

            var itemTable = client.GetTableReference(ItemV2.TableName);
            await itemTable.CreateIfNotExistsAsync();

            var itemMapping = await Insert(partitionKey, partition.RowKey, itemTable, items);

            log.Info($"Inserted {items.Count} items over {itemMapping.Count} batches");

            bool shouldClosePartition = items.Count >= 90;

            if (shouldClosePartition)
            {
                log.Info($"Closing partition {partition.PartitionKey}, due to received count at {items.Count}");
                partition.IsActive = false;
                await client.GetTableReference(PartitionV2.TableName).ExecuteAsync(TableOperation.Replace(partition));
            }

            var result = new UploadResultDto {
                Partition = itemMapping.First().Partition,
                IsClosed  = shouldClosePartition,
                Items     = itemMapping
            };

            return(new OkObjectResult(result));
        }
Ejemplo n.º 17
0
        public ValidationResult Validate(HttpRequest req)
        {
            var result = _auth.Authenticate(new JwtBearerToken(req).Token);

            return(result.Item1 == Token.Verified
                ? ValidationResult.Valid
                : new ValidationResult(result.Item1.ToString()));
        }
Ejemplo n.º 18
0
        public void Test_AuthenticateReturnsNoUserWhenEmptyListOfUsers()
        {
            Authenticator authenticator = new Authenticator(new List <User>());

            User authenticatedUser = authenticator.Authenticate("test", "test");

            Assert.Null(authenticatedUser);
        }
Ejemplo n.º 19
0
        public void Setup()
        {
            var driveAuthenticator = new Authenticator();

            driveAuthenticator.Authenticate("test");
            this.googleDriveServiceProvider = new GoogleDriveServiceProvider(driveAuthenticator);
            this.testee = new FileDownloader(this.googleDriveServiceProvider);
        }
Ejemplo n.º 20
0
        public void Authenticate_ExistingUser_UserHasAuthenticated()
        {
            var    ar     = new Authenticator(new StubService());
            string result = ar.Authenticate("User1", "p1");

            Assert.IsNotNullOrEmpty(result, "Empty string response after authentication method.");
            Console.WriteLine(result);
        }
Ejemplo n.º 21
0
        private RestRequest CreateRequest(Method method)
        {
            Authenticator.Authenticate();
            RestRequest request = new RestRequest(method);

            request.AddHeader("Authorization", "Bearer " + AccessToken);
            return(request);
        }
Ejemplo n.º 22
0
        public void Test_SearchingForAUserNotInTheListReturnsNull()
        {
            Authenticator authenticator = new Authenticator(new List <User>());

            User result = authenticator.Authenticate("Test", "Test");

            Assert.IsNull(result);
        }
Ejemplo n.º 23
0
        public void Test_AuthenticateUserNotFound()
        {
            var users         = createUsersList();
            var authenticator = new Authenticator(users);

            var user = authenticator.Authenticate("Sara", "password");

            Assert.Null(user);
        }
Ejemplo n.º 24
0
        public void Test_AuthenticateInvalidPassword()
        {
            var users         = createUsersList();
            var authenticator = new Authenticator(users);

            var user = authenticator.Authenticate("Jane", "password");

            Assert.Null(user);
        }
Ejemplo n.º 25
0
        public void Test_AuthenticateNullUsername()
        {
            var users         = createUsersList();
            var authenticator = new Authenticator(users);

            var user = authenticator.Authenticate(null, "password");

            Assert.Null(user);
        }
Ejemplo n.º 26
0
        public void Setup()
        {
            var authenticator = new Authenticator();

            authenticator.Authenticate("test");
            var serviceProvider = new GoogleDriveServiceProvider(authenticator);

            this.testee = new FolderSynchronizer(new FilesGetter(serviceProvider), new FileDownloader(serviceProvider));
        }
        public void Test_AuthenticateWithEmptyUserList()
        {
            List <User>   users         = new List <User>();
            Authenticator authenticator = new Authenticator(users);

            User authenticatedUser = authenticator.Authenticate("User Test", "");

            Assert.AreNotEqual(authenticatedUser, "User Test", "");
        }
        public void Test_AuthenticateNullUser()
        {
            User          user          = createTestUser("Test User", "", 100);
            Authenticator authenticator = CreateAuthenticator(user);

            User authenticatedUser = authenticator.Authenticate(null, null);

            Assert.AreNotEqual(authenticatedUser, user);
        }
        public void Test_AuthenticateEmptyStringUser()
        {
            User          user          = createTestUser("Test User", "", 100);
            Authenticator authenticator = CreateAuthenticator(user);

            User authenticatedUser = authenticator.Authenticate("", "");

            Assert.AreNotEqual(authenticatedUser, user);
        }
        public void Test_AuthenticateUserThatDoesNotExist()
        {
            User          user          = createTestUser("Test User", "", 100);
            Authenticator authenticator = CreateAuthenticator(user);

            User authenticatedUser = authenticator.Authenticate("User", "");

            Assert.AreNotEqual(authenticatedUser, user);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Send user input to assistant (stateful).
        ///
        /// Send user input to an assistant and receive a response, with conversation state (including context data)
        /// stored by Watson Assistant for the duration of the session.
        ///
        /// There is no rate limit for this operation.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="assistantId">Unique identifier of the assistant. To find the assistant ID in the Watson
        /// Assistant user interface, open the assistant settings and click **API Details**. For information about
        /// creating assistants, see the
        /// [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-add#assistant-add-task).
        ///
        /// **Note:** Currently, the v2 API does not support creating assistants.</param>
        /// <param name="sessionId">Unique identifier of the session.</param>
        /// <param name="input">An input object that includes the input text. (optional)</param>
        /// <param name="context">Context data for the conversation. You can use this property to set or modify context
        /// variables, which can also be accessed by dialog nodes. The context is stored by the assistant on a
        /// per-session basis.
        ///
        /// **Note:** The total size of the context data stored for a stateful session cannot exceed 100KB.
        /// (optional)</param>
        /// <returns><see cref="MessageResponse" />MessageResponse</returns>
        public bool Message(Callback <MessageResponse> callback, string assistantId, string sessionId, MessageInput input = null, MessageContext context = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Message`");
            }
            if (string.IsNullOrEmpty(assistantId))
            {
                throw new ArgumentNullException("`assistantId` is required for `Message`");
            }
            if (string.IsNullOrEmpty(sessionId))
            {
                throw new ArgumentNullException("`sessionId` is required for `Message`");
            }

            RequestObject <MessageResponse> req = new RequestObject <MessageResponse>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("conversation", "V2", "Message"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"]   = VersionDate;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";

            JObject bodyObject = new JObject();

            if (input != null)
            {
                bodyObject["input"] = JToken.FromObject(input);
            }
            if (context != null)
            {
                bodyObject["context"] = JToken.FromObject(context);
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));

            req.OnResponse = OnMessageResponse;

            Connector.URL = GetServiceUrl() + string.Format("/v2/assistants/{0}/sessions/{1}/message", assistantId, sessionId);
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Classify images.
        ///
        /// Classify images with built-in or custom classifiers.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="imagesFile">An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size
        /// is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file
        /// names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters
        /// non-ASCII characters.
        ///
        /// You can also include an image with the **url** parameter. (optional)</param>
        /// <param name="imagesFilename">The filename for imagesFile. (optional)</param>
        /// <param name="imagesFileContentType">The content type of imagesFile. (optional)</param>
        /// <param name="url">The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel
        /// density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224
        /// pixels. The maximum image size is 10 MB.
        ///
        /// You can also include images with the **images_file** parameter. (optional)</param>
        /// <param name="threshold">The minimum score a class must have to be displayed in the response. Set the
        /// threshold to `0.0` to return all identified classes. (optional)</param>
        /// <param name="owners">The categories of classifiers to apply. The **classifier_ids** parameter overrides
        /// **owners**, so make sure that **classifier_ids** is empty.
        /// - Use `IBM` to classify against the `default` general classifier. You get the same result if both
        /// **classifier_ids** and **owners** parameters are empty.
        /// - Use `me` to classify against all your custom classifiers. However, for better performance use
        /// **classifier_ids** to specify the specific custom classifiers to apply.
        /// - Use both `IBM` and `me` to analyze the image against both classifier categories. (optional)</param>
        /// <param name="classifierIds">Which classifiers to apply. Overrides the **owners** parameter. You can specify
        /// both custom and built-in classifier IDs. The built-in `default` classifier is used if both
        /// **classifier_ids** and **owners** parameters are empty.
        ///
        /// The following built-in classifier IDs require no training:
        /// - `default`: Returns classes from thousands of general tags.
        /// - `food`: Enhances specificity and accuracy for images of food items.
        /// - `explicit`: Evaluates whether the image might be pornographic. (optional)</param>
        /// <param name="acceptLanguage">The desired language of parts of the response. See the response for details.
        /// (optional, default to en)</param>
        /// <returns><see cref="ClassifiedImages" />ClassifiedImages</returns>
        public bool Classify(Callback <ClassifiedImages> callback, System.IO.MemoryStream imagesFile = null, string imagesFilename = null, string imagesFileContentType = null, string url = null, float?threshold = null, List <string> owners = null, List <string> classifierIds = null, string acceptLanguage = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Classify`");
            }

            RequestObject <ClassifiedImages> req = new RequestObject <ClassifiedImages>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "Classify"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (imagesFile != null)
            {
                req.Forms["images_file"] = new RESTConnector.Form(imagesFile, imagesFilename, imagesFileContentType);
            }
            if (!string.IsNullOrEmpty(url))
            {
                req.Forms["url"] = new RESTConnector.Form(url);
            }
            if (threshold != null)
            {
                req.Forms["threshold"] = new RESTConnector.Form(threshold.ToString());
            }
            if (owners != null && owners.Count > 0)
            {
                req.Forms["owners"] = new RESTConnector.Form(string.Join(", ", owners.ToArray()));
            }
            if (classifierIds != null && classifierIds.Count > 0)
            {
                req.Forms["classifier_ids"] = new RESTConnector.Form(string.Join(", ", classifierIds.ToArray()));
            }

            req.OnResponse = OnClassifyResponse;

            Connector.URL = GetServiceUrl() + "/v3/classify";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
Ejemplo n.º 33
0
        public async Task Authenticate_WhereDownstreamResultEmpty_ReturnsFalse()
        {
            // arrange
            var proxy = new AuthenticatorProxyWithResult("");
            authenticator = new Authenticator(proxy);

            // act
            var result = await authenticator.Authenticate("url");

            Assert.IsFalse(result.IsSuccess);
        }
Ejemplo n.º 34
0
        public async Task Authenticate_WhereDownstreamResultOccurs_ReturnsSuccess()
        {
            // arrange
            var proxy = new AuthenticatorProxyWithResult("foo");
            authenticator = new Authenticator(proxy);

            // act
            var result = await authenticator.Authenticate("url");

            Assert.IsTrue(result.IsSuccess);
        }
        public void Synchronize_WhenFolderIsSynchronize_ThenStructureIsCorrect()
        {
            // Arrange
            var authenticator = new Authenticator();
            authenticator.Authenticate("test");
            var filesGetter = new FilesGetter(new GoogleDriveServiceProvider(authenticator));
            var files = filesGetter.GetDriveFiles(GoogleDriveConstants.FolderMimeType).ToList();

            // Act
            string rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\TestGoogle";
            this.testee.SynchronizeFolder(
                files[1],
                rootFolder);

            // Assert
            Directory.Exists(rootFolder).Should().BeTrue();
            Directory.GetDirectories(rootFolder).Length.Should().Be(1);
        }
 public void Setup()
 {
     Authenticator driveAuthenticator = new Authenticator();
     driveAuthenticator.Authenticate("test");
     this.testee = new FilesGetter(new GoogleDriveServiceProvider(driveAuthenticator));
 }
Ejemplo n.º 37
0
        public async Task Authenticate_WhereDownstreamResultOccurs_ReturnsToken()
        {
            // arrange
            var proxy = new AuthenticatorProxyWithResult("foo");
            authenticator = new Authenticator(proxy);

            // act
            var result = await authenticator.Authenticate("url");

            Assert.AreEqual("foo", result.AccessToken);
        }
Ejemplo n.º 38
0
		protected override void InnerRun()
		{
            Succeeded = false;
            PendingUserActivation = true;
		    ShouldRetry = true;

            DoxApi api = new DoxApi(_serviceUrl);
		    IDoxSession session = null;

		    if (!string.IsNullOrEmpty(DeviceToken))
		    {
		        session = api.CreateSessionFromDeviceToken(_loginName, DeviceToken, ApiHelper);
                if (session == null && api.Error.IsConnectionError())
                {
                    PendingUserActivation = false;
                    ErrorMessage = Properties.Resources.ConnectionErrorDuringUpload;
                    return;
                }
		    }

		    if (session == null)
		    {
                // show login dialog
                var nativeWindow = new NativeWindow();
                nativeWindow.AssignHandle(IntPtr.Zero);
                _loginUi.NativeWindow = nativeWindow;
                _loginUi.RegisterTabVisible = false;
                _loginUi.LoginFieldEnabled = false;

		        var authenticator = new Authenticator(_loginUi);
                authenticator.Api = api;
		        authenticator.ApiHelper = ApiHelper;
		        bool cancelSend;
                session = authenticator.Authenticate(_loginName, null, out cancelSend);
                if (cancelSend)
                {
                    ShouldRetry = false;
                    PendingUserActivation = false;
                    Logger.LogInfo("User cancelled send");
                    ErrorMessage = "Unable to log in.";
                    return;
                }
		    }

		    if (session == null)
		    {
		        return; // something weird is happening, try again later
		    }

		    DeviceToken = session.Credentials.DeviceToken;
            OptionApi.SetEncrypted("SendLinkDeviceToken", DeviceToken, _entropy);
            OptionApi.SetEncrypted("SendLinkAccountId", session.CurrentUser.AccountId, _entropy);
            OptionApi.SetEncrypted("SendLinkUserId", session.CurrentUser.Id, _entropy);

		    if (session.CurrentUser.IsValidated)
		    {
		        PendingUserActivation = false;
                Succeeded = true;
                ErrorMessage = string.Empty;
		    }
		}