source: TFP-WebServer/WebServer/src/UrlHandlers/SessionHandler.cs@ 479

Last change on this file since 479 was 457, checked in by alloc, 16 months ago

Refactored APIs GamePrefs, GameStats, ServerInfo: Using arrays as result instead of objects, code sharing

File size: 6.6 KB
RevLine 
[391]1using System;
[402]2using System.Collections.Generic;
3using System.IO;
[391]4using System.Net;
[402]5using Platform.Steam;
6using Utf8Json;
[404]7using Webserver.Permissions;
[391]8
9namespace Webserver.UrlHandlers {
10 public class SessionHandler : AbsHandler {
[453]11
[394]12 private const string pageBasePath = "/app";
13 private const string pageErrorPath = "/app/error/";
[404]14
[391]15 private const string steamOpenIdVerifyUrl = "verifysteamopenid";
16 private const string steamLoginUrl = "loginsteam";
[453]17 private const string steamLoginName = "Steam OpenID";
[404]18 private const string steamLoginFailedPage = "SteamLoginFailed";
19
[402]20 private const string userPassLoginUrl = "login";
[417]21 public const string userPassLoginName = "User/pass";
[453]22 private const string userPassErrorPage = "UserPassLoginFailed";
[391]23
[453]24 public SessionHandler () : base (null) {
[391]25 }
26 public override void HandleRequest (RequestContext _context) {
[394]27 if (_context.Request.RemoteEndPoint == null) {
[453]28 WebUtils.WriteText (_context.Response, "NoRemoteEndpoint", HttpStatusCode.BadRequest);
[391]29 return;
30 }
31
32 string subpath = _context.RequestPath.Remove (0, urlBasePath.Length);
33
[404]34 string remoteEndpointString = _context.Request.RemoteEndPoint!.ToString ();
35
[391]36 if (subpath.StartsWith (steamOpenIdVerifyUrl)) {
[453]37 if (HandleSteamVerification (parent.ConnectionHandler, _context, remoteEndpointString)) {
38 _context.Response.Redirect (pageBasePath);
39 } else {
40 _context.Response.Redirect (pageErrorPath + steamLoginFailedPage);
41 }
[394]42 return;
43 }
[391]44
[394]45 if (subpath.StartsWith ("logout")) {
[453]46 HandleLogout (parent.ConnectionHandler, _context, pageBasePath);
[394]47 return;
48 }
[391]49
[394]50 if (subpath.StartsWith (steamLoginUrl)) {
[453]51 HandleSteamLogin (_context, $"{urlBasePath}{steamOpenIdVerifyUrl}");
[394]52 return;
53 }
[404]54
[402]55 if (subpath.StartsWith (userPassLoginUrl)) {
[453]56 HandleUserPassLogin (parent.ConnectionHandler, _context, remoteEndpointString);
[402]57 return;
58 }
[391]59
[453]60 WebUtils.WriteText (_context.Response, "InvalidSessionsCommand", HttpStatusCode.BadRequest);
[394]61 }
62
[453]63 public static bool HandleUserPassLogin (ConnectionHandler _connectionHandler, RequestContext _context, string _remoteEndpointString) {
[402]64 if (!_context.Request.HasEntityBody) {
[422]65 WebUtils.WriteText (_context.Response, "NoLoginData", HttpStatusCode.BadRequest);
[453]66 return false;
[402]67 }
68
69 Stream requestInputStream = _context.Request.InputStream;
70
71 byte[] jsonInputData = new byte[_context.Request.ContentLength64];
72 requestInputStream.Read (jsonInputData, 0, (int)_context.Request.ContentLength64);
73
74 IDictionary<string, object> inputJson;
75 try {
76 inputJson = JsonSerializer.Deserialize<IDictionary<string, object>> (jsonInputData);
77 } catch (Exception e) {
78 Log.Error ("Error deserializing JSON from user/password login:");
79 Log.Exception (e);
[422]80 WebUtils.WriteText (_context.Response, "InvalidLoginJson", HttpStatusCode.BadRequest);
[453]81 return false;
[402]82 }
83
84 if (!inputJson.TryGetValue ("username", out object fieldNode) || fieldNode is not string username) {
[422]85 WebUtils.WriteText (_context.Response, "InvalidLoginJson", HttpStatusCode.BadRequest);
[453]86 return false;
[402]87 }
88
89 if (!inputJson.TryGetValue ("password", out fieldNode) || fieldNode is not string password) {
[422]90 WebUtils.WriteText (_context.Response, "InvalidLoginJson", HttpStatusCode.BadRequest);
[453]91 return false;
[402]92 }
93
[433]94 if (!AdminWebUsers.Instance.TryGetUser (username, password, out AdminWebUsers.WebUser webUser)) {
[453]95 WebUtils.WriteText (_context.Response, "UserPassInvalid", HttpStatusCode.Unauthorized);
[404]96 Log.Out ($"[Web] User/pass login failed from {_remoteEndpointString}");
[453]97 return false;
[402]98 }
99
[457]100 bool loginResult = HandleUserIdLogin (_connectionHandler, _context, _remoteEndpointString, userPassLoginName, webUser.Name, webUser.PlatformUser, webUser.CrossPlatformUser);
[453]101 if (loginResult) {
102 WebUtils.WriteText (_context.Response, "");
103 } else {
104 WebUtils.WriteText (_context.Response, "LoginError", HttpStatusCode.InternalServerError);
105 }
106
107 return loginResult;
[402]108 }
109
[453]110 public static void HandleSteamLogin (RequestContext _context, string _verificationCallbackUrl) {
[402]111 string host = $"{(WebUtils.IsSslRedirected (_context.Request) ? "https://" : "http://")}{_context.Request.UserHostName}";
[453]112 string url = OpenID.GetOpenIdLoginUrl (host, $"{host}{_verificationCallbackUrl}");
[394]113 _context.Response.Redirect (url);
114 }
115
[453]116 public static bool HandleLogout (ConnectionHandler _connectionHandler, RequestContext _context, string _pageBase) {
[394]117 Cookie cookie = new Cookie ("sid", "", "/") {
118 Expired = true
119 };
120 _context.Response.AppendCookie (cookie);
121
122 if (_context.Connection == null) {
[453]123 _context.Response.Redirect (_pageBase);
124 return false;
[394]125 }
126
[453]127 _connectionHandler.LogOut (_context.Connection.SessionID);
128 _context.Response.Redirect (_pageBase);
129 return true;
[394]130 }
131
[453]132 public static bool HandleSteamVerification (ConnectionHandler _connectionHandler, RequestContext _context, string _remoteEndpointString) {
[404]133 ulong id;
134 try {
135 id = OpenID.Validate (_context.Request);
136 } catch (Exception e) {
137 Log.Error ($"[Web] Error validating Steam login from {_remoteEndpointString}:");
138 Log.Exception (e);
[453]139 return false;
[404]140 }
[394]141
[404]142 if (id <= 0) {
143 Log.Out ($"[Web] Steam OpenID login failed (invalid ID) from {_remoteEndpointString}");
[453]144 return false;
[404]145 }
146
147 UserIdentifierSteam userId = new UserIdentifierSteam (id);
[453]148 return HandleUserIdLogin (_connectionHandler, _context, _remoteEndpointString, steamLoginName, userId.ToString (), userId);
[404]149 }
150
[453]151 public static bool HandleUserIdLogin (ConnectionHandler _connectionHandler, RequestContext _context, string _remoteEndpointString,
152 string _loginName, string _username, PlatformUserIdentifierAbs _userId, PlatformUserIdentifierAbs _crossUserId = null) {
[394]153 try {
[411]154 WebConnection con = _connectionHandler.LogIn (_context.Request.RemoteEndPoint!.Address, _username, _userId, _crossUserId);
[394]155
[404]156 int level1 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_userId);
157 int level2 = int.MaxValue;
158 if (_crossUserId != null) {
159 level2 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_crossUserId);
160 }
[394]161
[404]162 int higherLevel = Math.Min (level1, level2);
163
[453]164 Log.Out ($"[Web] {_loginName} login from {_remoteEndpointString}, name {_username} with ID {_userId}, CID {(_crossUserId != null ? _crossUserId.ToString () : "none")}, permission level {higherLevel}");
[404]165 Cookie cookie = new Cookie ("sid", con.SessionID, "/") {
166 Expired = false,
167 Expires = DateTime.MinValue,
168 HttpOnly = true,
169 Secure = false
170 };
171 _context.Response.AppendCookie (cookie);
[417]172
[453]173 return true;
[394]174 } catch (Exception e) {
[404]175 Log.Error ($"[Web] Error during {_loginName} login:");
[394]176 Log.Exception (e);
[391]177 }
[453]178
179 return false;
[394]180 }
[453]181
[391]182 }
183}
Note: See TracBrowser for help on using the repository browser.