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

Last change on this file since 487 was 487, checked in by alloc, 5 months ago

1.1.0.1 Release for V 1.0

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