1 | using AllocsFixes.NetConnections.Servers.Web.API;
|
---|
2 | using System;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using System.IO;
|
---|
5 | using System.Net;
|
---|
6 | using System.Threading;
|
---|
7 |
|
---|
8 | namespace AllocsFixes.NetConnections.Servers.Web.Handlers
|
---|
9 | {
|
---|
10 | public class ApiHandler : PathHandler {
|
---|
11 | private string staticPart;
|
---|
12 | private Dictionary<String, WebAPI> apis = new Dictionary<string, WebAPI> ();
|
---|
13 |
|
---|
14 | public ApiHandler (string staticPart, string moduleName = null) : base(moduleName) {
|
---|
15 | this.staticPart = staticPart;
|
---|
16 | addApi ("getlandclaims", new GetLandClaims ());
|
---|
17 | addApi ("getplayersonline", new GetPlayersOnline ());
|
---|
18 | addApi ("getplayerslocation", new GetPlayersLocation ());
|
---|
19 | addApi ("getplayerinventory", new GetPlayerInventory ());
|
---|
20 | addApi ("getstats", new GetStats ());
|
---|
21 | }
|
---|
22 |
|
---|
23 | private void addApi (string _apiName, WebAPI _api) {
|
---|
24 | apis.Add (_apiName, _api);
|
---|
25 | WebPermissions.Instance.AddKnownModule ("webapi." + _apiName);
|
---|
26 | }
|
---|
27 |
|
---|
28 | public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) {
|
---|
29 | string apiName = req.Url.AbsolutePath.Remove (0, staticPart.Length);
|
---|
30 | if (!AuthorizeForCommand (apiName, user, permissionLevel)) {
|
---|
31 | resp.StatusCode = (int)HttpStatusCode.Forbidden;
|
---|
32 | if (user != null) {
|
---|
33 | //Log.Out ("ApiHandler: user '{0}' not allowed to execute '{1}'", user.SteamID, apiName);
|
---|
34 | } else {
|
---|
35 | //Log.Out ("ApiHandler: unidentified user from '{0}' not allowed to execute '{1}'", req.RemoteEndPoint.Address, apiName);
|
---|
36 | }
|
---|
37 | return;
|
---|
38 | } else {
|
---|
39 | foreach (KeyValuePair<string, WebAPI> kvp in apis) {
|
---|
40 | try {
|
---|
41 | if (apiName.StartsWith (kvp.Key)) {
|
---|
42 | kvp.Value.HandleRequest (req, resp, user, permissionLevel);
|
---|
43 | return;
|
---|
44 | }
|
---|
45 | } catch (Exception e) {
|
---|
46 | Log.Out ("Error in ApiHandler.HandleRequest(): Handler threw an exception: " + e);
|
---|
47 | resp.StatusCode = (int)HttpStatusCode.InternalServerError;
|
---|
48 | return;
|
---|
49 | }
|
---|
50 | }
|
---|
51 | }
|
---|
52 |
|
---|
53 | Log.Out ("Error in ApiHandler.HandleRequest(): No handler found for API \"" + apiName + "\"");
|
---|
54 | resp.StatusCode = (int)HttpStatusCode.NotFound;
|
---|
55 | }
|
---|
56 |
|
---|
57 | private bool AuthorizeForCommand (string apiName, WebConnection user, int permissionLevel) {
|
---|
58 | return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi." + apiName, permissionLevel);
|
---|
59 | }
|
---|
60 |
|
---|
61 | }
|
---|
62 |
|
---|
63 | }
|
---|
64 |
|
---|