public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);

            // if we don't have the info we need to authenticate, then do not authenticate
            Guid authKey;

            if (String.IsNullOrEmpty(OpenAMUrl) || actionContext.Request.Headers.Authorization == null || !Guid.TryParse(actionContext.Request.Headers.Authorization.Parameter, out authKey))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Not authorized to access this endpoint.")
                };
                Utilities.Statistics.AddToUnauthenticatedRequestCount();
                return;
            }

            // try to get it from cache
            AuthTokenCache.CacheEntry entry = AuthTokenCache.Instance.Get(authKey);
            if (entry != null)
            {
                return; // it's in the cache, so let it through
            }
            // wasn't in the cache.  Authenticate it then add it to the cache if successful
            HttpResponseMessage response = null;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    response = client.GetAsync(String.Format("{0}?access_token={1}", OpenAMUrl, authKey)).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        // appears to be a successful authentication.
                        try
                        {
                            // get the token info; if it's good, cache it
                            TokenInfo tok = response.Content.ReadAsAsync <TokenInfo>().Result;
                            if (tok.IsAuthenticated)
                            {
                                AuthTokenCache.Instance.Put(tok);
                            }
                            else  // token is not valid.  Do not authenticate
                            {
                                response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                                {
                                    Content = new StringContent(String.Format("Token not authenticated: {0}, {1}", tok.error, tok.error_description))
                                }
                            };
                        }
                        catch (Exception ex)
                        {
                            // there was an error deserializing the token info.  Do not authenticate.
                            response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                            {
                                Content = new StringContent(String.Format("Could not read token: {0}", ex.Message))
                            };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TISServicesLogger.Log(ex);
                response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("An exception occurred while attempting to access the oauth server.")
                };
            }

            if (!response.IsSuccessStatusCode)
            {
                actionContext.Response = response;
                Utilities.Statistics.AddToUnauthenticatedRequestCount();
            }
        }
Exemple #2
0
        public HttpResponseMessage Submit(string statusCallback)
        {
            Uri callBackUrl = null;

            Statistics.AddToReceivedRequestCount();

            //don't need this; qs params are wired to method params
            //Dictionary<string, string> qsParams = Request.GetQueryStringParams();

            if (String.IsNullOrEmpty(statusCallback))
            {
                TISServicesLogger.Log("Empty statusCallback.");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "This request is not properly formatted."));
            }

            try
            {
                // make sure it's a valid URI
                callBackUrl = new Uri(statusCallback);
            }
            catch
            {
                TISServicesLogger.Log(String.Format("statusCallback could not be converted to a Uri: {0}", statusCallback));
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Illegal statusCallback format."));
            }

            // check to make sure it's a valid XML doc.  XmlRep.InsertXml would do this anyway if we passed a string,
            //  so best to do it here where we can check it.
            XmlDocument doc = null;

            try
            {
                //TODO: validate against XSD, or let TIS handle that?  For now, do not validate.
                doc = new XmlDocument();
                doc.Load(XmlReader.Create(Request.Content.ReadAsStreamAsync().Result));
            }
            catch (Exception ex)
            {
                TISServicesLogger.Log(ex);
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Content format is not valid."));
            }

            // sanity check to make sure we're getting the right files
            //TODO: want to add any other validation?  Note that if we do decide to validate against the XSD above, this isn't needed.
            if (!doc.DocumentElement.Name.Equals("TDSReport"))
            {
                TISServicesLogger.Log(String.Format("Unexpected document element: {0}", doc.DocumentElement.Name));
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Format("Invalid test result: {0}", doc.DocumentElement.Name)));
            }

            try
            {
                new XmlRepository().InsertXml(XmlRepository.Location.source, doc, callBackUrl.AbsoluteUri, new TestResultSerializerFactory());
                Statistics.AddToInsertedRequestCount();
            }
            catch (Exception ex)
            {
                TISServicesLogger.Log(ex);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not persist the request."));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }