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

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