// Use this for initialization
    IEnumerator Start()
    {
        APIKeys keys = JsonUtility.FromJson <APIKeys>(json.text);

        ConsumerKey    = keys.consumer_key;
        ConsumerSecret = keys.consumer_secret;

        using (UnityWebRequest www = ObtainBearerToken(EncodeKeyAndSecret(ConsumerKey, ConsumerSecret)))
        {
            yield return(www.SendWebRequest());

            if (www.error != null)
            {
                Debug.LogError("There was an error sending request: " + www.error);
                Debug.LogError(www.downloadHandler.text);
            }
            else
            {
                var response = JsonUtility.FromJson <AuthResponse>(www.downloadHandler.text);
                if (response.token_type != "bearer")
                {
                    throw new Exception("Unexpected token type: " + response.token_type);
                }
                else
                {
                    authenticationToken = response.access_token;
                }
            }
        }
    }
Exemple #2
0
    private APIKeys GetAPIKeys()
    {
        APIKeys keys = new APIKeys();

#if USING_KEY_FILE
        string keyFile;
        using (StreamReader sr = new StreamReader("key"))
        {
            keyFile = sr.ReadToEnd();
        }
        string[] keyRows = keyFile.Split('\n');

        /* The keys file needs to be exactly two rows, on the first the App ID
         * and on the second row the App Key provided by Yle */
        if (keyRows.Length == 2)
        {
            keys.AppID  = keyRows[0].Trim(); // Remember to trim Windows's \r 😬
            keys.AppKey = keyRows[1].Trim();
            Debug.LogFormat("<color=#060>API Keys read OK</color>\nApp ID: [{0}] App Key: [{1}]", keys.AppID, keys.AppKey);
        }
        else
        {
            string error = string.Format("Problem with reading the API keys. Please check or create the keys file in project root.\n(Rows from file: {0})", keyRows.Length);
            Debug.LogError(error);
            ResultsDisplay.Instance.DisplayError(error);
        }
#else
        if (Authentication != null)
        {
            keys = Authentication.Keys;
        }
#endif
        return(keys);
    }
Exemple #3
0
 /// <summary>
 /// The constructor for the MainPage UI
 /// </summary>
 public MainPage()
 {
     this.InitializeComponent();
     db   = new PopLibraryDataManager("PopLibrary.db");
     keys = JsonConvert.DeserializeObject <APIKeys>(ReadConfigFile().Result);
     submitButton.KeyUp += SubmitButton_KeyUp;
     SetupBookList();
 }
Exemple #4
0
    private string GetSearchString(string query)
    {
        string  searchURL = "";
        APIKeys keys      = GetAPIKeys();

        searchURL = string.Format("{0}?app_id={1}&app_key={2}&limit={3}&offset={4}&q={5}", _baseURL, keys.AppID, keys.AppKey, _limit, _offset, UnityWebRequest.EscapeURL(query));
        Debug.Log("URL: " + searchURL);
        return(searchURL);
    }
Exemple #5
0
        public static async Task <bool> RefreshAuthorizationTokenIfRequired()
        {
            long lastSetTime = ApplicationSetting.GetLocalSetting_Long("google_token_expiresTime", 0);

            if (lastSetTime != 0)
            {
                long now = DateTime.Now.Ticks / TimeSpan.TicksPerSecond;
                if (now > lastSetTime)
                {
                    // expired
                    string FetchURL = "https://accounts.google.com/o/oauth2/token";

                    var handler = new HttpClientHandler();
                    var req     = new HttpClient(handler);


                    Tuple <string, string> keypair = APIKeys.GetRandomizedClientSecretAndIDPair();
                    string pdata = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token",
                                                 keypair.Item1,
                                                 keypair.Item2,
                                                 await ApplicationSetting.GetEncryptedLocalStringValueOrDefault("google_refresh_token", ""));
                    StringContent strc = new StringContent(pdata, Encoding.UTF8, "application/x-www-form-urlencoded");
                    try
                    {
                        HttpResponseMessage data = await req.PostAsync(FetchURL, strc);

                        HttpContent content = data.Content;
                        data.EnsureSuccessStatusCode();

                        // {"access_token":"1/fFAGRNJru1FTz70BzhT3Zg","expires_in":3920,"token_type":"Bearer"}
                        JObject token = JObject.Parse(await content.ReadAsStringAsync());

                        /*   string access_token = (string) token["access_token"];
                         * string token_type = (string)token["token_type"];
                         * int expires_in = (int)token["expires_in"];
                         * string refresh_token = (string)token["refresh_token"];
                         *
                         * Debug.WriteLine(ReturnData);*/
                        await ApplicationSetting.SetUpdateLocalValueEncrypted("google_access_token", (string)token["access_token"]);

                        ApplicationSetting.SetLocalSetting("google_token_expiresTime", (long)now + (((long)token["expires_in"] - 5L) * 60L));

                        return(true);
                    }
                    catch (Exception eex)
                    {
                        Debug.WriteLine(eex.ToString());
                    }
                    return(false);
                }
                else
                {
                    // not expired, do nothing.
                }
            }
            return(true);
        }
        public ActionResult MappAddress(int?id)
        {
            Customer customer = db.Customers.Where(c => c.ID == id).FirstOrDefault();

            customer.Address = db.Addresses.Where(c => c.ID == customer.AddressID).FirstOrDefault();
            APIKeys aPIKeys = new APIKeys();

            customer.key = aPIKeys.api;

            return(View("MappAddress", customer));
        }
