Ignore:
Timestamp:
Aug 6, 2022, 11:32:32 PM (3 years ago)
Author:
alloc
Message:

Big refactoring in Web to pass around a Context instead of a bunch of individual arguments all the time

Location:
binary-improvements2/MapRendering/Web/Handlers
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • binary-improvements2/MapRendering/Web/Handlers/AbsHandler.cs

    r383 r387  
    1 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    2 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    3 
    41namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
    52        public abstract class AbsHandler {
     
    1613                }
    1714
    18                 public abstract void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    19                         int _permissionLevel);
     15                public abstract void HandleRequest (RequestContext _context);
    2016
    2117                public virtual bool IsAuthorizedForHandler (WebConnection _user, int _permissionLevel) {
  • binary-improvements2/MapRendering/Web/Handlers/ApiHandler.cs

    r384 r387  
    44using System.Reflection;
    55using AllocsFixes.NetConnections.Servers.Web.API;
    6 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    7 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    86
    97namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
    108        public class ApiHandler : AbsHandler {
    11                 private readonly Dictionary<string, WebAPI> apis = new CaseInsensitiveStringDictionary<WebAPI> ();
     9                private readonly Dictionary<string, AbsWebAPI> apis = new CaseInsensitiveStringDictionary<AbsWebAPI> ();
    1210
    1311                public ApiHandler () : base (null) {
     
    2523                       
    2624                        foreach (Type t in Assembly.GetExecutingAssembly ().GetTypes ()) {
    27                                 if (!t.IsAbstract && t.IsSubclassOf (typeof (WebAPI))) {
     25                                if (!t.IsAbstract && t.IsSubclassOf (typeof (AbsWebAPI))) {
    2826                                        ConstructorInfo ctor = t.GetConstructor (apiWithParentCtorTypes);
    2927                                        if (ctor != null) {
    30                                                 WebAPI apiInstance = (WebAPI) ctor.Invoke (apiWithParentCtorArgs);
     28                                                AbsWebAPI apiInstance = (AbsWebAPI) ctor.Invoke (apiWithParentCtorArgs);
    3129                                                addApi (apiInstance);
    3230                                                continue;
     
    3533                                        ctor = t.GetConstructor (apiEmptyCtorTypes);
    3634                                        if (ctor != null) {
    37                                                 WebAPI apiInstance = (WebAPI) ctor.Invoke (apiEmptyCtorArgs);
     35                                                AbsWebAPI apiInstance = (AbsWebAPI) ctor.Invoke (apiEmptyCtorArgs);
    3836                                                addApi (apiInstance);
    3937                                        }
     
    4644                }
    4745
    48                 private void addApi (WebAPI _api) {
     46                private void addApi (AbsWebAPI _api) {
    4947                        apis.Add (_api.Name, _api);
    5048                        WebPermissions.Instance.AddKnownModule ("webapi." + _api.Name, _api.DefaultPermissionLevel ());
     
    5553#endif
    5654
    57                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    58                         int _permissionLevel) {
    59                         string apiName = _requestPath.Remove (0, urlBasePath.Length);
     55                public override void HandleRequest (RequestContext _context) {
    6056
    61                         if (!apis.TryGetValue (apiName, out WebAPI api)) {
     57                        string apiName;
     58                        string subPath = null;
     59
     60                        int pathSeparatorIndex = _context.RequestPath.IndexOf ('/', urlBasePath.Length);
     61                        if (pathSeparatorIndex >= 0) {
     62                                apiName = _context.RequestPath.Substring (urlBasePath.Length, pathSeparatorIndex - urlBasePath.Length);
     63                                subPath = _context.RequestPath.Substring (pathSeparatorIndex + 1);
     64                        } else {
     65                                apiName = _context.RequestPath.Substring (urlBasePath.Length);
     66                        }
     67                       
     68                        if (!apis.TryGetValue (apiName, out AbsWebAPI api)) {
    6269                                Log.Out ($"Error in {nameof(ApiHandler)}.HandleRequest(): No handler found for API \"{apiName}\"");
    63                                 _resp.StatusCode = (int) HttpStatusCode.NotFound;
     70                                _context.Response.StatusCode = (int) HttpStatusCode.NotFound;
    6471                                return;
    6572                        }
    6673
    67                         if (!AuthorizeForApi (apiName, _permissionLevel)) {
    68                                 _resp.StatusCode = (int) HttpStatusCode.Forbidden;
    69                                 if (_con != null) {
     74                        if (!AuthorizeForApi (apiName, _context.PermissionLevel)) {
     75                                _context.Response.StatusCode = (int) HttpStatusCode.Forbidden;
     76                                if (_context.Connection != null) {
    7077                                        //Log.Out ($"{nameof(ApiHandler)}: user '{user.SteamID}' not allowed to execute '{apiName}'");
    7178                                }
     
    7481                        }
    7582
     83                        _context.RequestPath = subPath;
     84
    7685                        try {
    7786#if ENABLE_PROFILER
    7887                                apiHandlerSampler.Begin ();
    7988#endif
    80                                 api.HandleRequest (_req, _resp, _con, _permissionLevel);
     89                                api.HandleRequest (_context);
    8190#if ENABLE_PROFILER
    8291                                apiHandlerSampler.End ();
     
    8594                                Log.Error ($"Error in {nameof(ApiHandler)}.HandleRequest(): Handler {api.Name} threw an exception:");
    8695                                Log.Exception (e);
    87                                 _resp.StatusCode = (int) HttpStatusCode.InternalServerError;
     96                                _context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
    8897                        }
    8998                }
  • binary-improvements2/MapRendering/Web/Handlers/ItemIconHandler.cs

    r382 r387  
    44using System.Net;
    55using UnityEngine;
    6 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    7 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    86using Object = UnityEngine.Object;
    97
     
    2624                public static ItemIconHandler Instance { get; private set; }
    2725
    28                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    29                         int _permissionLevel) {
     26                public override void HandleRequest (RequestContext _context) {
    3027                        if (!loaded) {
    31                                 _resp.StatusCode = (int) HttpStatusCode.InternalServerError;
     28                                _context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
    3229                                Log.Out ("Web:IconHandler: Icons not loaded");
    3330                                return;
    3431                        }
    3532
    36                         string requestFileName = _requestPath.Remove (0, urlBasePath.Length);
     33                        string requestFileName = _context.RequestPath.Remove (0, urlBasePath.Length);
    3734                        requestFileName = requestFileName.Remove (requestFileName.LastIndexOf ('.'));
    3835
    39                         if (icons.ContainsKey (requestFileName) && _requestPath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
    40                                 _resp.ContentType = MimeType.GetMimeType (".png");
     36                        if (icons.ContainsKey (requestFileName) && _context.RequestPath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
     37                                _context.Response.ContentType = MimeType.GetMimeType (".png");
    4138
    4239                                byte[] itemIconData = icons [requestFileName];
    4340
    44                                 _resp.ContentLength64 = itemIconData.Length;
    45                                 _resp.OutputStream.Write (itemIconData, 0, itemIconData.Length);
     41                                _context.Response.ContentLength64 = itemIconData.Length;
     42                                _context.Response.OutputStream.Write (itemIconData, 0, itemIconData.Length);
    4643                        } else {
    47                                 _resp.StatusCode = (int) HttpStatusCode.NotFound;
     44                                _context.Response.StatusCode = (int) HttpStatusCode.NotFound;
    4845                                if (logMissingFiles) {
    49                                         Log.Out ("Web:IconHandler:FileNotFound: \"" + _requestPath + "\" ");
     46                                        Log.Out ("Web:IconHandler:FileNotFound: \"" + _context.RequestPath + "\" ");
    5047                                }
    5148                        }
  • binary-improvements2/MapRendering/Web/Handlers/RewriteHandler.cs

    r382 r387  
    1 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    2 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    3 
    41namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
    52        public class RewriteHandler : AbsHandler {
     
    129                }
    1310
    14                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    15                         int _permissionLevel) {
    16                         string newRequestPath = fixedTarget ? target : target + _requestPath.Remove (0, urlBasePath.Length);
    17                         parent.ApplyPathHandler (newRequestPath, _req, _resp, _con, _permissionLevel);
     11                public override void HandleRequest (RequestContext _context) {
     12                        _context.RequestPath = fixedTarget ? target : target + _context.RequestPath.Remove (0, urlBasePath.Length);
     13                        parent.ApplyPathHandler (_context);
    1814                }
    1915        }
  • binary-improvements2/MapRendering/Web/Handlers/SessionHandler.cs

    r382 r387  
    33using System.Net;
    44using System.Text;
    5 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    6 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    75
    86namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
     
    2927                }
    3028
    31                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    32                         int _permissionLevel) {
     29                public override void HandleRequest (RequestContext _context) {
    3330                       
    34                         IPEndPoint reqRemoteEndPoint = _req.RemoteEndPoint;
     31                        IPEndPoint reqRemoteEndPoint = _context.Request.RemoteEndPoint;
    3532                        if (reqRemoteEndPoint == null) {
    36                                 _resp.Redirect (pageBasePath);
     33                                _context.Response.Redirect (pageBasePath);
    3734                                return;
    3835                        }
    3936
    40                         string subpath = _requestPath.Remove (0, urlBasePath.Length);
     37                        string subpath = _context.RequestPath.Remove (0, urlBasePath.Length);
    4138
    4239                        StringBuilder result = new StringBuilder ();
     
    4744
    4845                                try {
    49                                         ulong id = OpenID.Validate (_req);
     46                                        ulong id = OpenID.Validate (_context.Request);
    5047                                        if (id > 0) {
    5148                                                WebConnection con = connectionHandler.LogIn (id, reqRemoteEndPoint.Address);
     
    6057                                                        Secure = false
    6158                                                };
    62                                                 _resp.AppendCookie (cookie);
    63                                                 _resp.Redirect (pageBasePath);
     59                                                _context.Response.AppendCookie (cookie);
     60                                                _context.Response.Redirect (pageBasePath);
    6461
    6562                                                return;
     
    7370                                result.Append ($"<h1>Login failed, <a href=\"{pageBasePath}\">click to return to main page</a>.</h1>");
    7471                        } else if (subpath.StartsWith ("logout")) {
    75                                 if (_con != null) {
    76                                         connectionHandler.LogOut (_con.SessionID);
     72                                if (_context.Connection != null) {
     73                                        connectionHandler.LogOut (_context.Connection.SessionID);
    7774                                        Cookie cookie = new Cookie ("sid", "", "/") {
    7875                                                Expired = true
    7976                                        };
    80                                         _resp.AppendCookie (cookie);
    81                                         _resp.Redirect (pageBasePath);
     77                                        _context.Response.AppendCookie (cookie);
     78                                        _context.Response.Redirect (pageBasePath);
    8279                                        return;
    8380                                }
     
    8582                                result.Append ($"<h1>Not logged in, <a href=\"{pageBasePath}\">click to return to main page</a>.</h1>");
    8683                        } else if (subpath.StartsWith (steamLoginUrl)) {
    87                                 string host = (Web.IsSslRedirected (_req) ? "https://" : "http://") + _req.UserHostName;
     84                                string host = (Web.IsSslRedirected (_context.Request) ? "https://" : "http://") + _context.Request.UserHostName;
    8885                                string url = OpenID.GetOpenIdLoginUrl (host, host + urlBasePath + steamOpenIdVerifyUrl);
    89                                 _resp.Redirect (url);
     86                                _context.Response.Redirect (url);
    9087                                return;
    9188                        } else {
     
    9592                        result.Append (footer);
    9693
    97                         _resp.ContentType = MimeType.GetMimeType (".html");
    98                         _resp.ContentEncoding = Encoding.UTF8;
    99                         byte[] buf = Encoding.UTF8.GetBytes (result.ToString ());
    100                         _resp.ContentLength64 = buf.Length;
    101                         _resp.OutputStream.Write (buf, 0, buf.Length);
     94                        WebUtils.WriteText (_context.Response, result.ToString (), _mimeType: WebUtils.MimeHtml);
    10295                }
    10396        }
  • binary-improvements2/MapRendering/Web/Handlers/SimpleRedirectHandler.cs

    r383 r387  
    1 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    2 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    3 
    41namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
    52        public class SimpleRedirectHandler : AbsHandler {
     
    107                }
    118
    12                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    13                         int _permissionLevel) {
    14                         _resp.Redirect (target);
     9                public override void HandleRequest (RequestContext _context) {
     10                        _context.Response.Redirect (target);
    1511                }
    1612        }
  • binary-improvements2/MapRendering/Web/Handlers/StaticHandler.cs

    r382 r387  
    22using System.Net;
    33using AllocsFixes.FileCache;
    4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    64
    75namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
     
    1816                }
    1917
    20                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    21                         int _permissionLevel) {
    22                         string fn = _requestPath.Remove (0, urlBasePath.Length);
     18                public override void HandleRequest (RequestContext _context) {
     19                        string fn = _context.RequestPath.Remove (0, urlBasePath.Length);
    2320
    2421                        byte[] content = cache.GetFileContent (datapath + fn);
    2522
    2623                        if (content != null) {
    27                                 _resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn));
    28                                 _resp.ContentLength64 = content.Length;
    29                                 _resp.OutputStream.Write (content, 0, content.Length);
     24                                _context.Response.ContentType = MimeType.GetMimeType (Path.GetExtension (fn));
     25                                _context.Response.ContentLength64 = content.Length;
     26                                _context.Response.OutputStream.Write (content, 0, content.Length);
    3027                        } else {
    31                                 _resp.StatusCode = (int) HttpStatusCode.NotFound;
     28                                _context.Response.StatusCode = (int) HttpStatusCode.NotFound;
    3229                                if (logMissingFiles) {
    33                                         Log.Out ("Web:Static:FileNotFound: \"" + _requestPath + "\" @ \"" + datapath + fn + "\"");
     30                                        Log.Out ("Web:Static:FileNotFound: \"" + _context.RequestPath + "\" @ \"" + datapath + fn + "\"");
    3431                                }
    3532                        }
  • binary-improvements2/MapRendering/Web/Handlers/UserStatusHandler.cs

    r382 r387  
    11using AllocsFixes.JSON;
    2 using AllocsFixes.NetConnections.Servers.Web.API;
    3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
    4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
    52
    63namespace AllocsFixes.NetConnections.Servers.Web.Handlers {
     
    96                }
    107
    11                 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con,
    12                         int _permissionLevel) {
     8                public override void HandleRequest (RequestContext _context) {
    139                        JSONObject result = new JSONObject ();
    1410
    15                         result.Add ("loggedin", new JSONBoolean (_con != null));
    16                         result.Add ("username", new JSONString (_con != null ? _con.UserId.ToString () : string.Empty));
     11                        result.Add ("loggedin", new JSONBoolean (_context.Connection != null));
     12                        result.Add ("username", new JSONString (_context.Connection != null ? _context.Connection.UserId.ToString () : string.Empty));
    1713
    1814                        JSONArray perms = new JSONArray ();
     
    2016                                JSONObject permObj = new JSONObject ();
    2117                                permObj.Add ("module", new JSONString (perm.module));
    22                                 permObj.Add ("allowed", new JSONBoolean (perm.permissionLevel >= _permissionLevel));
     18                                permObj.Add ("allowed", new JSONBoolean (perm.permissionLevel >= _context.PermissionLevel));
    2319                                perms.Add (permObj);
    2420                        }
     
    2622                        result.Add ("permissions", perms);
    2723
    28                         WebAPI.WriteJSON (_resp, result);
     24                        WebUtils.WriteJson (_context.Response, result);
    2925                }
    3026        }
Note: See TracChangeset for help on using the changeset viewer.