forked from perceptile/ScriptServices
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptServicesModule.cs
More file actions
74 lines (58 loc) · 2.16 KB
/
Copy pathScriptServicesModule.cs
File metadata and controls
74 lines (58 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System.Collections.Generic;
using System.IO;
using Nancy;
using Nancy.Extensions;
using Nancy.Json;
using ScriptServices.powershell;
namespace ScriptServices
{
public class ScriptServicesModule : NancyModule
{
private readonly ConfigSettings _settings;
public ScriptServicesModule(ConfigSettings settings)
{
_settings = settings;
JsonSettings.MaxJsonLength = 5000000;
JsonSettings.RetainCasing = true;
Get["/admin"] = _ =>
Response.AsJson("Hello Admin!");
Get["/script/^(?<route>.*)$"] = p =>
ProcessRequest(p);
Post["/script/^(?<route>.*)$"] = p =>
ProcessRequest(p);
Put["/script/^(?<route>.*)$"] = p =>
ProcessRequest(p);
Delete["/script/^(?<route>.*)$"] = p =>
ProcessRequest(p);
}
private Response ProcessRequest(dynamic routeParameters)
{
// Resolve the script being reference by the request
var subPath = ((string)routeParameters["route"]);
var script = string.Format("{0}.ps1", Path.Combine(_settings.ScriptRepoRoot, subPath));
if (!File.Exists(script))
{
return HttpStatusCode.NotFound;
}
// elements of the request will be passed to the script as named routeParameters
var scriptArgs = new Dictionary<string, string>();
// Process querystring routeParameters
foreach (var q in Request.Query.Keys)
{
scriptArgs.Add(q, Request.Query[q].Value);
}
// Process request body, if any
var body = this.Request.Body.AsString();
if (!string.IsNullOrEmpty(body))
{
scriptArgs.Add("body", body);
}
var res = PowerShellRunner.Execute(Request.Method, script, scriptArgs);
if (!res.Success)
{
return Response.AsJson(new { Error = res.Output }, HttpStatusCode.InternalServerError);
}
return Response.AsJson(res.Output);
}
}
}