backend: Enforce notification access and clear push devices
This commit is contained in:
1 parent
ee5f1d3d10
commit
4f95c8a379
12 files changed
+145
-46
No files matched your search
@@ -62,7 +62,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
|||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlášení ze všech zařízení – zneplatní všechny tokeny uživatele.</summary>
|
/// <summary>Odhlášení ze všech zařízení. Zneplatní tokeny a odstraní registrace pro push.</summary>
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[HttpPost("logout-all")]
|
[HttpPost("logout-all")]
|
||||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ public sealed class AuthService(
|
|||||||
|
|
||||||
await using var transaction = await db.BeginWriteAsync(ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.EmailConfirm, ct);
|
||||||
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.PasswordChanged, ct);
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||||
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||||
user.ConfirmEmail();
|
user.ConfirmEmail();
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
@@ -128,7 +128,7 @@ public sealed class AuthService(
|
|||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.ReuseDetected, ct);
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.ReuseDetected, ct);
|
||||||
await transaction.CommitAsync(ct);
|
await transaction.CommitAsync(ct);
|
||||||
revocation.Publish(revoked);
|
revocation.Publish(revoked);
|
||||||
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||||
@@ -146,8 +146,15 @@ public sealed class AuthService(
|
|||||||
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
await revocation.RevokeAsync(currentUser.Id, jtis, RevokeReason.Logout, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct) =>
|
public async Task LogoutAllAsync(ICurrentUser currentUser, CancellationToken ct)
|
||||||
revocation.RevokeAllAsync(currentUser.Id, RevokeReason.LogoutAll, ct);
|
{
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
|
await db.LockUserAsync(userId, ct);
|
||||||
|
var revoked = await StageDisconnectAsync(userId, RevokeReason.LogoutAll, ct);
|
||||||
|
await transaction.CommitAsync(ct);
|
||||||
|
revocation.Publish(revoked);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
|
/// <summary>Vždy uspěje, i pro neexistující e-mail – odpověď neprozradí, zda účet existuje.</summary>
|
||||||
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
|
public async Task ForgotPasswordAsync(ForgotPasswordRequest request, CancellationToken ct)
|
||||||
@@ -173,13 +180,22 @@ public sealed class AuthService(
|
|||||||
|
|
||||||
await using var transaction = await db.BeginWriteAsync(ct);
|
await using var transaction = await db.BeginWriteAsync(ct);
|
||||||
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
var user = await ConsumeEmailTokenAsync(request.Token, TokenType.PasswordReset, ct);
|
||||||
var revoked = await revocation.StageRevokeAllAsync([user.Id], RevokeReason.PasswordChanged, ct);
|
var revoked = await StageDisconnectAsync(user.Id, RevokeReason.PasswordChanged, ct);
|
||||||
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
user.ChangePasswordHash(passwordHasher.Hash(request.NewPassword));
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
await transaction.CommitAsync(ct);
|
await transaction.CommitAsync(ct);
|
||||||
revocation.Publish(revoked);
|
revocation.Publish(revoked);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Volat v transakci se zámkem účtu, který používá i registrace zařízení.
|
||||||
|
private async Task<List<TokenRevocationService.RevokedAccessToken>> StageDisconnectAsync(
|
||||||
|
int userId, RevokeReason reason, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var revoked = await revocation.StageRevokeAllAsync([userId], reason, ct);
|
||||||
|
await db.PushDevices.Where(device => device.UserId == userId).ExecuteDeleteAsync(ct);
|
||||||
|
return revoked;
|
||||||
|
}
|
||||||
|
|
||||||
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
private async Task<AuthResponse> IssueTokenPairAsync(User user, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var access = tokens.Issue(user, TokenType.Access);
|
var access = tokens.Issue(user, TokenType.Access);
|
||||||
|
|||||||
@@ -34,10 +34,6 @@ public sealed class TokenRevocationService(IAppDbContext db, IRevokedTokenStore
|
|||||||
Publish(await LoadRevokedAccessTokensAsync([userId], now, ct));
|
Publish(await LoadRevokedAccessTokensAsync([userId], now, ct));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Zneplatní všechny platné tokeny uživatele – jeden UPDATE (kap. 10.1).</summary>
|
|
||||||
public async Task RevokeAllAsync(int userId, RevokeReason reason, CancellationToken ct) =>
|
|
||||||
Publish(await StageRevokeAllAsync([userId], reason, ct));
|
|
||||||
|
|
||||||
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
|
internal async Task<List<RevokedAccessToken>> StageRevokeAllAsync(int[] userIds, RevokeReason reason, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var now = Now();
|
var now = Now();
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUs
|
|||||||
private IQueryable<Notification> Inbox()
|
private IQueryable<Notification> Inbox()
|
||||||
{
|
{
|
||||||
var userId = currentUser.Id;
|
var userId = currentUser.Id;
|
||||||
return db.Notifications.Where(n => n.UserId == userId);
|
return NotificationVisibility.VisibleToRecipients(db).Where(n => n.UserId == userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
|
||||||
|
namespace Helpdesk.Application.Notifications;
|
||||||
|
|
||||||
|
public static class NotificationVisibility
|
||||||
|
{
|
||||||
|
internal static readonly UserRole[] ReadAllIssueRoles = Enum.GetValues<UserRole>().Where(Issue.CanReadAll).ToArray();
|
||||||
|
|
||||||
|
public static IQueryable<Notification> VisibleToRecipients(IAppDbContext db) =>
|
||||||
|
db.Notifications.Where(n => db.Users.Any(u => u.Id == n.UserId && u.IsActive && !u.IsDeleted &&
|
||||||
|
(n.IssueId == null || ReadAllIssueRoles.Contains(u.Role) ||
|
||||||
|
db.Issues.Any(issue => issue.Id == n.IssueId && issue.ReporterId == u.Id))));
|
||||||
|
}
|
||||||
@@ -14,9 +14,7 @@ public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock)
|
|||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var reporterId = issue.ReporterId;
|
var reporterId = issue.ReporterId;
|
||||||
var eligibleUsers = db.Users.Where(u =>
|
var eligibleUsers = db.Users.Where(u => u.Id == reporterId || NotificationVisibility.ReadAllIssueRoles.Contains(u.Role));
|
||||||
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management ||
|
|
||||||
u.Role == UserRole.Admin);
|
|
||||||
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
||||||
id => new Notification(issue, id, type, title, issue.Title), ct);
|
id => new Notification(issue, id, type, title, issue.Title), ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
using Helpdesk.Domain.Notifications;
|
using Helpdesk.Domain.Notifications;
|
||||||
using Helpdesk.Infrastructure.Email;
|
using Helpdesk.Infrastructure.Email;
|
||||||
using Helpdesk.Infrastructure.Notifications;
|
using Helpdesk.Infrastructure.Notifications;
|
||||||
@@ -56,13 +57,13 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
var recipient = await (
|
var recipient = await (
|
||||||
from notification in db.Notifications.AsNoTracking()
|
from notification in NotificationVisibility.VisibleToRecipients(db).AsNoTracking()
|
||||||
join user in db.Users on notification.UserId equals user.Id
|
join user in db.Users on notification.UserId equals user.Id
|
||||||
where notification.Id == delivery.NotificationId
|
where notification.Id == delivery.NotificationId
|
||||||
select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
select new { Notification = notification, user.Id, user.Email, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
||||||
).SingleAsync(ct);
|
).SingleOrDefaultAsync(ct);
|
||||||
|
|
||||||
if (!recipient.IsActive)
|
if (recipient is null)
|
||||||
delivery.Skip();
|
delivery.Skip();
|
||||||
else if (delivery.Channel == DeliveryChannel.Email)
|
else if (delivery.Channel == DeliveryChannel.Email)
|
||||||
{
|
{
|
||||||
@@ -73,7 +74,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct);
|
await SendPushAsync(db, delivery, recipient.Id, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
@@ -94,8 +95,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendPushAsync(
|
private async Task SendPushAsync(HelpdeskDbContext db, NotificationDelivery delivery, int userId, CancellationToken ct)
|
||||||
HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct)
|
|
||||||
{
|
{
|
||||||
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
||||||
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
||||||
@@ -105,7 +105,7 @@ internal sealed partial class NotificationDispatcher(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = await push!.SendAsync(notification, tokens, ct);
|
var result = await push!.SendAsync(tokens, ct);
|
||||||
foreach (var invalidToken in result.InvalidTokens)
|
foreach (var invalidToken in result.InvalidTokens)
|
||||||
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using FirebaseAdmin;
|
using FirebaseAdmin;
|
||||||
using FirebaseAdmin.Messaging;
|
using FirebaseAdmin.Messaging;
|
||||||
using Google.Apis.Auth.OAuth2;
|
using Google.Apis.Auth.OAuth2;
|
||||||
using Google.Apis.Auth.OAuth2.Responses;
|
using Google.Apis.Auth.OAuth2.Responses;
|
||||||
using Helpdesk.Domain;
|
using Helpdesk.Domain;
|
||||||
using Notification = Helpdesk.Domain.Notifications.Notification;
|
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Notifications;
|
namespace Helpdesk.Infrastructure.Notifications;
|
||||||
|
|
||||||
@@ -37,17 +35,8 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|||||||
return new FirebasePushSender(app);
|
return new FirebasePushSender(app);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
|
public async Task<PushDeliveryResult> SendAsync(string[] tokens, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var data = new Dictionary<string, string>
|
|
||||||
{
|
|
||||||
["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture),
|
|
||||||
};
|
|
||||||
if (notification.IssueId is int issueId)
|
|
||||||
data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture);
|
|
||||||
if (notification.ProposalId is int proposalId)
|
|
||||||
data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture);
|
|
||||||
|
|
||||||
var messaging = FirebaseMessaging.GetMessaging(app);
|
var messaging = FirebaseMessaging.GetMessaging(app);
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
@@ -65,12 +54,11 @@ internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
|||||||
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
||||||
Tokens = batch,
|
Tokens = batch,
|
||||||
#pragma warning restore CS0618
|
#pragma warning restore CS0618
|
||||||
Notification = new FirebaseAdmin.Messaging.Notification
|
Notification = new Notification
|
||||||
{
|
{
|
||||||
Title = notification.Title,
|
Title = "NTBug",
|
||||||
Body = notification.Message,
|
Body = "V aplikaci máte novou notifikaci.",
|
||||||
},
|
},
|
||||||
Data = data,
|
|
||||||
}, timeout.Token);
|
}, timeout.Token);
|
||||||
|
|
||||||
sent |= result.SuccessCount > 0;
|
sent |= result.SuccessCount > 0;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Api.Controllers;
|
||||||
using Helpdesk.Application.Auth;
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
@@ -13,11 +14,13 @@ namespace Helpdesk.IntegrationTests;
|
|||||||
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
{
|
{
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
|
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSessionAndRemovesItsDevice()
|
||||||
{
|
{
|
||||||
using var anonymous = fixture.CreateClient();
|
using var anonymous = fixture.CreateClient();
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
await ExpectAsync(oldSession.PostAsJsonAsync("/api/v1/devices",
|
||||||
|
new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent);
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
|
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
|
||||||
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
@@ -31,6 +34,9 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
new LoginRequest(user.Email, newPassword), Cancellation));
|
new LoginRequest(user.Email, newPassword), Cancellation));
|
||||||
Assert.Equal(user.Id, session.User.Id);
|
Assert.Equal(user.Id, session.User.Id);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -57,6 +63,29 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
token.RevokeReason == RevokeReason.Logout, Cancellation));
|
token.RevokeReason == RevokeReason.Logout, Cancellation));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task LogoutAllRemovesAllDevicesForTheAccount()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
var otherUser = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var first = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
using var second = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
||||||
|
using var unrelated = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
|
||||||
|
const string devices = "/api/v1/devices";
|
||||||
|
await ExpectAsync(first.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-first"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(second.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-second"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(unrelated.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-unrelated"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await ExpectAsync(first.PostAsync("/api/v1/auth/logout-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
await ExpectAsync(first.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(second.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-second"), Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
|
Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == otherUser.Id, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
||||||
{
|
{
|
||||||
@@ -64,6 +93,9 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
var user = await fixture.RegisterAsync(anonymous);
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
var session = await LoginAsync(anonymous, user.Email);
|
var session = await LoginAsync(anonymous, user.Email);
|
||||||
var otherSession = await LoginAsync(anonymous, user.Email);
|
var otherSession = await LoginAsync(anonymous, user.Email);
|
||||||
|
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
||||||
|
await ExpectAsync(otherClient.PostAsJsonAsync("/api/v1/devices",
|
||||||
|
new RegisterDeviceRequest("refresh-replay-device"), Cancellation), HttpStatusCode.NoContent);
|
||||||
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
||||||
|
|
||||||
var pause = fixture.TokenSaves.PauseNextSave();
|
var pause = fixture.TokenSaves.PauseNextSave();
|
||||||
@@ -87,11 +119,11 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
|||||||
var renewed = await ReadAsync<AuthResponse>(first);
|
var renewed = await ReadAsync<AuthResponse>(first);
|
||||||
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
||||||
await using var after = fixture.Services.CreateAsyncScope();
|
await using var after = fixture.Services.CreateAsyncScope();
|
||||||
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().AuthTokens;
|
var afterDb = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
Assert.False(await afterDb.AuthTokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
||||||
|
Assert.False(await afterDb.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||||
|
|
||||||
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
|
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
|
||||||
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
|
||||||
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
.Build();
|
.Build();
|
||||||
private readonly TestEmailSender email = new();
|
private readonly TestEmailSender email = new();
|
||||||
private ApiFactory? factory;
|
private ApiFactory? factory;
|
||||||
|
private int clientNumber;
|
||||||
|
|
||||||
internal TokenSaveGate TokenSaves { get; } = new();
|
internal TokenSaveGate TokenSaves { get; } = new();
|
||||||
internal IServiceProvider Services => factory!.Services;
|
internal IServiceProvider Services => factory!.Services;
|
||||||
@@ -62,7 +63,13 @@ public sealed class BackendFixture : IAsyncLifetime
|
|||||||
|
|
||||||
internal HttpClient CreateClient(string? accessToken = null)
|
internal HttpClient CreateClient(string? accessToken = null)
|
||||||
{
|
{
|
||||||
var client = factory!.CreateClient();
|
// Každý klient simuluje vlastní IP adresu a má vlastní limit požadavků na přihlášení.
|
||||||
|
var address = IPAddress.Parse($"2001:db8::{Interlocked.Increment(ref clientNumber):x}");
|
||||||
|
var server = factory!.Server;
|
||||||
|
var client = new HttpClient(server.CreateHandler(context => context.Connection.RemoteIpAddress = address))
|
||||||
|
{
|
||||||
|
BaseAddress = server.BaseAddress,
|
||||||
|
};
|
||||||
if (accessToken is not null)
|
if (accessToken is not null)
|
||||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||||
return client;
|
return client;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using Helpdesk.Application.Catalogs;
|
|||||||
using Helpdesk.Application.Common;
|
using Helpdesk.Application.Common;
|
||||||
using Helpdesk.Application.Issues;
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Notifications;
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -66,6 +67,50 @@ public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<Ba
|
|||||||
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RoleChangeHidesOtherIssuesAndSkipsQueuedEmail()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var reporterAccount = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, reporterAccount.Email)).AccessToken);
|
||||||
|
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||||
|
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||||
|
const string issues = "/api/v1/issues";
|
||||||
|
const string inbox = "/api/v1/notifications";
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var request = new CreateIssueRequest("Závada v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
|
||||||
|
|
||||||
|
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
|
||||||
|
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
var before = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox, Cancellation));
|
||||||
|
var hidden = Assert.Single(before.Items);
|
||||||
|
Assert.Equal(issue.Id, hidden.IssueId);
|
||||||
|
var failed = await WaitForDeliveryAsync(admin, hidden.Id, "FAILED");
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{managerSession.User.Id}/role",
|
||||||
|
new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
using var student = fixture.CreateClient((await LoginAsync(anonymous, managerSession.User.Email)).AccessToken);
|
||||||
|
var ownIssue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created);
|
||||||
|
await ReadAsync<IssueEventDto>(admin.PostAsJsonAsync($"{issues}/{ownIssue.Id}/comments",
|
||||||
|
new CommentRequest("Komentář k vlastní závadě uživatele."), Cancellation));
|
||||||
|
|
||||||
|
var after = await ReadAsync<PagedResult<NotificationDto>>(student.GetAsync(inbox, Cancellation));
|
||||||
|
Assert.Equal(1, after.TotalCount);
|
||||||
|
Assert.Equal(ownIssue.Id, Assert.Single(after.Items).IssueId);
|
||||||
|
Assert.Equal(1, (await ReadAsync<UnreadCountDto>(student.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||||
|
await ExpectAsync(student.PostAsync($"{inbox}/{hidden.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
|
||||||
|
await ExpectAsync(student.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(student.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||||
|
|
||||||
|
await ExpectAsync(admin.PostAsync($"/api/v1/admin/notification-deliveries/{failed.Id}/retry", null, Cancellation),
|
||||||
|
HttpStatusCode.NoContent);
|
||||||
|
await WaitForDeliveryAsync(admin, hidden.Id, "SKIPPED", attempts: 0);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.Null(await db.Notifications.Where(n => n.Id == hidden.Id).Select(n => n.ReadAt).SingleAsync(Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -374,9 +374,10 @@ sequenceDiagram
|
|||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
- **V aplikaci:** tabulka `notification`. Notifikace v aplikaci je doručena vždy, protože vzniká v DB ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
- **V aplikaci:** notifikace se uloží do tabulky `notification` ve stejné transakci jako událost. Klient zobrazuje seznam a počet nepřečtených (`GET /api/v1/notifications/unread-count`, web jej obnovuje periodicky).
|
||||||
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
- **E-mail:** SMTP (knihovna MailKit); ve vývoji zachytává e-maily kontejner Mailpit.
|
||||||
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`); backend odesílá přes Firebase Admin SDK.
|
- **Push:** mobilní aplikace po přihlášení zaregistruje FCM token (`POST /api/v1/devices`). Backend přes Firebase Admin SDK posílá obecné upozornění. Podrobnosti klient načte z API po přihlášení.
|
||||||
|
- Při zobrazení notifikace v aplikaci i před doručením e-mailu nebo push backend ověřuje aktuální přístup příjemce k související závadě.
|
||||||
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
- Pro každou notifikaci se vytvoří řádek `notification_delivery` pro každý externí kanál. Stav kanálu se tak sleduje samostatně: e-mail může selhat, i když push prošel.
|
||||||
|
|
||||||
### 8.3 Řešení nedoručení
|
### 8.3 Řešení nedoručení
|
||||||
@@ -470,7 +471,7 @@ Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "C
|
|||||||
| Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku |
|
| Síť | Retrofit + OkHttp + kotlinx.serialization; `Authenticator` pro obnovu tokenu, `Interceptor` pro Bearer hlavičku |
|
||||||
| Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore |
|
| Úložiště tokenů | DataStore, šifrováno klíčem z Android Keystore |
|
||||||
| Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním |
|
| Fotky | Systémový fotoaparát / výběr z galerie (Activity Result API), náhledy Coil, zmenšení před odesláním |
|
||||||
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), deep link na detail závady |
|
| Push | Firebase Cloud Messaging (`FirebaseMessagingService`), podrobnosti v přihlášené aplikaci |
|
||||||
| Min. verze | Android 8.0 (API 26) |
|
| Min. verze | Android 8.0 (API 26) |
|
||||||
|
|
||||||
### 9.6 Struktura repozitáře (Git, EngineRevive)
|
### 9.6 Struktura repozitáře (Git, EngineRevive)
|
||||||
|
|||||||
Reference in new issue
Block a user