Changeset 404 for binary-improvements2/WebServer
- Timestamp:
- Feb 16, 2023, 3:50:53 PM (22 months ago)
- Location:
- binary-improvements2/WebServer
- Files:
-
- 6 added
- 2 deleted
- 17 edited
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements2/WebServer/WebServer.csproj
r402 r404 43 43 </PropertyGroup> 44 44 <ItemGroup> 45 <Reference Include="0Harmony, Version=2.10.0.0, Culture=neutral, PublicKeyToken=null"> 46 <HintPath>..\7dtd-binaries\0Harmony.dll</HintPath> 47 <Private>False</Private> 48 </Reference> 45 49 <Reference Include="Assembly-CSharp-firstpass, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"> 46 50 <HintPath>..\7dtd-binaries\Assembly-CSharp-firstpass.dll</HintPath> … … 65 69 <Reference Include="System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 66 70 <HintPath>..\7dtd-binaries\System.Xml.dll</HintPath> 71 <Private>False</Private> 72 </Reference> 73 <Reference Include="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 74 <HintPath>..\7dtd-binaries\System.Xml.Linq.dll</HintPath> 67 75 <Private>False</Private> 68 76 </Reference> … … 93 101 </ItemGroup> 94 102 <ItemGroup> 103 <Compile Include="src\Commands\CreateWebUser.cs" /> 95 104 <Compile Include="src\FileCache\AbstractCache.cs" /> 96 105 <Compile Include="src\FileCache\DirectAccess.cs" /> … … 101 110 <Compile Include="src\LiveData\Hostiles.cs" /> 102 111 <Compile Include="src\ModApi.cs" /> 112 <Compile Include="src\Permissions\AdminWebModules.cs" /> 113 <Compile Include="src\Permissions\AdminApiTokens.cs" /> 114 <Compile Include="src\Permissions\AdminWebUsers.cs" /> 115 <Compile Include="src\Permissions\RegisterModules.cs" /> 103 116 <Compile Include="src\UrlHandlers\ApiHandler.cs" /> 104 117 <Compile Include="src\UrlHandlers\SseHandler.cs" /> … … 123 136 <Compile Include="src\AssemblyInfo.cs" /> 124 137 <Compile Include="src\Commands\EnableOpenIDDebug.cs" /> 125 <Compile Include="src\Commands\ReloadWebPermissions.cs" />126 138 <Compile Include="src\Commands\WebPermissionsCmd.cs" /> 127 139 <Compile Include="src\Commands\WebTokens.cs" /> … … 144 156 <Compile Include="src\WebConnection.cs" /> 145 157 <Compile Include="src\WebMod.cs" /> 146 <Compile Include="src\WebPermissions.cs" />147 158 <Compile Include="src\WebUtils.cs" /> 148 159 </ItemGroup> -
binary-improvements2/WebServer/src/Commands/WebPermissionsCmd.cs
r391 r404 1 1 using System.Collections.Generic; 2 2 using JetBrains.Annotations; 3 using Webserver.Permissions; 3 4 4 5 namespace Webserver.Commands { … … 44 45 } 45 46 46 if (! WebPermissions.Instance.IsKnownModule (_params [1])) {47 if (!AdminWebModules.Instance.IsKnownModule (_params [1])) { 47 48 SdtdConsole.Instance.Output ($"\"{_params [1]}\" is not a valid web function."); 48 49 return; … … 54 55 } 55 56 56 WebPermissions.Instance.AddModulePermission(_params [1], level);57 AdminWebModules.Instance.AddModule (_params [1], level); 57 58 SdtdConsole.Instance.Output ($"{_params [1]} added with permission level of {level}."); 58 59 } … … 64 65 } 65 66 66 if (! WebPermissions.Instance.IsKnownModule (_params [1])) {67 if (!AdminWebModules.Instance.IsKnownModule (_params [1])) { 67 68 SdtdConsole.Instance.Output ($"\"{_params [1]}\" is not a valid web function."); 68 69 return; 69 70 } 70 71 71 WebPermissions.Instance.RemoveModulePermission(_params [1]);72 AdminWebModules.Instance.RemoveModule (_params [1]); 72 73 SdtdConsole.Instance.Output ($"{_params [1]} removed from permissions list."); 73 74 } … … 76 77 SdtdConsole.Instance.Output ("Defined web function permissions:"); 77 78 SdtdConsole.Instance.Output (" Level: Web function"); 78 foreach (WebPermissions.WebModulePermission wmp in WebPermissions.Instance.GetModules ()) { 79 SdtdConsole.Instance.Output ($" {wmp.permissionLevel,5}: {wmp.module}"); 79 80 List<AdminWebModules.WebModule> wmps = AdminWebModules.Instance.GetModules (); 81 for (int i = 0; i < wmps.Count; i++) { 82 AdminWebModules.WebModule wmp = wmps [i]; 83 84 SdtdConsole.Instance.Output ($" {wmp.PermissionLevel,5}: {wmp.Name}"); 80 85 } 81 86 } -
binary-improvements2/WebServer/src/Commands/WebTokens.cs
r402 r404 2 2 using System.Text.RegularExpressions; 3 3 using JetBrains.Annotations; 4 using Webserver.Permissions; 4 5 5 6 namespace Webserver.Commands { … … 19 20 return "Set/get webtoken permission levels. A level of 0 is maximum permission.\n" + 20 21 "Usage:\n" + 21 " webtokens add < username> <usertoken> <level>\n" +22 " webtokens remove < username>\n" +22 " webtokens add <tokenname> <tokensecret> <level>\n" + 23 " webtokens remove <tokenname>\n" + 23 24 " webtokens list"; 24 25 } … … 47 48 48 49 if (string.IsNullOrEmpty (_params [1])) { 49 SdtdConsole.Instance.Output ("Argument ' username' is empty.");50 SdtdConsole.Instance.Output ("Argument 'tokenname' is empty."); 50 51 return; 51 52 } … … 53 54 if (!validNameTokenMatcher.IsMatch (_params [1])) { 54 55 SdtdConsole.Instance.Output ( 55 "Argument ' username' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_).");56 "Argument 'tokenname' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 56 57 return; 57 58 } 58 59 59 60 if (string.IsNullOrEmpty (_params [2])) { 60 SdtdConsole.Instance.Output ("Argument ' usertoken' is empty.");61 SdtdConsole.Instance.Output ("Argument 'tokensecret' is empty."); 61 62 return; 62 63 } … … 64 65 if (!validNameTokenMatcher.IsMatch (_params [2])) { 65 66 SdtdConsole.Instance.Output ( 66 "Argument ' usertoken' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_).");67 "Argument 'tokensecret' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 67 68 return; 68 69 } … … 73 74 } 74 75 75 WebPermissions.Instance.AddAdmin (_params [1], _params [2], level);76 SdtdConsole.Instance.Output ($"Web user with name={_params [1]} and password={_params [2]} added with permission level of {level}.");76 AdminApiTokens.Instance.AddToken (_params [1], _params [2], level); 77 SdtdConsole.Instance.Output ($"Web API token with name={_params [1]} and secret={_params [2]} added with permission level of {level}."); 77 78 } 78 79 … … 84 85 85 86 if (string.IsNullOrEmpty (_params [1])) { 86 SdtdConsole.Instance.Output ("Argument ' username' is empty.");87 SdtdConsole.Instance.Output ("Argument 'tokenname' is empty."); 87 88 return; 88 89 } … … 90 91 if (!validNameTokenMatcher.IsMatch (_params [1])) { 91 92 SdtdConsole.Instance.Output ( 92 "Argument ' username' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_).");93 "Argument 'tokenname' may only contain characters (A-Z, a-z), digits (0-9) and underscores (_)."); 93 94 return; 94 95 } 95 96 96 WebPermissions.Instance.RemoveAdmin (_params [1]);97 SdtdConsole.Instance.Output ($"{_params [1]} removed from web userpermissions list.");97 AdminApiTokens.Instance.RemoveToken (_params [1]); 98 SdtdConsole.Instance.Output ($"{_params [1]} removed from web API token permissions list."); 98 99 } 99 100 100 101 private void ExecuteList () { 101 SdtdConsole.Instance.Output ("Defined web userpermissions:");102 SdtdConsole.Instance.Output (" Level: Name / Token");103 foreach ( WebPermissions.AdminToken at in WebPermissions.Instance.GetAdmins ()) {104 SdtdConsole.Instance.Output ($" {a t.permissionLevel,5}: {at.name} / {at.token}");102 SdtdConsole.Instance.Output ("Defined web API token permissions:"); 103 SdtdConsole.Instance.Output (" Level: Name / Secret"); 104 foreach ((string _, AdminApiTokens.ApiToken apiToken) in AdminApiTokens.Instance.GetTokens ()) { 105 SdtdConsole.Instance.Output ($" {apiToken.PermissionLevel,5}: {apiToken.Name} / {apiToken.Secret}"); 105 106 } 106 107 } -
binary-improvements2/WebServer/src/ConnectionHandler.cs
r402 r404 31 31 } 32 32 33 public WebConnection LogIn ( PlatformUserIdentifierAbs _userId, IPAddress _ip) {33 public WebConnection LogIn (IPAddress _ip, string _username, PlatformUserIdentifierAbs _userId, PlatformUserIdentifierAbs _crossUserId = null) { 34 34 string sessionId = Guid.NewGuid ().ToString (); 35 WebConnection con = new WebConnection (sessionId, _ip, _user Id);35 WebConnection con = new WebConnection (sessionId, _ip, _username, _userId, _crossUserId); 36 36 connections.Add (sessionId, con); 37 37 return con; -
binary-improvements2/WebServer/src/ModApi.cs
r391 r404 1 using System.Reflection; 2 using HarmonyLib; 1 3 using JetBrains.Annotations; 2 4 using Webserver.UrlHandlers; … … 12 14 ModEvents.GameShutdown.RegisterHandler (GameShutdown); 13 15 modInstance = _modInstance; 16 17 Harmony.CreateAndPatchAll (Assembly.GetExecutingAssembly ()); 14 18 } 15 19 -
binary-improvements2/WebServer/src/UrlHandlers/AbsHandler.cs
r391 r404 1 using Webserver.Permissions; 2 1 3 namespace Webserver.UrlHandlers { 2 4 public abstract class AbsHandler { … … 10 12 protected AbsHandler (string _moduleName, int _defaultPermissionLevel = 0) { 11 13 moduleName = _moduleName; 12 WebPermissions.Instance.AddKnownModule (_moduleName, _defaultPermissionLevel);14 AdminWebModules.Instance.AddKnownModule (_moduleName, _defaultPermissionLevel); 13 15 } 14 16 … … 16 18 17 19 public virtual bool IsAuthorizedForHandler (WebConnection _user, int _permissionLevel) { 18 return moduleName == null || WebPermissions.Instance.ModuleAllowedWithLevel (moduleName, _permissionLevel);20 return moduleName == null || AdminWebModules.Instance.ModuleAllowedWithLevel (moduleName, _permissionLevel); 19 21 } 20 22 -
binary-improvements2/WebServer/src/UrlHandlers/ApiHandler.cs
r402 r404 3 3 using System.Net; 4 4 using System.Reflection; 5 using Webserver.Permissions; 5 6 using Webserver.WebAPI; 6 7 … … 10 11 11 12 public ApiHandler () : base (null) { 12 13 13 } 14 15 private static readonly Type[] apiWithParentCtorTypes = { typeof (Web) }; 16 private static readonly object[] apiWithParentCtorArgs = new object[1]; 17 private static readonly Type[] apiEmptyCtorTypes = { }; 18 private static readonly object[] apiEmptyCtorArgs = { }; 14 19 15 20 public override void SetBasePathAndParent (Web _parent, string _relativePath) { 16 21 base.SetBasePathAndParent (_parent, _relativePath); 17 22 18 Type[] apiWithParentCtorTypes = { typeof (Web) }; 19 object[] apiWithParentCtorArgs = { _parent }; 23 apiWithParentCtorArgs[0] = _parent; 20 24 21 Type[] apiEmptyCtorTypes = { }; 22 object[] apiEmptyCtorArgs = { }; 23 24 25 ReflectionHelpers.FindTypesImplementingBase (typeof (AbsWebAPI), _type => { 26 ConstructorInfo ctor = _type.GetConstructor (apiWithParentCtorTypes); 27 if (ctor != null) { 28 AbsWebAPI apiInstance = (AbsWebAPI) ctor.Invoke (apiWithParentCtorArgs); 29 addApi (apiInstance); 30 return; 31 } 32 33 ctor = _type.GetConstructor (apiEmptyCtorTypes); 34 if (ctor != null) { 35 AbsWebAPI apiInstance = (AbsWebAPI) ctor.Invoke (apiEmptyCtorArgs); 36 addApi (apiInstance); 37 } 38 }); 25 ReflectionHelpers.FindTypesImplementingBase (typeof (AbsWebAPI), apiFoundCallback); 39 26 40 27 // Permissions that don't map to a real API … … 43 30 } 44 31 32 private void apiFoundCallback (Type _type) { 33 ConstructorInfo ctor = _type.GetConstructor (apiWithParentCtorTypes); 34 if (ctor != null) { 35 AbsWebAPI apiInstance = (AbsWebAPI)ctor.Invoke (apiWithParentCtorArgs); 36 addApi (apiInstance); 37 return; 38 } 39 40 ctor = _type.GetConstructor (apiEmptyCtorTypes); 41 if (ctor != null) { 42 AbsWebAPI apiInstance = (AbsWebAPI)ctor.Invoke (apiEmptyCtorArgs); 43 addApi (apiInstance); 44 } 45 } 46 45 47 private void addApi (AbsWebAPI _api) { 46 48 apis.Add (_api.Name, _api); 47 WebPermissions.Instance.AddKnownModule ($"webapi.{_api.Name}", _api.DefaultPermissionLevel ());49 AdminWebModules.Instance.AddKnownModule ($"webapi.{_api.Name}", _api.DefaultPermissionLevel ()); 48 50 } 49 51 … … 92 94 93 95 private bool IsAuthorizedForApi (string _apiName, int _permissionLevel) { 94 return WebPermissions.Instance.ModuleAllowedWithLevel ($"webapi.{_apiName}", _permissionLevel);96 return AdminWebModules.Instance.ModuleAllowedWithLevel ($"webapi.{_apiName}", _permissionLevel); 95 97 } 96 98 } -
binary-improvements2/WebServer/src/UrlHandlers/SessionHandler.cs
r402 r404 5 5 using Platform.Steam; 6 6 using Utf8Json; 7 using Webserver.Permissions; 7 8 8 9 namespace Webserver.UrlHandlers { … … 10 11 private const string pageBasePath = "/app"; 11 12 private const string pageErrorPath = "/app/error/"; 12 13 13 14 private const string steamOpenIdVerifyUrl = "verifysteamopenid"; 14 15 private const string steamLoginUrl = "loginsteam"; 16 private const string steamLoginFailedPage = "SteamLoginFailed"; 17 15 18 private const string userPassLoginUrl = "login"; 16 19 … … 29 32 string subpath = _context.RequestPath.Remove (0, urlBasePath.Length); 30 33 34 string remoteEndpointString = _context.Request.RemoteEndPoint!.ToString (); 35 31 36 if (subpath.StartsWith (steamOpenIdVerifyUrl)) { 32 HandleSteamVerification (_context );37 HandleSteamVerification (_context, remoteEndpointString); 33 38 return; 34 39 } … … 43 48 return; 44 49 } 45 50 46 51 if (subpath.StartsWith (userPassLoginUrl)) { 47 HandleUserPassLogin (_context );52 HandleUserPassLogin (_context, remoteEndpointString); 48 53 return; 49 54 } … … 52 57 } 53 58 54 private void HandleUserPassLogin (RequestContext _context ) {59 private void HandleUserPassLogin (RequestContext _context, string _remoteEndpointString) { 55 60 if (!_context.Request.HasEntityBody) { 56 61 _context.Response.Redirect (pageErrorPath + "NoLoginData"); … … 83 88 } 84 89 85 // TODO: Apply login90 AdminWebUsers.WebUser? webUser = AdminWebUsers.Instance.GetUser (username, password); 86 91 87 string remoteEndpointString = _context.Request.RemoteEndPoint!.ToString (); 88 89 if (username != "test" || password != "123") { 90 // TODO: failed login 91 Log.Out ($"[Web] User/pass login failed from {remoteEndpointString}"); 92 if (!webUser.HasValue) { 93 Log.Out ($"[Web] User/pass login failed from {_remoteEndpointString}"); 92 94 _context.Response.Redirect (pageErrorPath + "UserPassInvalid"); 93 95 return; 94 96 } 95 96 try {97 // TODO: Match username/password to UserIdentifierAbs / serveradmins.xml98 99 WebConnection con = connectionHandler.LogIn (new UserIdentifierSteam (76561198066968172ul), _context.Request.RemoteEndPoint.Address);100 int level = GameManager.Instance.adminTools.GetUserPermissionLevel (con.UserId);101 Log.Out ($"[Web] User/pass login from {remoteEndpointString} with ID {con.UserId}, permission level {level}");102 97 103 Cookie cookie = new Cookie ("sid", con.SessionID, "/") { 104 Expired = false, 105 Expires = DateTime.MinValue, 106 HttpOnly = true, 107 Secure = false 108 }; 109 _context.Response.AppendCookie (cookie); 110 _context.Response.Redirect (pageBasePath); 111 112 return; 113 } catch (Exception e) { 114 Log.Error ("[Web] Error during user/pass login:"); 115 Log.Exception (e); 116 } 117 118 _context.Response.Redirect (pageErrorPath + "UserPassLoginFailed"); 98 HandleUserIdLogin (_context, _remoteEndpointString, "user/pass", "UserPassLoginFailed", webUser.Value.Name, webUser.Value.PlatformUser, webUser.Value.CrossPlatformUser); 119 99 } 120 100 … … 140 120 } 141 121 142 private void HandleSteamVerification (RequestContext _context) { 143 string remoteEndpointString = _context.Request.RemoteEndPoint!.ToString (); 144 122 private void HandleSteamVerification (RequestContext _context, string _remoteEndpointString) { 123 ulong id; 145 124 try { 146 ulong id = OpenID.Validate (_context.Request); 147 if (id > 0) { 148 WebConnection con = connectionHandler.LogIn (new UserIdentifierSteam (id), _context.Request.RemoteEndPoint.Address); 149 int level = GameManager.Instance.adminTools.GetUserPermissionLevel (con.UserId); 150 Log.Out ($"[Web] Steam OpenID login from {remoteEndpointString} with ID {con.UserId}, permission level {level}"); 151 152 Cookie cookie = new Cookie ("sid", con.SessionID, "/") { 153 Expired = false, 154 Expires = DateTime.MinValue, 155 HttpOnly = true, 156 Secure = false 157 }; 158 _context.Response.AppendCookie (cookie); 159 _context.Response.Redirect (pageBasePath); 160 161 return; 162 } 125 id = OpenID.Validate (_context.Request); 163 126 } catch (Exception e) { 164 Log.Error ( "[Web] Error validating Steam login:");127 Log.Error ($"[Web] Error validating Steam login from {_remoteEndpointString}:"); 165 128 Log.Exception (e); 129 _context.Response.Redirect (pageErrorPath + steamLoginFailedPage); 130 return; 166 131 } 167 132 168 Log.Out ($"[Web] Steam OpenID login failed from {remoteEndpointString}"); 169 _context.Response.Redirect (pageErrorPath + "SteamLoginFailed"); 133 if (id <= 0) { 134 Log.Out ($"[Web] Steam OpenID login failed (invalid ID) from {_remoteEndpointString}"); 135 _context.Response.Redirect (pageErrorPath + steamLoginFailedPage); 136 return; 137 } 138 139 UserIdentifierSteam userId = new UserIdentifierSteam (id); 140 HandleUserIdLogin (_context, _remoteEndpointString, "Steam OpenID", steamLoginFailedPage, userId.ToString (), userId); 170 141 } 171 142 143 private void HandleUserIdLogin (RequestContext _context, string _remoteEndpointString, string _loginName, string _errorPage, string _username, 144 PlatformUserIdentifierAbs _userId, PlatformUserIdentifierAbs _crossUserId = null) { 145 try { 146 WebConnection con = connectionHandler.LogIn (_context.Request.RemoteEndPoint!.Address, _username, _userId, _crossUserId); 147 148 int level1 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_userId); 149 int level2 = int.MaxValue; 150 if (_crossUserId != null) { 151 level2 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_crossUserId); 152 } 153 154 int higherLevel = Math.Min (level1, level2); 155 156 Log.Out ($"[Web] {_loginName} login from {_remoteEndpointString}, name {_username} with ID {_userId}, CID {(_crossUserId != null ? _crossUserId : "none")}, permission level {higherLevel}"); 157 Cookie cookie = new Cookie ("sid", con.SessionID, "/") { 158 Expired = false, 159 Expires = DateTime.MinValue, 160 HttpOnly = true, 161 Secure = false 162 }; 163 _context.Response.AppendCookie (cookie); 164 _context.Response.Redirect (pageBasePath); 165 } catch (Exception e) { 166 Log.Error ($"[Web] Error during {_loginName} login:"); 167 Log.Exception (e); 168 _context.Response.Redirect (pageErrorPath + _errorPage); 169 } 170 } 172 171 } 173 172 } -
binary-improvements2/WebServer/src/UrlHandlers/SseHandler.cs
r402 r404 4 4 using System.Reflection; 5 5 using System.Threading; 6 using Webserver.Permissions; 6 7 using Webserver.SSE; 7 8 … … 17 18 private bool shutdown; 18 19 20 private static readonly Type[] ctorTypes = { typeof (SseHandler) }; 21 private static readonly object[] ctorParams = new object[1]; 22 19 23 public SseHandler (string _moduleName = null) : base (_moduleName) { 20 Type[] ctorTypes = { typeof (SseHandler) }; 21 object[] ctorParams = { this }; 24 ctorParams[0] = this; 22 25 23 foreach (Type t in Assembly.GetExecutingAssembly ().GetTypes ()) { 24 if (t.IsAbstract || !t.IsSubclassOf (typeof (AbsEvent))) { 25 continue; 26 } 26 ReflectionHelpers.FindTypesImplementingBase (typeof (AbsEvent), apiFoundCallback); 27 } 27 28 28 ConstructorInfo ctor = t.GetConstructor (ctorTypes); 29 if (ctor == null) { 30 continue; 31 } 29 private void apiFoundCallback (Type _type) { 30 ConstructorInfo ctor = _type.GetConstructor (ctorTypes); 31 if (ctor == null) { 32 return; 33 } 32 34 33 AbsEvent apiInstance = (AbsEvent)ctor.Invoke (ctorParams); 34 AddEvent (apiInstance.Name, apiInstance); 35 } 35 AbsEvent apiInstance = (AbsEvent)ctor.Invoke (ctorParams); 36 AddEvent (apiInstance.Name, apiInstance); 36 37 } 37 38 … … 52 53 public void AddEvent (string _eventName, AbsEvent _eventInstance) { 53 54 events.Add (_eventName, _eventInstance); 54 WebPermissions.Instance.AddKnownModule ($"webevent.{_eventName}", _eventInstance.DefaultPermissionLevel ());55 AdminWebModules.Instance.AddKnownModule ($"webevent.{_eventName}", _eventInstance.DefaultPermissionLevel ()); 55 56 } 56 57 … … 89 90 90 91 private bool IsAuthorizedForEvent (string _eventName, int _permissionLevel) { 91 return WebPermissions.Instance.ModuleAllowedWithLevel ($"webevent.{_eventName}", _permissionLevel);92 return AdminWebModules.Instance.ModuleAllowedWithLevel ($"webevent.{_eventName}", _permissionLevel); 92 93 } 93 94 -
binary-improvements2/WebServer/src/UrlHandlers/UserStatusHandler.cs
r402 r404 1 using System.Collections.Generic; 1 2 using Utf8Json; 3 using Webserver.Permissions; 2 4 3 5 namespace Webserver.UrlHandlers { … … 8 10 private static readonly byte[] jsonLoggedInKey = JsonWriter.GetEncodedPropertyNameWithBeginObject ("loggedIn"); 9 11 private static readonly byte[] jsonUsernameKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("username"); 12 private static readonly byte[] jsonPermissionLevelKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("permissionLevel"); 10 13 private static readonly byte[] jsonPermissionsKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("permissions"); 11 14 … … 20 23 21 24 writer.WriteRaw (jsonUsernameKey); 22 writer.WriteString (_context.Connection != null ? _context.Connection.UserId.ToString () : string.Empty); 25 writer.WriteString (_context.Connection != null ? _context.Connection.Username : string.Empty); 26 27 writer.WriteRaw (jsonPermissionLevelKey); 28 writer.WriteInt32 (_context.PermissionLevel); 23 29 24 30 writer.WriteRaw (jsonPermissionsKey); 25 31 writer.WriteBeginArray (); 26 32 27 bool first = true; 28 foreach (WebPermissions.WebModulePermission perm in WebPermissions.Instance.GetModules ()) { 29 if (!first) { 33 List<AdminWebModules.WebModule> list = AdminWebModules.Instance.GetModules (); 34 for (int i = 0; i < list.Count; i++) { 35 AdminWebModules.WebModule perm = list [i]; 36 37 if (i > 0) { 30 38 writer.WriteValueSeparator (); 31 39 } 32 40 33 first = false;34 35 41 writer.WriteRaw (jsonModuleKey); 36 writer.WriteString (perm. module);37 42 writer.WriteString (perm.Name); 43 38 44 writer.WriteRaw (jsonAllowedKey); 39 writer.WriteBoolean (perm. permissionLevel >= _context.PermissionLevel);40 45 writer.WriteBoolean (perm.PermissionLevel >= _context.PermissionLevel); 46 41 47 writer.WriteEndObject (); 42 48 } -
binary-improvements2/WebServer/src/Web.cs
r402 r404 6 6 using UnityEngine; 7 7 using Webserver.FileCache; 8 using Webserver.Permissions; 8 9 using Webserver.UrlHandlers; 9 10 using Cookie = System.Net.Cookie; … … 25 26 private readonly Version httpProtocolVersion = new Version(1, 1); 26 27 28 private readonly AsyncCallback handleRequestDelegate; 29 27 30 public Web (string _modInstancePath) { 28 31 try { … … 81 84 // listener.Prefixes.Add ($"http://[::1]:{webPort}/"); 82 85 listener.Start (); 83 listener.BeginGetContext (HandleRequest, listener); 86 handleRequestDelegate = HandleRequest; 87 listener.BeginGetContext (handleRequestDelegate, listener); 84 88 85 89 SdtdConsole.Instance.RegisterServer (this); … … 250 254 #if ENABLE_PROFILER 251 255 } finally { 252 listenerInstance.BeginGetContext ( HandleRequest, listenerInstance);256 listenerInstance.BeginGetContext (handleRequestDelegate, listenerInstance); 253 257 UnityEngine.Profiling.Profiler.EndThreadProfiling (); 254 258 } … … 297 301 _con = connectionHandler.IsLoggedIn (sessionId, reqRemoteEndPoint.Address); 298 302 if (_con != null) { 299 return GameManager.Instance.adminTools.GetUserPermissionLevel (_con.UserId); 300 } 301 } 302 303 if (_req.QueryString ["adminuser"] == null || _req.QueryString ["admintoken"] == null) { 303 int level1 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_con.UserId); 304 int level2 = int.MaxValue; 305 if (_con.CrossplatformUserId != null) { 306 level2 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_con.CrossplatformUserId); 307 } 308 309 return Math.Min (level1, level2); 310 } 311 } 312 313 if (!_req.Headers.TryGetValue ("X-SDTD-API-TOKENNAME", out string apiTokenName) || 314 !_req.Headers.TryGetValue ("X-SDTD-API-SECRET", out string apiTokenSecret)) { 304 315 return guestPermissionLevel; 305 316 } 306 317 307 WebPermissions.AdminToken admin = WebPermissions.Instance.GetWebAdmin (_req.QueryString ["adminuser"], 308 _req.QueryString ["admintoken"]); 309 if (admin != null) { 310 return admin.permissionLevel; 318 int adminLevel = AdminApiTokens.Instance.GetPermissionLevel (apiTokenName, apiTokenSecret); 319 if (adminLevel < int.MaxValue) { 320 return adminLevel; 311 321 } 312 322 -
binary-improvements2/WebServer/src/WebAPI/APIs/Command.cs
r402 r404 25 25 26 26 if (string.IsNullOrEmpty (id)) { 27 bool first = true; 28 foreach (IConsoleCommand cc in SdtdConsole.Instance.GetCommands ()) { 29 if (!first) { 27 IList<IConsoleCommand> ccs = SdtdConsole.Instance.GetCommands (); 28 for (int i = 0; i < ccs.Count; i++) { 29 IConsoleCommand cc = ccs [i]; 30 31 if (i > 0) { 30 32 writer.WriteValueSeparator (); 31 33 } 32 33 first = false;34 34 35 35 writeCommandJson (ref writer, cc, permissionLevel); … … 81 81 _writer.WriteString (_command.GetHelp ()); 82 82 83 int commandPermissionLevel = GameManager.Instance.adminTools. GetCommandPermissionLevel (_command.GetCommands ());83 int commandPermissionLevel = GameManager.Instance.adminTools.Commands.GetCommandPermissionLevel (_command.GetCommands ()); 84 84 _writer.WriteRaw (jsonAllowedKey); 85 85 _writer.WriteBoolean (_userPermissionLevel <= commandPermissionLevel); … … 117 117 } 118 118 119 int commandPermissionLevel = GameManager.Instance.adminTools. GetCommandPermissionLevel (command.GetCommands ());119 int commandPermissionLevel = GameManager.Instance.adminTools.Commands.GetCommandPermissionLevel (command.GetCommands ()); 120 120 121 121 if (_context.PermissionLevel > commandPermissionLevel) { -
binary-improvements2/WebServer/src/WebAPI/APIs/ServerInfo.cs
r402 r404 1 using System.Collections.Generic; 1 2 using JetBrains.Annotations; 2 3 using Utf8Json; … … 22 23 GameServerInfo gsi = ConnectionManager.Instance.LocalServerInfo; 23 24 24 bool first = true;25 26 25 IList<GameInfoString> list = EnumUtils.Values<GameInfoString> (); 26 for (int i = 0; i < list.Count; i++) { 27 GameInfoString stringGamePref = list [i]; 27 28 28 foreach (GameInfoString stringGamePref in EnumUtils.Values<GameInfoString> ()) { 29 string value = gsi.GetValue (stringGamePref); 30 31 if (!first) { 29 if (i > 0) { 32 30 writer.WriteValueSeparator (); 33 31 } 34 32 35 first = false;36 37 33 writer.WriteString (stringGamePref.ToStringCached ()); 38 34 writer.WriteNameSeparator (); 39 35 40 36 writer.WriteRaw (keyType); 41 37 writer.WriteString ("string"); 42 38 43 39 writer.WriteRaw (keyValue); 44 writer.WriteString ( value);45 40 writer.WriteString (gsi.GetValue (stringGamePref)); 41 46 42 writer.WriteEndObject (); 47 43 } 48 44 49 foreach (GameInfoInt intGamePref in EnumUtils.Values<GameInfoInt> ()) { 50 int value = gsi.GetValue (intGamePref); 45 IList<GameInfoInt> ints = EnumUtils.Values<GameInfoInt> (); 46 for (int i = 0; i < ints.Count; i++) { 47 GameInfoInt intGamePref = ints [i]; 51 48 52 if ( !first) {49 if (i > 0) { 53 50 writer.WriteValueSeparator (); 54 51 } 55 52 56 first = false;57 58 53 writer.WriteString (intGamePref.ToStringCached ()); 59 54 writer.WriteNameSeparator (); 60 55 61 56 writer.WriteRaw (keyType); 62 57 writer.WriteString ("int"); 63 58 64 59 writer.WriteRaw (keyValue); 65 writer.WriteInt32 ( value);66 60 writer.WriteInt32 (gsi.GetValue (intGamePref)); 61 67 62 writer.WriteEndObject (); 68 63 } 69 64 70 foreach (GameInfoBool boolGamePref in EnumUtils.Values<GameInfoBool> ()) { 71 bool value = gsi.GetValue (boolGamePref); 65 IList<GameInfoBool> prefs = EnumUtils.Values<GameInfoBool> (); 66 for (int i = 0; i < prefs.Count; i++) { 67 GameInfoBool boolGamePref = prefs [i]; 72 68 73 if ( !first) {69 if (i > 0) { 74 70 writer.WriteValueSeparator (); 75 71 } 76 72 77 first = false;78 79 73 writer.WriteString (boolGamePref.ToStringCached ()); 80 74 writer.WriteNameSeparator (); 81 75 82 76 writer.WriteRaw (keyType); 83 77 writer.WriteString ("bool"); 84 78 85 79 writer.WriteRaw (keyValue); 86 writer.WriteBoolean ( value);87 80 writer.WriteBoolean (gsi.GetValue (boolGamePref)); 81 88 82 writer.WriteEndObject (); 89 83 } 90 84 91 85 writer.WriteEndObject (); 92 86 -
binary-improvements2/WebServer/src/WebAPI/AbsRestApi.cs
r402 r404 95 95 } 96 96 97 protected void SendErrorResult (RequestContext _context, HttpStatusCode _statusCode, byte[] _jsonInputData = null, string _errorCode = null, Exception _exception = null) {98 PrepareEnvelopedResult (out JsonWriter writer);99 writer.WriteRaw (JsonEmptyData);100 SendEnvelopedResult (_context, ref writer, _statusCode, _jsonInputData, _errorCode, _exception);101 }102 103 97 static AbsRestApi () { 104 98 JsonWriter writer = new JsonWriter (); … … 108 102 } 109 103 104 protected virtual void HandleRestGet (RequestContext _context) { 105 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, null, "Unsupported"); 106 } 107 108 protected virtual void HandleRestPost (RequestContext _context, IDictionary<string, object> _jsonInput, byte[] _jsonInputData) { 109 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, _jsonInputData, "Unsupported"); 110 } 111 112 protected virtual void HandleRestPut (RequestContext _context, IDictionary<string, object> _jsonInput, byte[] _jsonInputData) { 113 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, _jsonInputData, "Unsupported"); 114 } 115 116 protected virtual void HandleRestDelete (RequestContext _context) { 117 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, null, "Unsupported"); 118 } 119 120 121 #region Helpers 122 110 123 protected static readonly byte[] JsonEmptyData; 111 124 112 protected void PrepareEnvelopedResult (out JsonWriter _writer) {125 protected static void PrepareEnvelopedResult (out JsonWriter _writer) { 113 126 WebUtils.PrepareEnvelopedResult (out _writer); 114 127 } 115 128 116 protected void SendEnvelopedResult (RequestContext _context, ref JsonWriter _writer, HttpStatusCode _statusCode = HttpStatusCode.OK,129 protected static void SendEnvelopedResult (RequestContext _context, ref JsonWriter _writer, HttpStatusCode _statusCode = HttpStatusCode.OK, 117 130 byte[] _jsonInputData = null, string _errorCode = null, Exception _exception = null) { 118 131 … … 120 133 } 121 134 122 protected bool TryGetJsonField (IDictionary<string, object> _jsonObject, string _fieldName, out int _value) { 135 protected static void SendErrorResult (RequestContext _context, HttpStatusCode _statusCode, byte[] _jsonInputData = null, string _errorCode = null, Exception _exception = null) { 136 PrepareEnvelopedResult (out JsonWriter writer); 137 writer.WriteRaw (JsonEmptyData); 138 SendEnvelopedResult (_context, ref writer, _statusCode, _jsonInputData, _errorCode, _exception); 139 } 140 141 protected static bool TryGetJsonField (IDictionary<string, object> _jsonObject, string _fieldName, out int _value) { 123 142 _value = default; 124 143 … … 139 158 } 140 159 141 protected bool TryGetJsonField (IDictionary<string, object> _jsonObject, string _fieldName, out double _value) {160 protected static bool TryGetJsonField (IDictionary<string, object> _jsonObject, string _fieldName, out double _value) { 142 161 _value = default; 143 162 … … 158 177 } 159 178 160 protected bool TryGetJsonField (IDictionary<string, object> _jsonObject, string _fieldName, out string _value) {179 protected static bool TryGetJsonField (IDictionary<string, object> _jsonObject, string _fieldName, out string _value) { 161 180 _value = default; 162 181 … … 176 195 } 177 196 } 178 179 protected virtual void HandleRestGet (RequestContext _context) { 180 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, null, "Unsupported"); 181 } 182 183 protected virtual void HandleRestPost (RequestContext _context, IDictionary<string, object> _jsonInput, byte[] _jsonInputData) { 184 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, _jsonInputData, "Unsupported"); 185 } 186 187 protected virtual void HandleRestPut (RequestContext _context, IDictionary<string, object> _jsonInput, byte[] _jsonInputData) { 188 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, _jsonInputData, "Unsupported"); 189 } 190 191 protected virtual void HandleRestDelete (RequestContext _context) { 192 SendErrorResult (_context, HttpStatusCode.MethodNotAllowed, null, "Unsupported"); 193 } 197 198 199 #endregion 194 200 } 195 201 } -
binary-improvements2/WebServer/src/WebAPI/Null.cs
r391 r404 1 using System.Text; 1 using System; 2 using System.Text; 2 3 3 4 namespace Webserver.WebAPI { … … 10 11 _context.Response.ContentType = "text/plain"; 11 12 _context.Response.ContentEncoding = Encoding.ASCII; 12 _context.Response.OutputStream.Write ( new byte[] { }, 0, 0);13 _context.Response.OutputStream.Write (Array.Empty<byte> (), 0, 0); 13 14 } 14 15 } -
binary-improvements2/WebServer/src/WebConnection.cs
r402 r404 3 3 using System.Net; 4 4 using UnityEngine; 5 using Webserver.Permissions; 5 6 6 7 namespace Webserver { … … 15 16 public IPAddress Endpoint { get; } 16 17 18 public string Username { get; } 17 19 public PlatformUserIdentifierAbs UserId { get; } 20 public PlatformUserIdentifierAbs CrossplatformUserId { get; } 18 21 19 22 public TimeSpan Age => DateTime.Now - lastAction; 20 23 21 public WebConnection (string _sessionId, IPAddress _endpoint, PlatformUserIdentifierAbs _userId) {24 public WebConnection (string _sessionId, IPAddress _endpoint, string _username, PlatformUserIdentifierAbs _userId, PlatformUserIdentifierAbs _crossUserId = null) { 22 25 SessionID = _sessionId; 23 26 Endpoint = _endpoint; 27 Username = _username; 24 28 UserId = _userId; 29 CrossplatformUserId = _crossUserId; 25 30 login = DateTime.Now; 26 31 lastAction = login; … … 29 34 30 35 public static bool CanViewAllPlayers (int _permissionLevel) { 31 return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi.viewallplayers", _permissionLevel);36 return AdminWebModules.Instance.ModuleAllowedWithLevel ("webapi.viewallplayers", _permissionLevel); 32 37 } 33 38 34 39 public static bool CanViewAllClaims (int _permissionLevel) { 35 return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi.viewallclaims", _permissionLevel);40 return AdminWebModules.Instance.ModuleAllowedWithLevel ("webapi.viewallclaims", _permissionLevel); 36 41 } 37 42 -
binary-improvements2/WebServer/src/WebUtils.cs
r402 r404 1 1 using System; 2 using System.Collections.Specialized; 2 3 using System.Diagnostics.CodeAnalysis; 3 4 using System.Net; … … 110 111 WriteJsonData (_context.Response, ref _writer, _statusCode); 111 112 } 113 114 public static bool TryGetValue (this NameValueCollection _nameValueCollection, string _name, out string _result) { 115 _result = _nameValueCollection [_name]; 116 return _result != null; 117 } 112 118 } 113 119 }
Note:
See TracChangeset
for help on using the changeset viewer.