source: binary-improvements/MapRendering/Web/Handlers/ApiHandler.cs@ 249

Last change on this file since 249 was 247, checked in by alloc, 9 years ago

Fixes

File size: 2.3 KB
Line 
1using AllocsFixes.NetConnections.Servers.Web.API;
2using System;
3using System.Collections.Generic;
4using System.IO;
5using System.Net;
6using System.Threading;
7
8namespace 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
Note: See TracBrowser for help on using the repository browser.