using System; using System.IO; using System.Net; using System.Text; namespace Webserver.UrlHandlers { public class SessionHandler : AbsHandler { private const string pageBasePath = "/"; private const string steamOpenIdVerifyUrl = "verifysteamopenid"; private const string steamLoginUrl = "loginsteam"; private readonly string footer = ""; private readonly string header = ""; private readonly ConnectionHandler connectionHandler; public SessionHandler (string _dataFolder, ConnectionHandler _connectionHandler) : base (null) { connectionHandler = _connectionHandler; if (File.Exists (_dataFolder + "/sessionheader.tmpl")) { header = File.ReadAllText (_dataFolder + "/sessionheader.tmpl"); } if (File.Exists (_dataFolder + "/sessionfooter.tmpl")) { footer = File.ReadAllText (_dataFolder + "/sessionfooter.tmpl"); } } public override void HandleRequest (RequestContext _context) { IPEndPoint reqRemoteEndPoint = _context.Request.RemoteEndPoint; if (reqRemoteEndPoint == null) { _context.Response.Redirect (pageBasePath); return; } string subpath = _context.RequestPath.Remove (0, urlBasePath.Length); StringBuilder result = new StringBuilder (); result.Append (header); if (subpath.StartsWith (steamOpenIdVerifyUrl)) { string remoteEndpointString = reqRemoteEndPoint.ToString (); try { ulong id = OpenID.Validate (_context.Request); if (id > 0) { WebConnection con = connectionHandler.LogIn (id, reqRemoteEndPoint.Address); int level = GameManager.Instance.adminTools.GetUserPermissionLevel (con.UserId); Log.Out ("Steam OpenID login from {0} with ID {1}, permission level {2}", remoteEndpointString, con.UserId, level); Cookie cookie = new Cookie ("sid", con.SessionID, "/") { Expired = false, Expires = DateTime.MinValue, HttpOnly = true, Secure = false }; _context.Response.AppendCookie (cookie); _context.Response.Redirect (pageBasePath); return; } } catch (Exception e) { Log.Error ("Error validating login:"); Log.Exception (e); } Log.Out ($"Steam OpenID login failed from {remoteEndpointString}"); result.Append ($"

Login failed, click to return to main page.

"); } else if (subpath.StartsWith ("logout")) { if (_context.Connection != null) { connectionHandler.LogOut (_context.Connection.SessionID); Cookie cookie = new Cookie ("sid", "", "/") { Expired = true }; _context.Response.AppendCookie (cookie); _context.Response.Redirect (pageBasePath); return; } result.Append ($"

Not logged in, click to return to main page.

"); } else if (subpath.StartsWith (steamLoginUrl)) { string host = (WebUtils.IsSslRedirected (_context.Request) ? "https://" : "http://") + _context.Request.UserHostName; string url = OpenID.GetOpenIdLoginUrl (host, host + urlBasePath + steamOpenIdVerifyUrl); _context.Response.Redirect (url); return; } else { result.Append ($"

Unknown command, click to return to main page.

"); } result.Append (footer); WebUtils.WriteText (_context.Response, result.ToString (), _mimeType: WebUtils.MimeHtml); } } }