Ejemplo n.º 1
0
        public HttpHandlerResult SaveScript(HttpRequestParams request)
        {
            var id = request.GetGuid("id");
            var name = request.GetRequiredString("name");
            var body = request.GetRequiredString("body");

            using (var session = database.OpenSession())
            {
                UserScript script;

                if (id.HasValue)
                {
                    script = session.Set<UserScript>().Single(s => s.Id == id.Value);
                }
                else
                {
                    script = new UserScript { Id = Guid.NewGuid() };
                    session.Set<UserScript>().Add(script);
                }

                script.Name = name;
                script.Body = body;
                session.SaveChanges();

                return HttpHandlerResult.Json(new { scriptId = script.Id });
            }
        }
Ejemplo n.º 2
0
 public HttpHandlerResult TmpHandlerMethod42(HttpRequestParams requestParams)
 {
     return(HttpHandlerResult.Json(new
     {
         answer = 42,
         name = requestParams.GetString("name")
     }));
 }
Ejemplo n.º 3
0
        public HttpHandlerResult GetUrlErrors(HttpRequestParams requestParams)
        {
            var sb = new StringBuilder();

            errors.ForEach(msg => sb.AppendLine(msg));

            return(HttpHandlerResult.Text(sb.ToString()));
        }
Ejemplo n.º 4
0
        public HttpHandlerResult LoadTask(HttpRequestParams request)
        {
            var id = request.GetRequiredGuid("id");

            using (var session = database.OpenSession())
            {
                var task = session.Set <CronTask>().Single(x => x.Id == id);

                return(HttpHandlerResult.Json(ToApiModel(task)));
            }
        }
Ejemplo n.º 5
0
        public HttpHandlerResult TmpHandlerMethod43(HttpRequestParams requestParams)
        {
            using (var db = database.OpenSession())
            {
                var list = db.Set <SmallPig>()
                           .Select(pig => new { id = pig.Id, name = pig.Name, size = pig.Size })
                           .ToList();

                return(HttpHandlerResult.Json(list));
            }
        }
Ejemplo n.º 6
0
        public HttpHandlerResult GetScriptList(HttpRequestParams request)
        {
            using (var session = database.OpenSession())
            {
                var list = session.Set<UserScript>()
                    .Select(x => new { id = x.Id, name = x.Name })
                    .ToArray();

                return HttpHandlerResult.Json(list);
            }
        }
Ejemplo n.º 7
0
        public HttpHandlerResult LoadScript(HttpRequestParams request)
        {
            var id = request.GetRequiredGuid("id");

            using (var session = database.OpenSession())
            {
                var script = session.Set<UserScript>()
                    .Select(x => new { id = x.Id, name = x.Name, body = x.Body })
                    .Single(x => x.id == id);

                return HttpHandlerResult.Json(script);
            }
        }
Ejemplo n.º 8
0
        public HttpHandlerResult RunScript(HttpRequestParams request)
        {
            var id = request.GetRequiredGuid("id");

            using (var session = database.OpenSession())
            {
                var script = session.Set<UserScript>().Single(s => s.Id == id);

                object result = scripts.ExecuteScript(script);

                return HttpHandlerResult.Json(result);
            }
        }
Ejemplo n.º 9
0
        public override HttpHandlerResult Post()
        {
            var id = GetQuery("id");

            if (string.IsNullOrEmpty(id))
            {
                return(Response.BadRequest().SetText("'id' is undefined!"));
            }

            PhotonServer.Instance.Projects.Remove(id);

            return(HttpHandlerResult.Ok());
        }
