Files
Shogi/Gameboard.ShogiUI.Sockets/Managers/SocketConnectionManager.cs
2020-12-13 14:27:36 -06:00

45 lines
1.3 KiB
C#

using Microsoft.AspNetCore.Http;
using System;
using System.Net;
using System.Threading.Tasks;
namespace Websockets.Managers
{
public interface ISocketConnectionManager
{
Task HandleSocketRequest(HttpContext context);
}
public class SocketConnectionManager : ISocketConnectionManager
{
private readonly ISocketCommunicationManager communicationManager;
private readonly ISocketTokenManager tokenManager;
public SocketConnectionManager(ISocketCommunicationManager communicationManager, ISocketTokenManager tokenManager) : base()
{
this.communicationManager = communicationManager;
this.tokenManager = tokenManager;
}
public async Task HandleSocketRequest(HttpContext context)
{
var hasToken = context.Request.Query.Keys.Contains("token");
if (hasToken)
{
var oneTimeToken = context.Request.Query["token"][0];
var tokenAsGuid = Guid.Parse(oneTimeToken);
var userName = tokenManager.GetUsername(tokenAsGuid);
if (!string.IsNullOrEmpty(userName))
{
var socket = await context.WebSockets.AcceptWebSocketAsync();
await communicationManager.CommunicateWith(socket, userName);
return;
}
}
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
}
}