using AllocsFixes.NetConnections.Servers.Web.API; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; namespace AllocsFixes.NetConnections.Servers.Web.Handlers { public class ApiHandler : PathHandler { private string staticPart; private Dictionary apis = new Dictionary (); public ApiHandler (string staticPart, string moduleName = null) : base(moduleName) { this.staticPart = staticPart; addApi ("getlandclaims", new GetLandClaims ()); addApi ("getplayersonline", new GetPlayersOnline ()); addApi ("getplayerslocation", new GetPlayersLocation ()); addApi ("getplayerinventory", new GetPlayerInventory ()); addApi ("getstats", new GetStats ()); } private void addApi (string _apiName, WebAPI _api) { apis.Add (_apiName, _api); WebPermissions.Instance.AddKnownModule ("webapi." + _apiName); } public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { string apiName = req.Url.AbsolutePath.Remove (0, staticPart.Length); if (!AuthorizeForCommand (apiName, user, permissionLevel)) { resp.StatusCode = (int)HttpStatusCode.Forbidden; if (user != null) { //Log.Out ("ApiHandler: user '{0}' not allowed to execute '{1}'", user.SteamID, apiName); } else { //Log.Out ("ApiHandler: unidentified user from '{0}' not allowed to execute '{1}'", req.RemoteEndPoint.Address, apiName); } return; } else { foreach (KeyValuePair kvp in apis) { try { if (apiName.StartsWith (kvp.Key)) { kvp.Value.HandleRequest (req, resp, user, permissionLevel); return; } } catch (Exception e) { Log.Out ("Error in ApiHandler.HandleRequest(): Handler threw an exception: " + e); resp.StatusCode = (int)HttpStatusCode.InternalServerError; return; } } } Log.Out ("Error in ApiHandler.HandleRequest(): No handler found for API \"" + apiName + "\""); resp.StatusCode = (int)HttpStatusCode.NotFound; } private bool AuthorizeForCommand (string apiName, WebConnection user, int permissionLevel) { return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi." + apiName, permissionLevel); } } }