#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using ApplicationAuthorizationService = Lumina.Application.Common.Infrastructure.Authorization.IAuthorizationService;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Notifications;
///
/// SignalR hub for broadcasting the state of the scheduled jobs to the connected administrator clients.
///
[Authorize]
public class ScheduledJobsHub : Hub
{
///
/// Name of the group that holds the connections of the verified administrator clients.
///
public const string ADMINISTRATORS_GROUP = "Administrators";
private readonly IServiceScopeFactory _serviceScopeFactory;
///
/// Initializes a new instance of the class.
///
/// Injected factory used for creating scopes in which services are requested.
public ScheduledJobsHub(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
///
/// Verifies that the connecting client belongs to an administrator account, and rejects the connection otherwise.
///
/// A task that represents the asynchronous operation.
public override async Task OnConnectedAsync()
{
string? userIdClaim = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!Guid.TryParse(userIdClaim, out Guid userId) || !await IsAdministratorAsync(userId).ConfigureAwait(false))
{
Context.Abort();
return;
}
// The connection is added to the administrator group only after the role check succeeded, so the notifications, which are
// broadcast to that group, can never reach a client whose connection was not verified to belong to an administrator.
await Groups.AddToGroupAsync(Context.ConnectionId, ADMINISTRATORS_GROUP).ConfigureAwait(false);
await base.OnConnectedAsync().ConfigureAwait(false);
}
///
/// Determines whether the user identified by is an administrator.
///
/// The unique identifier of the user to check.
/// when the user is an administrator, otherwise.
private async Task IsAdministratorAsync(Guid userId)
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
ApplicationAuthorizationService authorizationService = scope.ServiceProvider.GetRequiredService();
return await authorizationService.IsInRoleAsync(userId, "Admin", CancellationToken.None).ConfigureAwait(false);
}
}