public async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            counter++;
            var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}";

            switch (Mode)
            {
            case MockMode.Record:
                //Add following code since the request.Content will be released after sendAsync
                var requestClone = request;
                if (requestClone.Content != null)
                {
                    requestClone = await request.CloneWithContent(request.RequestUri, request.Method);
                }
                // make the call
                var response = await next.SendAsync(request, callback);

                // save the message to the recording file
                SaveMessage(rqkey, requestClone, response);

                // return the response.
                return(response);

            case MockMode.Playback:
                // load and return the response.
                return(LoadMessage(rqkey));

            default:
                // pass-thru, do nothing
                return(await next.SendAsync(request, callback));
            }
        }
示例#2
0
        protected async Task <HttpResponseMessage> CustomError(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            System.Net.Http.HttpResponseMessage response = await next.SendAsync(request, callback);

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }
            else
            {
                var ResponseContent = await response.Content.ReadAsStringAsync();

                if (response.ReasonPhrase == "Unauthorized")
                {
                    System.Environment.SetEnvironmentVariable("JCApiKey", "");
                    System.Environment.SetEnvironmentVariable("JCOrgId", "");
                }
                throw new Exception(
                          "JumpCloudApiSdkError:: "
                          + Environment.NewLine
                          + " StatusCode: "
                          + (int)response.StatusCode
                          + " - "
                          + response.ReasonPhrase
                          + Environment.NewLine
                          + response.RequestMessage
                          + Environment.NewLine
                          + " RequestContent: " + request.Content.ReadAsStringAsync().Result
                          + Environment.NewLine
                          + " ResponseContent: " + ResponseContent
                          );
            }
        }
示例#3
0
        protected async Task <HttpResponseMessage> AddApiKey(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            request.Headers.Add("Authorization", "Token token=" + System.Environment.GetEnvironmentVariable("CifV3ApiKey"));

            // let it go on.
            return(await next.SendAsync(request, callback));
        }
        protected async Task <HttpResponseMessage> AddEntityTokenAuth(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            string titleId            = System.Environment.GetEnvironmentVariable("TitleId");
            string entityToken        = System.Environment.GetEnvironmentVariable("EntityToken");
            string playFabApiHostName = System.Environment.GetEnvironmentVariable("PlayFabApiHostName");
            string pfDebug            = System.Environment.GetEnvironmentVariable("PF_DEBUG");
            bool   shouldOutputDebug  = string.Equals(pfDebug, "true", StringComparison.OrdinalIgnoreCase);

            if (string.IsNullOrEmpty(titleId) || string.IsNullOrEmpty(entityToken) || string.IsNullOrEmpty(playFabApiHostName))
            {
                throw new InvalidOperationException("Missing authentication. Call 'Set-PfTitle' before making this request.");
            }

            // replace the TitleId in the uri
            request.RequestUri = new System.Uri(request.RequestUri.AbsoluteUri.Replace("titleid", titleId));

            // replace the hostname in the uri
            request.RequestUri = new System.Uri(request.RequestUri.AbsoluteUri.Replace("playfabapi.com", playFabApiHostName));

            // add the X-EntityToken header
            request.Headers.Add("X-EntityToken", entityToken);

            // Apparently the body gets disposed after being sent when running in Windows Powershell (but doesn't get
            // disposed in Powershell Core) so we store it now
            string requestContent = await request.Content.ReadAsStringAsync();

            // let the request go on.
            HttpResponseMessage response = await next.SendAsync(request, callback);

            if (shouldOutputDebug || !response.IsSuccessStatusCode)
            {
                Console.ForegroundColor = ConsoleColor.DarkGray;

                Console.Error.WriteLine($"{request.Method} {request.RequestUri}");
                Console.Error.WriteLine();
                foreach (KeyValuePair <string, IEnumerable <string> > header in request.Headers)
                {
                    Console.Error.WriteLine($"{header.Key}: {string.Join(",", header.Value)}");
                }
                Console.Error.WriteLine();
                Console.Error.WriteLine(requestContent);

                Console.Error.WriteLine();
                Console.Error.WriteLine();
                foreach (KeyValuePair <string, IEnumerable <string> > header in response.Headers)
                {
                    Console.Error.WriteLine($"{header.Key}: {string.Join(",", header.Value)}");
                }
                Console.Error.WriteLine();
                Console.Error.WriteLine(await response.Content.ReadAsStringAsync());

                Console.ResetColor();
            }

            return(response);
        }