Exemple #7
0
 /// <summary>
 ///     Create a client that connects to the SendGrid Web API
 /// </summary>
 /// <param name="apiKey">Your SendGrid API Key</param>
 /// <param name="baseUri">Base SendGrid API Uri</param>
 public Client(string apiKey, string baseUri = "https://api.sendgrid.com/")
 {
     _baseUri           = new Uri(baseUri);
     _apiKey            = apiKey;
     Version            = "Josh";//Assembly.GetExecutingAssembly().GetName().Version.ToString();
     ApiKeys            = new APIKeys(this);
     UnsubscribeGroups  = new UnsubscribeGroups(this);
     Suppressions       = new Suppressions(this);
     GlobalSuppressions = new GlobalSuppressions(this);
     GlobalStats        = new GlobalStats(this);
 }
Exemple #8
0
 private void Initialize()
 {
     Version            = Assembly.GetExecutingAssembly().GetName().Version.ToString();
     ApiKeys            = new APIKeys(this);
     UnsubscribeGroups  = new UnsubscribeGroups(this);
     Suppressions       = new Suppressions(this);
     GlobalSuppressions = new GlobalSuppressions(this);
     GlobalStats        = new GlobalStats(this);
     Templates          = new Templates(this);
     Versions           = new Versions(this);
     Batches            = new Batches(this);
 }
        private UserConfig(UserConfig src)
        {
            foreach (var kvp in src.APIKeys)
            {
                var temp = new APIKey();

                temp.Initialize(kvp.Value.Protection !);
                temp.Value = kvp.Value.Value;

                APIKeys.Add(kvp.Key, temp);
            }
        }
Exemple #10
0
        public static async Task <Object> RequestedAuthenticatedAPICall(string url, Type type)
        {
            // Authenticated parameters\
            string apiKey      = APIKeys.GetLoginAPIKey();
            string accessToken = await ApplicationSetting.GetEncryptedLocalStringValueOrDefault("google_access_token", null);

            if (apiKey == null || accessToken == null)
            {
                return(null);
            }
            // Refresh auth key if required
            if (!await YoutubeService.RefreshAuthorizationTokenIfRequired())
            {
                return(null);
            }

            // HTTP
            var handler = new HttpClientHandler();
            var req     = new HttpClient(handler);

            req.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

            string FetchURL = string.Format("{0}&key={1}", url, apiKey);

            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            try
            {
                HttpResponseMessage data = await req.GetAsync(FetchURL);

                HttpContent content = data.Content;
                data.EnsureSuccessStatusCode();

                string ReturnData = await content.ReadAsStringAsync();

                // Debug.WriteLine(ReturnData);

                if (ReturnData == null)
                {
                    return(null);
                }

                Object obj = JsonConvert.DeserializeObject(ReturnData, type);

                return(obj);
            }
            catch (Exception eex)
            {
                Debug.WriteLine(eex.ToString());
            }
            return(null);
        }
        public static void TwilioMessage(string phoneNumber, string messageText)
        {
            string accountSid = APIKeys.GetAccountSid();
            string authToken  = APIKeys.GetAuthToken();

            TwilioClient.Init(accountSid, authToken);

            var message = MessageResource.Create(
                body: messageText,
                from: new Twilio.Types.PhoneNumber("+19206266861"),
                to: new Twilio.Types.PhoneNumber("+" + phoneNumber)
                );
        }