Ejemplo n.º 10
0
        internal async Task <HttpHandlerResult> ExecuteAsync(IHttpHandler handlerObj, CancellationToken token)
        {
            var method = handlerObj.HttpContext.Request.HttpMethod;
            HttpHandlerResult result = null;

            var filters = handlerObj.GetType().GetCustomAttributes()
                          .OfType <HttpFilterAttribute>().ToArray();

            foreach (var filter in filters)
            {
                result = filter.Run(handlerObj, HttpFilterEvents.Before);
                if (result != null)
                {
                    return(result);
                }
            }

            try {
                if (handlerObj is HttpHandlerAsync handlerAsync)
                {
                    if (!execMapAsync.TryGetValue(method, out var execFunc))
                    {
                        throw new ApplicationException($"Unsupported method '{method}'!");
                    }

                    result = await execFunc.Invoke(handlerAsync, token);
                }
                else if (handlerObj is HttpHandler handler)
                {
                    if (!execMap.TryGetValue(method, out var execFunc))
                    {
                        throw new ApplicationException($"Unsupported method '{method}'!");
                    }

                    result = await Task.Run(() => execFunc.Invoke(handler), token);
                }
            }
            finally {
                foreach (var filter in filters)
                {
                    var newResult = filter.RunAfter(handlerObj, result);
                    if (newResult != null)
                    {
                        result = newResult;
                        break;
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 11
0
        internal async Task <HttpHandlerResult> ExecuteUnauthorizedAsync(IHttpHandler handlerObj, CancellationToken token)
        {
            HttpHandlerResult result = null;

            if (handlerObj is HttpHandlerAsync handlerAsync)
            {
                result = await handlerAsync.OnUnauthorizedAsync(token);
            }
            else if (handlerObj is HttpHandler handler)
            {
                result = await Task.Run(() => handler.OnUnauthorized(), token);
            }

            return(result);
        }
Ejemplo n.º 12
0
        public HttpHandlerResult GetTaskList(HttpRequestParams request)
        {
            using (var session = database.OpenSession())
            {
                var list = session.Set <CronTask>()
                           .OrderBy(e => e.Month)
                           .ThenBy(e => e.Day)
                           .ThenBy(e => e.Hour)
                           .ThenBy(e => e.Minute)
                           .Select(ToApiModel)
                           .ToArray();

                return(HttpHandlerResult.Json(list));
            }
        }
Ejemplo n.º 13
0
        public HttpHandlerResult GetSubscriptionList(HttpRequestParams request)
        {
            using (var session = database.OpenSession())
            {
                var list = session.Set<ScriptEventHandler>()
                    .Select(x => new
                    {
                        id = x.Id,
                        scriptId = x.UserScript.Id,
                        scriptName = x.UserScript.Name,
                        eventAlias = x.EventAlias
                    })
                    .ToList();

                return HttpHandlerResult.Json(list);
            }
        }
Ejemplo n.º 14
0
        private async Task RouteRequest(HttpListenerContext httpContext)
        {
            // Auto-Redirect HTTP to HTTPS if 'HttpsState' is 'Forced'.
            if (Context.Https == HttpsStates.Forced && !string.Equals("https", httpContext.Request.Url.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                RedirectToSecure(httpContext);
                return;
            }

            var path = httpContext.Request.Url.AbsolutePath.TrimEnd('/');

            var root = Context.ListenerPath.TrimEnd('/');

            if (path.StartsWith(root))
            {
                path = path.Substring(root.Length);
            }

            if (path.Length == 0)
            {
                path = "/";
            }

            HttpHandlerResult result = null;
            var tokenSource          = new CancellationTokenSource();

            try {
                result = await GetRouteResult(httpContext, path, tokenSource.Token)
                         ?? HttpHandlerResult.NotFound().SetText($"No content found matching path '{path}'!");

                await result.ApplyAsync(httpContext, tokenSource.Token);
            }
            catch (Exception) {
                tokenSource.Cancel();
                throw;
            }
            finally {
                try {
                    result?.Dispose();
                }
                catch {}

                tokenSource.Dispose();
            }
        }
Ejemplo n.º 15
0
        private HttpHandlerResult ProcessContent(HttpListenerContext context, string localPath, ContentDirectory directory)
        {
            if (Path.DirectorySeparatorChar != '/')
            {
                localPath = localPath.Replace('/', Path.DirectorySeparatorChar);
            }

            var localFilename = Path.Combine(directory.DirectoryPath, localPath);

            // Ensure requested content is within the specified directory
            // IE, prevent relative path hacking
            var fullRootPath      = Path.GetFullPath(directory.DirectoryPath);
            var fullLocalFilename = Path.GetFullPath(localFilename);

            if (!fullLocalFilename.StartsWith(fullRootPath))
            {
                return(HttpHandlerResult.NotFound()
                       .SetText($"Requested file is outisde of the content directory! [{fullLocalFilename}]"));
            }

            var localFile = new FileInfo(fullLocalFilename);

            // Ensure file exists
            if (!localFile.Exists)
            {
                return(HttpHandlerResult.NotFound()
                       .SetText($"File not found! [{fullLocalFilename}]"));
            }

            // HTTP Caching - Last-Modified
            var ifModifiedSince = context.Request.Headers.Get("If-Modified-Since");

            if (DateTime.TryParse(ifModifiedSince, out var ifModifiedSinceValue))
            {
                if (localFile.LastWriteTime.TrimMilliseconds() <= ifModifiedSinceValue)
                {
                    return(HttpHandlerResult.Status(HttpStatusCode.NotModified));
                }
            }

            return(HttpHandlerResult.File(Context, fullLocalFilename)
                   .SetHeader("Last-Modified", localFile.LastWriteTimeUtc.ToString("r")));
        }
Ejemplo n.º 16
0
        public HttpHandlerResult SaveTask(HttpRequestParams request)
        {
            var id         = request.GetGuid("id");
            var name       = request.GetRequiredString("name");
            var eventAlias = request.GetString("eventAlias");
            var month      = request.GetInt32("month");
            var day        = request.GetInt32("day");
            var hour       = request.GetInt32("hour");
            var minute     = request.GetInt32("minute");
            var enabled    = request.GetRequiredBool("enabled");

            using (var session = database.OpenSession())
            {
                CronTask task;

                if (id.HasValue)
                {
                    task = session.Set <CronTask>().Single(s => s.Id == id.Value);
                }
                else
                {
                    task = new CronTask {
                        Id = Guid.NewGuid()
                    };
                    session.Set <CronTask>().Add(task);
                }

                task.Name       = name;
                task.EventAlias = eventAlias;
                task.Enabled    = enabled;
                task.Month      = month;
                task.Day        = day;
                task.Hour       = hour;
                task.Minute     = minute;
                session.SaveChanges();

                // reset cron event cache
                cron.ReloadTasks();

                return(HttpHandlerResult.Json(new { taskId = task.Id }));
            }
        }
Ejemplo n.º 17
0
        public HttpHandlerResult AddSubscription(HttpRequestParams request)
        {
            var scriptId = request.GetRequiredGuid("scriptId");
            var eventAlias = request.GetRequiredString("eventAlias");

            using (var session = database.OpenSession())
            {
                var subscriptionId = Guid.NewGuid();

                var subscription = new ScriptEventHandler
                {
                    Id = subscriptionId,
                    EventAlias = eventAlias,
                    UserScriptId = scriptId
                };

                session.Set<ScriptEventHandler>().Add(subscription);
                session.SaveChanges();

                return HttpHandlerResult.Json(new { subscriptionId }) ;
            }
        }
Ejemplo n.º 18
0
 private HttpHandlerResult GetRouteUnauthorizedResult(HttpListenerContext httpContext)
 {
     return(Context.SecurityMgr.OnUnauthorized(httpContext, Context)
            ?? HttpHandlerResult.Unauthorized());
 }
Ejemplo n.º 19
0
        private async Task <HttpHandlerResult> GetRouteResult(HttpListenerContext httpContext, string path, CancellationToken token)
        {
            var overrideRoute = RouteOverrides.Where(x => x.IsEnabled)
                                .FirstOrDefault(x => x.FilterFunc(path));

            // Http Route Overrides with Content
            if (overrideRoute != null && overrideRoute.IncludesContent)
            {
                if (overrideRoute.IsSecure && Context.SecurityMgr != null)
                {
                    if (!Context.SecurityMgr.Authorize(httpContext.Request))
                    {
                        return(GetRouteUnauthorizedResult(httpContext));
                    }
                }

                try {
                    if (overrideRoute.ExecuteEvent == null)
                    {
                        return(null);
                    }

                    return(await overrideRoute.ExecuteEvent.Invoke(httpContext, Context));
                }
                catch (Exception error) {
                    return(HttpHandlerResult.Exception(error));
                }
            }

            // Content Directories
            var contentRoute = Context.ContentDirectories
                               .FirstOrDefault(x => path.StartsWith(x.UrlPath));

            if (contentRoute != null)
            {
                if (contentRoute.IsSecure && Context.SecurityMgr != null)
                {
                    if (!Context.SecurityMgr.Authorize(httpContext.Request))
                    {
                        return(GetRouteUnauthorizedResult(httpContext));
                    }
                }

                var localPath = path.Substring(contentRoute.UrlPath.Length);
                return(ProcessContent(httpContext, localPath, contentRoute));
            }

            // Http Route Overrides without Content
            if (overrideRoute != null)
            {
                if (overrideRoute.IsSecure && Context.SecurityMgr != null)
                {
                    if (!Context.SecurityMgr.Authorize(httpContext.Request))
                    {
                        return(GetRouteUnauthorizedResult(httpContext));
                    }
                }

                try {
                    if (overrideRoute.ExecuteEvent == null)
                    {
                        return(null);
                    }

                    return(await overrideRoute.ExecuteEvent.Invoke(httpContext, Context));
                }
                catch (Exception error) {
                    return(HttpHandlerResult.Exception(error));
                }
            }

            // Http Route
            if (Routes.FindRoute(path, out var routeDesc))
            {
                var handler = Routes.GetHandler(routeDesc, httpContext, Context);

                if (routeDesc.IsSecure && Context.SecurityMgr != null)
                {
                    if (!Context.SecurityMgr.Authorize(httpContext.Request))
                    {
                        HttpHandlerResult result = null;
                        if (handler != null)
                        {
                            result = await Routes.ExecuteUnauthorizedAsync(handler, token);
                        }

                        return(result ?? GetRouteUnauthorizedResult(httpContext));
                    }
                }

                try {
                    //var handler = Routes.GetHandler(routeDesc, httpContext, Context);
                    if (handler == null)
                    {
                        return(null);
                    }

                    return(await Routes.ExecuteAsync(handler, token));
                }
                catch (Exception error) {
                    return(HttpHandlerResult.Exception(error));
                }
            }

            // Not Found
            return(null);
        }
Ejemplo n.º 20
0
        public HttpHandlerResult OnUnauthorized(HttpListenerContext httpContext, HttpReceiverContext context)
        {
            var returnUrl = httpContext.Request.RawUrl;

            return(HttpHandlerResult.Redirect(context, "/login", new { returnUrl }));
        }
Ejemplo n.º 21
0
 public virtual HttpHandlerResult OnUnauthorized()
 {
     return(Context.SecurityMgr.OnUnauthorized(HttpContext, Context)
            ?? HttpHandlerResult.Unauthorized());
 }