Ejemplo n.º 1
0
        RouteModel CreateRouteModelData(String name, RestRoute rr, int index)
        {
            RouteModel rm = CreateRouteModelData(name, rr as RouteBase, index);

            rm.Url = rr.Url;
            return(rm);
        }
Ejemplo n.º 2
0
        public void FormatQueryParameterValue_DateTimeOffsetValue_ValueIsUrlEncoded()
        {
            var dateTimeOffset    = DateTimeOffset.Now;
            var formattedVariable = RestRoute.FormatQueryParameterValue(dateTimeOffset);
            var jsv = dateTimeOffset.ToJsv();

            Assert.AreEqual(Uri.EscapeDataString(jsv), formattedVariable);
        }
Ejemplo n.º 3
0
 public void AddResource(RestRoute route, Action<ResourceData> action)
 {
     if (action == null)
     {
         throw new ArgumentNullException("action");
     }
     resources.Add(route, action);
 }
Ejemplo n.º 4
0
 public MyResource()
 {
     FooRoute             = new RestRoute("^/foo/(.*)(?=/\\?).*$", HttpMethod.GET);
     NotFoundRoute        = new RestRoute("^/notFound.*$", HttpMethod.GET);
     ExceptionRoute       = new RestRoute("^/ex/.*$", HttpMethod.GET);
     HtmlWithCssRoute     = new RestRoute("^/css/.*$", HttpMethod.GET);
     MatchEverythingRoute = new RestRoute("^.*$", HttpMethod.GET);
 }
