66 lines
2.7 KiB
C#
66 lines
2.7 KiB
C#
using HRM.BO;
|
|
using HRM.UI.Realtime.Jobs;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using System;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace HRM.UI.Realtime
|
|
{
|
|
/// <summary>
|
|
/// The application's single SignalR hub (/api/hubs/app). One connection per browser tab carries every real-time
|
|
/// feature; features are told apart by groups and topics, never by extra hubs.
|
|
///
|
|
/// Authentication is the app's normal JWT (the HttpOnly JWToken cookie, read in Startup's OnMessageReceived).
|
|
/// Clients never pick a group: the hub adds them, after checking their claims.
|
|
/// </summary>
|
|
[Authorize]
|
|
public class AppHub : Hub<IAppClient>
|
|
{
|
|
private readonly IJobRunner _jobRunner;
|
|
|
|
public AppHub(IJobRunner jobRunner)
|
|
{
|
|
_jobRunner = jobRunner;
|
|
}
|
|
|
|
public override async Task OnConnectedAsync()
|
|
{
|
|
CurrentUser user = CurrentUser.GetCurrentUser(Context.User);
|
|
if (user?.PayrollTypeID != null)
|
|
await Groups.AddToGroupAsync(Context.ConnectionId, RealtimeGroups.PayrollType(user.PayrollTypeID.Value));
|
|
await base.OnConnectedAsync();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Starts following a background job: answers its current state and from then on pushes every change as JobProgress.
|
|
/// Call it again after a reconnect (the browser does) - group membership does not survive a new connection.
|
|
/// </summary>
|
|
public async Task<JobSnapshot> SubscribeJob(string runId)
|
|
{
|
|
CurrentUser user = CurrentUser.GetCurrentUser(Context.User);
|
|
if (user == null)
|
|
throw new HubException("Not signed in.");
|
|
|
|
JobAccess access = _jobRunner.TryGet(runId, user.UserID, user.PayrollTypeID, out _);
|
|
if (access == JobAccess.NotFound)
|
|
throw new HubException("The job could not be found. The application may have restarted.");
|
|
if (access == JobAccess.Forbidden)
|
|
throw new HubException("You are not allowed to follow this job.");
|
|
|
|
await Groups.AddToGroupAsync(Context.ConnectionId, RealtimeGroups.Job(runId));
|
|
|
|
// Read the state only after joining the group, so no change can fall between the answer and the first push.
|
|
_jobRunner.TryGet(runId, user.UserID, user.PayrollTypeID, out JobSnapshot snapshot);
|
|
return snapshot;
|
|
}
|
|
|
|
public Task UnsubscribeJob(string runId)
|
|
{
|
|
if (string.IsNullOrEmpty(runId))
|
|
return Task.CompletedTask;
|
|
return Groups.RemoveFromGroupAsync(Context.ConnectionId, RealtimeGroups.Job(runId));
|
|
}
|
|
}
|
|
}
|