using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; using Helpdesk.Domain.Auth; using Microsoft.EntityFrameworkCore; namespace Helpdesk.Application.Notifications; public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser) { public async Task RegisterAsync(string token, CancellationToken ct) { ValidateToken(token); await using var transaction = await db.BeginWriteAsync(ct); var user = await db.LockUserAsync(currentUser.Id, ct); if (user is not { IsActive: true, IsDeleted: false }) throw new UnauthorizedException("Účet není aktivní."); // Po čekání na zámek mohl správce relaci odhlásit a odstranit všechna její zařízení. if (!await db.AuthTokens.AnyAsync(t => t.Jti == currentUser.TokenId && t.UserId == user.Id && t.TokenType == TokenType.Access && t.RevokedAt == null, ct)) throw new UnauthorizedException("Přihlášení vypršelo. Přihlaste se znovu."); await db.RegisterPushDeviceAsync(user.Id, token, ct); await transaction.CommitAsync(ct); } public async Task UnregisterAsync(string token, CancellationToken ct) { ValidateToken(token); var userId = currentUser.Id; await db.PushDevices.Where(d => d.UserId == userId && d.FcmToken == token).ExecuteDeleteAsync(ct); } private static void ValidateToken(string? token) { if (string.IsNullOrEmpty(token) || token.Length > 512 || token.Any(c => char.IsWhiteSpace(c) || char.IsControl(c))) throw new BadRequestException("Neplatný registrační token zařízení."); } }