PlotDirector/PlotLine/Hubs/NativeAgentCommandHub.cs

24 lines
1.5 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Hubs;
// Native bearer only. No client methods, command delivery, acknowledgement or client-chosen groups.
[Authorize(AuthenticationSchemes=DesktopPairing.Scheme)]
public sealed class NativeAgentCommandHub(NativeAgentConnections connections):Hub
{
public override async Task OnConnectedAsync()
{
var principal=Context.User!;
if(!int.TryParse(principal.FindFirstValue(ClaimTypes.NameIdentifier),out var user)||!Guid.TryParse(principal.FindFirstValue("PlotLine.SecurityStamp"),out var stamp)||
principal.FindFirstValue("NativeCompanion.Grant") is not {Length:>0} grant||!DateTimeOffset.TryParse(principal.FindFirstValue("NativeCompanion.Expires"),out var expires)){Context.Abort();return;}
Guid? Id(string claim)=>Guid.TryParse(principal.FindFirstValue(claim),out var id)?id:null;
if(!connections.Add(new(Context.ConnectionId,user,stamp,grant,Id("NativeCompanion.Installation"),Id("NativeCompanion.Connection"),expires,Context.Abort))){Context.Abort();return;}
try{await Groups.AddToGroupAsync(Context.ConnectionId,NativeAgentConnections.Group(user,grant),Context.ConnectionAborted);await base.OnConnectedAsync();}
catch{connections.Remove(Context.ConnectionId);throw;}
}
public override Task OnDisconnectedAsync(Exception? exception){connections.Remove(Context.ConnectionId);return base.OnDisconnectedAsync(exception);}
}