示例#5
0
        // partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref ModuleNameSpace.Runtime.HttpPipeline pipeline)
        // {
        //     pipeline.Append(Paginate);
        // }
        protected async Task <HttpResponseMessage> AddAuthHeaders(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            // Check to see if the environment variable for JCApiKey is populated
            var JCApiKey = System.Environment.GetEnvironmentVariable("JCApiKey");

            if (JCApiKey == null || JCApiKey == "")
            {
                Console.Write("Please enter your JumpCloud API key: ");
                JCApiKey = Console.ReadLine();
                Console.WriteLine("You entered '{0}'", JCApiKey);
                System.Environment.SetEnvironmentVariable("JCApiKey", JCApiKey);
            }
            // If headers do not contain an "x-api-key" header add one
            if (request.Headers.Contains("x-api-key") == false)
            {
                request.Headers.Add("x-api-key", JCApiKey);
            }
            // Check to see if the environment variable for JCOrgId is populated
            var JCOrgId = System.Environment.GetEnvironmentVariable("JCOrgId");

            if (JCOrgId == null || JCOrgId == "")
            {
                Console.Write("Please enter your JumpCloud organization id: ");
                JCOrgId = Console.ReadLine();
                Console.WriteLine("You entered '{0}'", JCOrgId);
                System.Environment.SetEnvironmentVariable("JCOrgId", JCOrgId);
            }
            // If headers do not contain an "x-org-id" header add one
            if (request.Headers.Contains("x-org-id") == false)
            {
                request.Headers.Add("x-org-id", JCOrgId);
            }
            // Organization endpoint does not accept x-org-id as a header so remove it
            if (request.Headers.Contains("x-org-id") && request.RequestUri.LocalPath.StartsWith("/api/organizations") == true)
            {
                request.Headers.Remove("x-org-id");
            }
            // If headers do not contain an "Accept" header add one
            if (request.Headers.Contains("Accept") == false)
            {
                request.Headers.Add("Accept", "application/json");
            }
            // If headers do not contain an "UserAgent" with the correct value fix it
            if (request.Headers.UserAgent.ToString() != "JumpCloud_JumpCloud.PowerShell.SDK.V1/0.0.27")
            {
                request.Headers.UserAgent.Clear();
                request.Headers.UserAgent.ParseAdd("JumpCloud_JumpCloud.PowerShell.SDK.V1/0.0.27");
            }
            // // request.Headers.Add("Content-Type", "application/json");
            System.Net.Http.HttpResponseMessage response = await next.SendAsync(request, callback);

            return(response);
        }
示例#6
0
        protected async Task <HttpResponseMessage> AddSessionToken(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            // does the request already have an authorization header? remove it
            if (request.Headers.Contains("Authorization"))
            {
                request.Headers.Remove("Authorization");
            }

            // add in the auth header
            request.Headers.Add("Authorization", "Session " + System.Environment.GetEnvironmentVariable("RunwaySessionToken"));

            // let it go on.
            return(await next.SendAsync(request, callback));
        }
示例#7
0
        protected async Task <HttpResponseMessage> AddApiKey(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            var apiKey = System.Environment.GetEnvironmentVariable("OpenHabApiKey");

            if (string.IsNullOrEmpty(apiKey))
            {
                throw new System.Exception("Please set the Environment Variable \"OpenHabApiKey\" with the Key you retrieved from the Web-Interface.");
            }
            var bytes        = System.Text.Encoding.ASCII.GetBytes($"{apiKey}:");
            var base64ApiKey = System.Convert.ToBase64String(bytes);

            request.Headers.Add("Authorization", $"Basic {base64ApiKey}");

            return(await next.SendAsync(request, callback));
        }
示例#8
0
        protected async Task <HttpResponseMessage> AddApiKey(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            // does the request already have a query?
            var sepChar = string.IsNullOrEmpty(request.RequestUri.Query) ? "?" : "&";

            // add on the apikey
            request.RequestUri = new System.Uri(
                request.RequestUri.AbsoluteUri +
                sepChar +
                "apikey=" +
                // we'll cheat and pull it from the environment :D
                System.Environment.GetEnvironmentVariable("TimesApiKey")
                );

            // let it go on.
            return(await next.SendAsync(request, callback));
        }
示例#9
0
        protected async Task <HttpResponseMessage> Debugging(HttpRequestMessage request, IEventListener callback, ISendAsync next)
        {
            System.Net.Http.HttpResponseMessage response = await next.SendAsync(request, callback);

            Console.WriteLine("------------------------------------------------------------------------");
            Console.WriteLine("Request: '{0}'", request);
            Console.WriteLine("------------------------------------------------------------------------");
            Console.WriteLine("RequestBody: '{0}'", request.Content.ReadAsStringAsync().Result);
            Console.WriteLine("------------------------------------------------------------------------");
            // Console.WriteLine("------------------------------------------------------------------------");
            // Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
            // Console.WriteLine("ResponseContent: {0}", ResponseContent);
            // Console.WriteLine("------------------------------------------------------------------------");
            // Console.WriteLine("RequestUri : {0}", request.RequestUri);
            // Console.WriteLine(response.Content.ReadAsStringAsync());
            // Console.WriteLine("Headers: {0}", response.Headers);
            // Console.WriteLine("RequestMessage: {0}", response.RequestMessage);
            // Console.WriteLine("IsSuccessStatusCode: {0}", response.IsSuccessStatusCode);
            // Console.WriteLine("ReasonPhrase: {0}", response.ReasonPhrase);
            // Console.WriteLine("StatusCode: {0}", response.StatusCode);
            // Console.WriteLine("Version: {0}", response.Version);
            return(response);
        }