Exemple #12
0
        public void RestoreFrom(UserConfig src)
        {
            APIKeys.Clear();

            foreach (var kvp in src.APIKeys)
            {
                var temp = new APIKey();

                temp.Initialize(kvp.Value.Protection !);
                temp.Value = kvp.Value.Value;

                APIKeys.Add(kvp.Key, temp);
            }
        }
        public static bool IsValidAPIKey(string key)
        {
            // TODO: Implement IsValidAPI Key using your repository

            Guid apiKey;

            // Convert the string into a Guid and validate it
            if (Guid.TryParse(key, out apiKey) && APIKeys.Contains(apiKey))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private void LoginPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsLoaded)
            {
                return;
            }
            IsLoaded = true;


            // https://accounts.google.com/o/oauth2/auth?client_id=519499300992-6d8h9ncnoft7ioldls8qf6vuvo04em4c.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&scope=https://www.googleapis.com/auth/youtube&response_type=code&access_type=offline
            // https://developers.google.com/youtube/v3/guides/auth/installed-apps

            string uri =
                string.Format("https://accounts.google.com/o/oauth2/auth?client_id={0}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.force-ssl%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.upload%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutubepartner&response_type=code&access_type=offline",
                              APIKeys.GetRandomizedYouTubeClientId());

            // await Launcher.LaunchUriAsync(new Uri(uri, UriKind.Absolute));
            this.WebView1.Navigate(new Uri(uri));
        }
Exemple #15
0
        public static async Task <JObject> ExchangeAuthorizationToken(string authorizationToken)
        {
            string FetchURL = "https://accounts.google.com/o/oauth2/token";

            var handler = new HttpClientHandler();
            var req     = new HttpClient(handler);


            Tuple <string, string> keypair = APIKeys.GetRandomizedClientSecretAndIDPair();
            string pdata = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code",
                                         authorizationToken,
                                         keypair.Item1,
                                         keypair.Item2);
            StringContent strc = new StringContent(pdata, Encoding.UTF8, "application/x-www-form-urlencoded");

            try
            {
                HttpResponseMessage data = await req.PostAsync(FetchURL, strc);

                HttpContent content = data.Content;
                data.EnsureSuccessStatusCode();

                string ReturnData = await content.ReadAsStringAsync();

                // "{\n  \"access_token\" : \"ya29.7gEujvKt67YIpX4sWE_vJMAHwcvEU7ZYdYUPDo56iNhSgSZnGVUiohJU-imIoEHyzl5T\",\n  \"token_type\" : \"Bearer\",\n  \"expires_in\" : 3600,\n  \"refresh_token\" : \"1/nelJL_l2PzLMdr9E6-Kg3g7tHFlaXv6jVf1HxjwUOKM\"\n}"
                JObject token = JObject.Parse(ReturnData);

                /*   string access_token = (string) token["access_token"];
                 * string token_type = (string)token["token_type"];
                 * int expires_in = (int)token["expires_in"];
                 * string refresh_token = (string)token["refresh_token"];
                 *
                 * Debug.WriteLine(ReturnData);*/

                return(token);
            }
            catch (Exception eex)
            {
                Debug.WriteLine(eex.ToString());
            }
            return(null);
        }
Exemple #16
0
        public void SendText(string PhoneNumber, string TextBody)
        {
            //APIKeys class instantiated

            APIKeys aPIKeys = new APIKeys();

            //Twilio library
            //Twilio.TwilioClient is the packge in .net which is responsbile for talking to all the twilio apis.
            Twilio.TwilioClient.SetUsername("TLaw92");

            //TwilioClient.Init() is the function which actually kicks start your twilioclient library to call differnt mehtods in that.
            TwilioClient.Init(APIKeys.TWILIO_API_SID, APIKeys.TWILIO_API_AUTH);

            //mesage resouurce is class in TwilioClient is to send and receieve messages to and from your application
            // with the power of Twilio.
            var message = MessageResource.Create(
                body: TextBody,                                     ///body key of message object where all the body of message is present.
                from: new Twilio.Types.PhoneNumber("+14049943666"), //Your Twilio Number, where the message will be sent.
                to: new Twilio.Types.PhoneNumber(PhoneNumber)       //The number to which the message will be sent.
                );
        }
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            if (!CameraList.HasItems)
            {
                MessageArea.Text = "No cameras found; cannot start processing";
                return;
            }

            // Create API clients.
            fsc = new FaceServiceClient(APIKeys.GetSubscriptionKey(), APIKeys.GetAPIURL());

            // How often to analyze.
            _grabber.TriggerAnalysisOnInterval(TimeSpan.FromSeconds(5));

            // Reset message.
            MessageArea.Text = "";

            // Record start time, for auto-stop
            _startTime = DateTime.Now;

            personGroupID = APIKeys.getPersonGroupID();

            await _grabber.StartProcessingCameraAsync(CameraList.SelectedIndex);
        }
 /// <summary>
 /// Checks that the given API-key is valid.
 /// </summary>
 /// <param name="context">The current service context</param>
 /// <returns>Whether the api key is valid or not.</returns>
 protected override bool CheckAccessCore(OperationContext context)
 {
     return(APIKeys.IsValidKey(GetAPIKey(context)));
 }
 /// <summary>
 /// Determines whether the specified user has at least one API key.
 /// </summary>
 public bool HasAPIKeys(ClaimsPrincipal claims) => APIKeys.Count(x => x.UserEmail == claims.Identity.Name) > 0;