feat(security): enforcement — filtrage caméra dans les endpoints sensibles (#175)
This commit is contained in:
1 parent
0f47236c08
commit
b97d3bec11
24 files changed
+313
-25
No files matched your search
@@ -5,6 +5,7 @@ using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.CreateCamera;
|
||||
|
||||
public record CreateCameraCommand(
|
||||
Guid SiteId,
|
||||
string Name,
|
||||
|
||||
@@ -3,6 +3,7 @@ using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.DeleteCamera;
|
||||
|
||||
public record DeleteCameraCommand(Guid Id) : IRequest<ServiceResult>;
|
||||
public class DeleteCameraCommandHandler : IRequestHandler<DeleteCameraCommand, ServiceResult>
|
||||
{
|
||||
|
||||
+1
@@ -4,6 +4,7 @@ using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
namespace Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
|
||||
|
||||
public record ToggleCameraStatusCommand(Guid Id) : IRequest<ServiceResult<CameraResponse>>;
|
||||
public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStatusCommand, ServiceResult<CameraResponse>>
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
namespace Heimdall.Application.Cameras.Commands.UpdateCamera;
|
||||
|
||||
public record UpdateCameraCommand(
|
||||
Guid Id,
|
||||
string Name,
|
||||
|
||||
@@ -35,6 +35,7 @@ public interface IApplicationDbContext
|
||||
DbSet<StoragePolicy> StoragePolicies { get; }
|
||||
DbSet<UserGroup> UserGroups { get; }
|
||||
DbSet<UserRecoveryCode> UserRecoveryCodes { get; }
|
||||
DbSet<UserCamera> UserCameras { get; }
|
||||
DbSet<UserSite> UserSites { get; }
|
||||
DbSet<Vehicle> Vehicles { get; }
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Events.Queries.GetEvent;
|
||||
|
||||
#pragma warning disable CA1711
|
||||
public class GetEventHandler : IRequestHandler<GetEventQuery, ServiceResult<CameraEventResponse>>
|
||||
#pragma warning restore CA1711
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly ICameraAccessService _cameraAccess;
|
||||
|
||||
public GetEventHandler(IApplicationDbContext context) => _context = context;
|
||||
public GetEventHandler(IApplicationDbContext context, ICameraAccessService cameraAccess)
|
||||
{
|
||||
_context = context;
|
||||
_cameraAccess = cameraAccess;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraEventResponse>> Handle(GetEventQuery request, CancellationToken ct)
|
||||
{
|
||||
@@ -21,9 +26,20 @@ public class GetEventHandler : IRequestHandler<GetEventQuery, ServiceResult<Came
|
||||
.Include(e => e.Camera)
|
||||
.FirstOrDefaultAsync(e => e.Id == request.Id, ct);
|
||||
|
||||
return ev is null
|
||||
? ServiceResult<CameraEventResponse>.NotFound("Event not found")
|
||||
: ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
|
||||
if (ev is null)
|
||||
return ServiceResult<CameraEventResponse>.NotFound("Event not found");
|
||||
|
||||
// Verify user has access to this event's camera
|
||||
if (request.UserId.HasValue)
|
||||
{
|
||||
var hasAccess = await _cameraAccess
|
||||
.HasCameraAccessAsync(request.UserId.Value, ev.CameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (!hasAccess)
|
||||
return ServiceResult<CameraEventResponse>.NotFound("Event not found");
|
||||
}
|
||||
|
||||
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
|
||||
}
|
||||
|
||||
private static CameraEventResponse MapResponse(CameraEvent e) => new(
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Events.Queries.GetEvent;
|
||||
|
||||
public record GetEventQuery(Guid Id) : IRequest<ServiceResult<CameraEventResponse>>;
|
||||
public record GetEventQuery(Guid Id, Guid? UserId = null) : IRequest<ServiceResult<CameraEventResponse>>;
|
||||
@@ -1,18 +1,23 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Events.Queries.GetEvents;
|
||||
|
||||
#pragma warning disable CA1711
|
||||
public class GetEventsHandler : IRequestHandler<GetEventsQuery, ServiceResult<PagedResult<CameraEventResponse>>>
|
||||
#pragma warning restore CA1711
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly ICameraAccessService _cameraAccess;
|
||||
|
||||
public GetEventsHandler(IApplicationDbContext context) => _context = context;
|
||||
public GetEventsHandler(IApplicationDbContext context, ICameraAccessService cameraAccess)
|
||||
{
|
||||
_context = context;
|
||||
_cameraAccess = cameraAccess;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<CameraEventResponse>>> Handle(GetEventsQuery request, CancellationToken ct)
|
||||
{
|
||||
@@ -21,6 +26,15 @@ public class GetEventsHandler : IRequestHandler<GetEventsQuery, ServiceResult<Pa
|
||||
.AsNoTracking()
|
||||
.Include(e => e.Camera);
|
||||
|
||||
// Camera access filtering
|
||||
if (request.UserId.HasValue)
|
||||
{
|
||||
var accessibleCameraIds = await _cameraAccess
|
||||
.GetUserAccessibleCameraIdsAsync(request.UserId.Value, ct)
|
||||
.ConfigureAwait(false);
|
||||
query = query.Where(e => accessibleCameraIds.Contains(e.CameraId));
|
||||
}
|
||||
|
||||
if (request.CameraId.HasValue)
|
||||
query = query.Where(e => e.CameraId == request.CameraId.Value);
|
||||
|
||||
|
||||
@@ -14,4 +14,5 @@ public record GetEventsQuery(
|
||||
double? MinConfidence,
|
||||
int Page = 1,
|
||||
int PageSize = 50,
|
||||
string? Search = null) : IRequest<ServiceResult<PagedResult<CameraEventResponse>>>;
|
||||
string? Search = null,
|
||||
Guid? UserId = null) : IRequest<ServiceResult<PagedResult<CameraEventResponse>>>;
|
||||
+17
-2
@@ -1,21 +1,36 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Events.Queries.GetRecentByCamera;
|
||||
|
||||
#pragma warning disable CA1711
|
||||
public class GetRecentByCameraHandler : IRequestHandler<GetRecentByCameraQuery, ServiceResult<List<CameraEventResponse>>>
|
||||
#pragma warning restore CA1711
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly ICameraAccessService _cameraAccess;
|
||||
|
||||
public GetRecentByCameraHandler(IApplicationDbContext context) => _context = context;
|
||||
public GetRecentByCameraHandler(IApplicationDbContext context, ICameraAccessService cameraAccess)
|
||||
{
|
||||
_context = context;
|
||||
_cameraAccess = cameraAccess;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<List<CameraEventResponse>>> Handle(GetRecentByCameraQuery request, CancellationToken ct)
|
||||
{
|
||||
// Verify user has access to this camera
|
||||
if (request.UserId.HasValue)
|
||||
{
|
||||
var hasAccess = await _cameraAccess
|
||||
.HasCameraAccessAsync(request.UserId.Value, request.CameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (!hasAccess)
|
||||
return ServiceResult<List<CameraEventResponse>>.NotFound("Camera not found");
|
||||
}
|
||||
|
||||
var items = await _context.CameraEvents
|
||||
.AsNoTracking()
|
||||
.Include(e => e.Camera)
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Events.Queries.GetRecentByCamera;
|
||||
|
||||
public record GetRecentByCameraQuery(Guid CameraId, int Count = 20) : IRequest<ServiceResult<List<CameraEventResponse>>>;
|
||||
public record GetRecentByCameraQuery(Guid CameraId, int Count = 20, Guid? UserId = null) : IRequest<ServiceResult<List<CameraEventResponse>>>;
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Enforces camera-level access control.
|
||||
/// Users with direct UserCamera entries get camera-level access.
|
||||
/// Users without UserCamera entries fall back to site-level (UserSite).
|
||||
/// Admin role bypasses all checks (always returns true / all cameras).
|
||||
/// </summary>
|
||||
public interface ICameraAccessService
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if the user has access to the specified camera.
|
||||
/// Admins always have access. Non-admins need either a UserCamera entry
|
||||
/// or a UserSite entry for the camera's site.
|
||||
/// </summary>
|
||||
Task<bool> HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Returns all camera IDs the user can access (via UserCamera or UserSite fallback).
|
||||
/// Admins get all camera IDs.
|
||||
/// </summary>
|
||||
Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.DeleteSite;
|
||||
|
||||
public class DeleteSiteHandler : IRequestHandler<DeleteSiteCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
@@ -3,4 +3,5 @@ using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.UpdateSite;
|
||||
|
||||
public record UpdateSiteCommand(Guid Id, string Name, string? Address, string? Timezone, string? NtfyTopic = null, bool? AutoUpdateEnabled = null) : IRequest<ServiceResult<SiteResponse>>;
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Many-to-many relationship between users and cameras.
|
||||
/// Determines which cameras a non-admin user can access at camera granularity.
|
||||
/// Falls back to site-level (UserSite) when no direct camera entry exists.
|
||||
/// </summary>
|
||||
public class UserCamera
|
||||
{
|
||||
public Guid UserId { get; private set; }
|
||||
public Guid CameraId { get; private set; }
|
||||
|
||||
public AppUser User { get; private set; } = null!;
|
||||
public Camera Camera { get; private set; } = null!;
|
||||
|
||||
private UserCamera() { } // EF Core
|
||||
|
||||
public UserCamera(Guid userId, Guid cameraId)
|
||||
{
|
||||
UserId = userId;
|
||||
CameraId = cameraId;
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
public DbSet<Camera> Cameras => Set<Camera>();
|
||||
public DbSet<CameraCredentials> CameraCredentials => Set<CameraCredentials>();
|
||||
public DbSet<CameraDetectionProfile> CameraDetectionProfiles => Set<CameraDetectionProfile>();
|
||||
public DbSet<UserCamera> UserCameras => Set<UserCamera>();
|
||||
public DbSet<UserSite> UserSites => Set<UserSite>();
|
||||
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
||||
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
|
||||
@@ -93,6 +94,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
builder.Entity<CameraCredentials>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
||||
builder.Entity<CameraDetectionProfile>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
||||
builder.Entity<UserSite>().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted);
|
||||
builder.Entity<UserCamera>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
||||
|
||||
// Matching query filters for dependent entities sharing required
|
||||
// navigations to soft-deletable entities. These prevent EF Core
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class UserCameraConfiguration : IEntityTypeConfiguration<UserCamera>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<UserCamera> builder)
|
||||
{
|
||||
builder.ToTable("user_cameras");
|
||||
|
||||
builder.HasKey(uc => new { uc.UserId, uc.CameraId });
|
||||
|
||||
builder.HasOne(uc => uc.User)
|
||||
.WithMany()
|
||||
.HasForeignKey(uc => uc.UserId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.HasOne(uc => uc.Camera)
|
||||
.WithMany()
|
||||
.HasForeignKey(uc => uc.CameraId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
// Index for "find all cameras for a user" queries
|
||||
builder.HasIndex(uc => uc.UserId);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,9 @@ public static class DependencyInjection
|
||||
// Camera assignment service (used by CQRS handlers)
|
||||
services.AddScoped<ICameraAssignmentService, CameraAssignmentService>();
|
||||
|
||||
// Camera access control (used by CQRS handlers and MonitoringHub)
|
||||
services.AddScoped<ICameraAccessService, CameraAccessService>();
|
||||
|
||||
// Analysis job scheduler (capability + affinity + load routing)
|
||||
services.AddScoped<IAnalysisJobSchedulerService, AnalysisJobSchedulerService>();
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Enforces camera-level access control.
|
||||
/// Admins bypass all checks. Non-admins fall back from UserCamera → UserSite.
|
||||
/// </summary>
|
||||
public class CameraAccessService : ICameraAccessService
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
private readonly UserManager<Heimdall.Domain.Entities.AppUser> _userManager;
|
||||
|
||||
public CameraAccessService(
|
||||
IApplicationDbContext context,
|
||||
UserManager<Heimdall.Domain.Entities.AppUser> userManager)
|
||||
{
|
||||
_context = context;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default)
|
||||
{
|
||||
// Admin bypass
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString()).ConfigureAwait(false);
|
||||
if (user is not null && await _userManager.IsInRoleAsync(user, AppRoles.Admin).ConfigureAwait(false))
|
||||
return true;
|
||||
|
||||
// Check direct UserCamera entry
|
||||
var hasDirectAccess = await _context.UserCameras
|
||||
.AnyAsync(uc => uc.UserId == userId && uc.CameraId == cameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (hasDirectAccess)
|
||||
return true;
|
||||
|
||||
// Fallback: check site-level access via UserSite
|
||||
var camera = await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(c => c.Id == cameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (camera is null)
|
||||
return false;
|
||||
|
||||
return await _context.UserSites
|
||||
.AnyAsync(us => us.UserId == userId && us.SiteId == camera.SiteId, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<Guid>> GetUserAccessibleCameraIdsAsync(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
// Admin: return all camera IDs
|
||||
var user = await _userManager.FindByIdAsync(userId.ToString()).ConfigureAwait(false);
|
||||
if (user is not null && await _userManager.IsInRoleAsync(user, AppRoles.Admin).ConfigureAwait(false))
|
||||
{
|
||||
return await _context.Cameras
|
||||
.AsNoTracking()
|
||||
.Select(c => c.Id)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Collect camera IDs from direct UserCamera entries
|
||||
var directCameraIds = await _context.UserCameras
|
||||
.AsNoTracking()
|
||||
.Where(uc => uc.UserId == userId)
|
||||
.Select(uc => uc.CameraId)
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Collect camera IDs from site-level UserSite fallback
|
||||
var siteCameraIds = await _context.UserSites
|
||||
.AsNoTracking()
|
||||
.Where(us => us.UserId == userId)
|
||||
.SelectMany(us => _context.Cameras
|
||||
.Where(c => c.SiteId == us.SiteId)
|
||||
.Select(c => c.Id))
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return directCameraIds.Union(siteCameraIds).Distinct().ToList();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Events.Commands.CreateEvent;
|
||||
using Heimdall.Application.Events.Commands.AttachSnapshot;
|
||||
@@ -48,7 +49,8 @@ public class EventsController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new GetEventQuery(id), ct);
|
||||
var userId = GetUserId();
|
||||
var result = await _mediator.Send(new GetEventQuery(id, userId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
@@ -74,7 +76,8 @@ public class EventsController : ControllerBase
|
||||
if (type is not null && Enum.TryParse<EventType>(type, true, out var t))
|
||||
parsedType = t;
|
||||
|
||||
var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q), ct);
|
||||
var userId = GetUserId();
|
||||
var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q, userId), ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
@@ -84,7 +87,8 @@ public class EventsController : ControllerBase
|
||||
[ProducesResponseType(typeof(List<CameraEventResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count), ct);
|
||||
var userId = GetUserId();
|
||||
var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count, userId), ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
@@ -113,6 +117,11 @@ public class EventsController : ControllerBase
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
private Guid? GetUserId()
|
||||
{
|
||||
var sub = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
|
||||
?? User?.FindFirst("sub")?.Value;
|
||||
return Guid.TryParse(sub, out var userId) ? userId : null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Metrics;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace Heimdall.Api.Hubs;
|
||||
@@ -14,11 +19,22 @@ namespace Heimdall.Api.Hubs;
|
||||
public class MonitoringHub : Hub
|
||||
{
|
||||
private readonly ILogger<MonitoringHub> _logger;
|
||||
private readonly ICameraAccessService _cameraAccess;
|
||||
private readonly UserManager<Heimdall.Domain.Entities.AppUser> _userManager;
|
||||
|
||||
public MonitoringHub(ILogger<MonitoringHub> logger) => _logger = logger;
|
||||
public MonitoringHub(
|
||||
ILogger<MonitoringHub> logger,
|
||||
ICameraAccessService cameraAccess,
|
||||
UserManager<Heimdall.Domain.Entities.AppUser> userManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_cameraAccess = cameraAccess;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clients call this to join monitoring for a specific site.
|
||||
/// Verifies the user has access to at least one camera at the site.
|
||||
/// </summary>
|
||||
public async Task JoinSiteMonitoring(string siteId)
|
||||
{
|
||||
@@ -27,6 +43,20 @@ public class MonitoringHub : Hub
|
||||
await Clients.Caller.SendAsync("Error", "Invalid siteId format");
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = GetUserId();
|
||||
if (userId.HasValue)
|
||||
{
|
||||
var accessibleCameraIds = await _cameraAccess
|
||||
.GetUserAccessibleCameraIdsAsync(userId.Value)
|
||||
.ConfigureAwait(false);
|
||||
if (accessibleCameraIds.Count == 0)
|
||||
{
|
||||
await Clients.Caller.SendAsync("Error", "Access denied");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
|
||||
_logger.LogDebug("Client {ConnectionId} joined monitoring group {SiteId}", Context.ConnectionId, siteId);
|
||||
}
|
||||
@@ -70,6 +100,13 @@ public class MonitoringHub : Hub
|
||||
_logger.LogDebug("Client disconnected from monitoring hub: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
|
||||
private Guid? GetUserId()
|
||||
{
|
||||
var sub = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
|
||||
?? Context.User?.FindFirst("sub")?.Value;
|
||||
return Guid.TryParse(sub, out var userId) ? userId : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Events.Queries.GetEvent;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
@@ -19,7 +20,10 @@ public class GetEventHandlerTests
|
||||
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>([ev]));
|
||||
var handler = new GetEventHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
cameraAccess.HasCameraAccessAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
var handler = new GetEventHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetEventQuery(ev.Id), CancellationToken.None);
|
||||
|
||||
@@ -34,7 +38,8 @@ public class GetEventHandlerTests
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>());
|
||||
var handler = new GetEventHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
var handler = new GetEventHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetEventQuery(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Events.Queries.GetEvents;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
@@ -23,7 +24,10 @@ public class GetEventsHandlerTests
|
||||
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>(events));
|
||||
var handler = new GetEventsHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
cameraAccess.GetUserAccessibleCameraIdsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns([camera.Id]);
|
||||
var handler = new GetEventsHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetEventsQuery(null, null, null, null, null, null, 1, 50), CancellationToken.None);
|
||||
|
||||
@@ -49,7 +53,10 @@ public class GetEventsHandlerTests
|
||||
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>(events));
|
||||
var handler = new GetEventsHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
cameraAccess.GetUserAccessibleCameraIdsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns([camera1.Id, camera2.Id]);
|
||||
var handler = new GetEventsHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetEventsQuery(camera1.Id, null, null, null, null, null, 1, 50), CancellationToken.None);
|
||||
|
||||
@@ -75,7 +82,10 @@ public class GetEventsHandlerTests
|
||||
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>(events));
|
||||
var handler = new GetEventsHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
cameraAccess.GetUserAccessibleCameraIdsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns([camera.Id]);
|
||||
var handler = new GetEventsHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetEventsQuery(null, null, null, null, null, null, 1, 50, "JEAN"), CancellationToken.None);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Events.Queries.GetRecentByCamera;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
@@ -25,7 +26,10 @@ public class GetRecentByCameraHandlerTests
|
||||
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>(events));
|
||||
var handler = new GetRecentByCameraHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
cameraAccess.HasCameraAccessAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
var handler = new GetRecentByCameraHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetRecentByCameraQuery(cameraId, 10), CancellationToken.None);
|
||||
|
||||
@@ -41,7 +45,10 @@ public class GetRecentByCameraHandlerTests
|
||||
var cameraId = Guid.NewGuid();
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.CameraEvents.Returns(MockDbSetHelper.CreateFor<CameraEvent>());
|
||||
var handler = new GetRecentByCameraHandler(context);
|
||||
var cameraAccess = Substitute.For<ICameraAccessService>();
|
||||
cameraAccess.HasCameraAccessAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
var handler = new GetRecentByCameraHandler(context, cameraAccess);
|
||||
|
||||
var result = await handler.Handle(new GetRecentByCameraQuery(cameraId, 10), CancellationToken.None);
|
||||
|
||||
|
||||
Reference in new issue
Block a user