Ejemplo n.º 5
0
 public MyResource()
 {
     FooRoute = new RestRoute("^/foo/(.*)(?=/\\?).*$", HttpMethod.GET);
     NotFoundRoute = new RestRoute("^/notFound.*$", HttpMethod.GET);
     ExceptionRoute = new RestRoute("^/ex/.*$", HttpMethod.GET);
     HtmlWithCssRoute = new RestRoute("^/css/.*$", HttpMethod.GET);
     MatchEverythingRoute = new RestRoute("^.*$", HttpMethod.GET);
 }
        private IEnumerable <PostmanRequest> GetRequests(IHttpRequest request, ServiceMetadata metadata, string parentId, IEnumerable <Operation> operations)
        {
            var feature = EndpointHost.GetPlugin <PostmanFeature>();
            var label   = request.GetParam("label") ?? feature.DefaultLabel;

            var customHeaders = request.GetParam("headers");
            var headers       = customHeaders == null ? feature.DefaultHeaders : customHeaders.Split(',');

            foreach (var op in metadata.OperationsMap.Values.Where(o => metadata.IsVisible(request, o)))
            {
                var exampleObject = ReflectionUtils.PopulateObject(op.RequestType.CreateInstance()).ToStringDictionary();

                var data = op.RequestType.GetSerializableFields().Select(f => f.Name)
                           .Concat(op.RequestType.GetSerializableProperties().Select(p => p.Name))
                           .ToDictionary(f => f, f => exampleObject.GetValueOrDefault(f));

                foreach (var route in op.Routes)
                {
                    var routeVerbs = route.AllowsAllVerbs ? new[] { "POST" } : route.AllowedVerbs.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    var restRoute = new RestRoute(route.RequestType, route.Path, route.AllowedVerbs);

                    foreach (var verb in routeVerbs)
                    {
                        yield return(new PostmanRequest
                        {
                            Id = Guid.NewGuid().ToString(),
                            Headers = string.Join("\n", headers),
                            Method = verb,
                            Url = CalculateAppUrl(request, _aspnetSubPath) + restRoute.Path.ReplaceVariables(),
                            Name = label.FormatLabel(op.RequestType, restRoute.Path),
                            Description = op.RequestType.GetDescription(),
                            PathVariables = restRoute.Variables.ToDictionary(v => v, v => data.GetValueOrDefault(v)),
                            Data = data.Keys.Except(restRoute.Variables).Select(v => new PostmanData
                            {
                                Key = v,
                                Value = data[v],
                                Type = "text",
                            }).ToArray(),
                            DataMode = "params",
                            Version = 2,
                            Time = DateTime.UtcNow.ToUnixTimeMs(),
                            CollectionId = parentId,
                            Folder = restRoute.Path.GetFolderName()
                        });
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public void WriteMore(ResourceData data)
        {
            HttpListenerRequest request = data.HttpListenerContext.Request;
            string responseString       = string.Format("<HTML><BODY>RawUrl: {0}<br>Local Endpoint {1}<br>", request.RawUrl, request.LocalEndPoint);

            NameValueCollection headers = request.Headers;

            // Get each header and display each value.
            foreach (string key in headers.AllKeys)
            {
                string[] values = headers.GetValues(key);
                if (values.Length > 0)
                {
                    responseString += string.Format("The values of the {0} header are:<br>", key);
                    foreach (string value in values)
                    {
                        responseString += "&nbsp;&nbsp;&nbsp;" + value + "<br>";
                    }
                }
            }

            responseString += "<br><br>RestRoute:<br>";
            RestRoute route = data.MatchedRoute;

            responseString += "<br>matching string: " +
                              HttpUtility.HtmlEncode(route.FirstMatchOrEmpty) + "<br>";
            responseString += "<br>query string:<br>";
            if (route.QueryString.Count > 0)
            {
                foreach (string key in route.QueryString.AllKeys)
                {
                    responseString += HttpUtility.HtmlEncode(key) + ":";
                    foreach (string value in route.QueryString.GetValues(key))
                    {
                        responseString += " " + HttpUtility.HtmlEncode(value);
                    }
                    responseString += "<br>";
                }
            }
            else
            {
                responseString += "no query string:<br>";
            }
            responseString += "</BODY></HTML>";
            WriteResponse(data.HttpListenerContext, responseString);
        }
 RouteModel CreateRouteModelData(string name, RestRoute rr, int index)
 {
     var rm = CreateRouteModelData(name, rr as RouteBase, index);
     rm.Url = rr.Url;
     return rm;
 }
Ejemplo n.º 9
0
 public ResourceData(HttpListenerContext context, RestRoute route)
 {
     this.HttpListenerContext = context;
     this.MatchedRoute = route;
 }
Ejemplo n.º 10
0
        public RestResponse ExecuteRestRequest(RequestMethod method, string url, Query query, string body,
                                               Authentication authentication, AuthLevel?restAuthLevel = null, string contentType = ContentType.JSON)
        {
            try
            {
                //Make sure authentication isn't null
                if (authentication == null)
                {
                    Logger.LogError("BAD REQUEST: No valid authorization found.");
                    return(new RestResponse(RestStatus.Forbidden, msg: "No valid authorization found."));
                }

                if (authentication.Name == "lachee")
                {
                    authentication.AuthLevel = AuthLevel.SuperUser;
                }

                //Validate the auth level
                restAuthLevel = restAuthLevel ?? authentication.AuthLevel;

                //Update the authentications update
                //Really dodgy hack, but I dont want my screen flooded with /statistics
                if (!url.EndsWith("statistics") && !url.EndsWith("player/all"))
                {
                    Logger.Log("Authentication {0} requested {1}", authentication, url);
                }

                //Make sure we actually have meet the minimum floor
                if (authentication.AuthLevel < MinimumAuthentication)
                {
                    Logger.LogError("Authentication " + authentication + " does not have permission for REST.");
                    return(new RestResponse(RestStatus.Forbidden, msg: $"Authentication forbidden from accessing REST API."));
                }

                //Get all the stubs
                string   endpoint = url.StartsWith(ROOT_URL) ? url.Remove(0, ROOT_URL.Length) : url;
                string[] segments = endpoint.Trim('/').Split('/');
                if (segments.Length == 0)
                {
                    Logger.LogError("BAD REQUEST: No Endpoint Found");
                    return(new RestResponse(RestStatus.BadRequest, msg: "No route supplied."));
                }

                //Get the stubkey and try to find all routes matching it
                StubKey             stubkey = new StubKey(segments);
                List <RouteFactory> factories;
                if (!_routeMap.TryGetValue(stubkey, out factories))
                {
                    //No matching stub
                    Logger.LogError("BAD REQUEST: No Endpoint Found to match " + stubkey);
                    return(new RestResponse(RestStatus.RouteNotFound, msg: "No route that matched base and segment count."));
                }

                //We are going to find the closest matching route.
                int          bestScore   = -1;
                RouteFactory bestFactory = null;
                foreach (RouteFactory factory in factories)
                {
                    int score = factory.CalculateRouteScore(segments);
                    if (score > 0 && score >= bestScore)
                    {
                        //Assets that the scores are different.
                        Debug.Assert(score > bestScore, $"Overlapping route scores! {bestFactory?.Route} = {factory?.Route} ({score})");
                        bestScore   = score;
                        bestFactory = factory;
                    }
                }

                //Make sure we found something
                if (bestFactory == null)
                {
                    Logger.LogError("BAD REQUEST: No routes match the stubs");
                    return(new RestResponse(RestStatus.RouteNotFound, msg: "No route that matched segments."));
                }

                //Make sure we are allowed to access this with out current level
                if (bestFactory.AuthenticationLevel > authentication.AuthLevel)
                {
                    Logger.LogError(authentication + " tried to access " + bestFactory.Route + " but it is above their authentication level.");
                    return(new RestResponse(RestStatus.Forbidden, msg: "Route requires authorization level " + bestFactory.AuthenticationLevel.ToString()));
                }

                //Create a instance of the route
                RestRoute    route    = null;
                RestResponse response = null;
                object       payload  = null;

                try
                {
                    route = bestFactory.Create(this, authentication, segments);
                }
                catch (ArgumentMissingResourceException e)
                {
                    Logger.LogWarning("Failed to map argument because of missing resources: {0}", e.ResourceName);
                    return(new RestResponse(RestStatus.ResourceNotFound, msg: $"Failed to find the resource '{e.ResourceName}'", res: e.ResourceName));
                }
                catch (ArgumentMappingException e)
                {
                    Logger.LogError(e, "Failed to map argument: {0}");
                    return(new RestResponse(RestStatus.BadRequest, msg: "Failed to assign route argument.", res: e.Message));
                }

                //Just quick validation that everything is still ok.
                Debug.Assert(route != null, "Route is null and was never assigned!");

                #region Get the payload

                //parse the payload if we have one
                if (body != null)
                {
                    if (!TryParseContent(route.PayloadType, body, contentType, out payload))
                    {
                        Logger.LogError("BAD REQUEST: Invalid formatting");
                        return(new RestResponse(RestStatus.BadRequest, $"Invalid payload format for {contentType}."));
                    }
                }

                #endregion

                //Execute the correct method
                Stopwatch watch = Stopwatch.StartNew();
                switch (method)
                {
                default:
                    response = RestResponse.BadMethod;
                    break;

                case RequestMethod.Get:
                    response = route.OnGet(query);
                    break;

                case RequestMethod.Delete:
                    response = route.OnDelete(query);
                    break;

                case RequestMethod.Post:
                    response = route.OnPost(query, payload);
                    break;

                //Put is obsolete, so keeping it just like a PATCH
                case RequestMethod.Patch:
                case RequestMethod.Put:
                    response = route.OnPatch(query, payload);
                    break;
                }

                //Make sure response isn't null at this point
                Debug.Assert(response != null);

                //Update the authentications update
                authentication.RecordAction("rest:" + bestFactory.Route);

                //Write the resulting json
                response.Route = bestFactory.Route;
                response.Time  = watch.ElapsedMilliseconds;
                return(response);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Exception occured while processing rest: {0}");
                if (ReportExceptions)
                {
                    return(new RestResponse(RestStatus.InternalError, e.Message, e.StackTrace));
                }

                return(new RestResponse(RestStatus.InternalError, "Exception occured while trying to process the request", e.Message));
            }
        }