source: binary-improvements2/WebServer/src/UrlHandlers/SessionHandler.cs@ 413

Last change on this file since 413 was 411, checked in by alloc, 21 months ago

SessionHandler refactoring for login reuse

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