Add online pinging and friendship verification features

Introduces OnlinePingingController and related integration/unit tests for user online status updates. Adds PingHandlerService with memory cache throttling, IPingHandlerService interface, and service registration. Implements VerifyFriendship service and interface for friendship validation, with exception handling. Refactors CurrentUserService for improved user ID extraction and testability. Updates ChatsHub to verify friendship before messaging. Cleans up MediaController and optimizes UsersRepository queries by removing unnecessary includes.
This commit is contained in:
Artemy
2025-07-02 19:16:49 +07:00
parent 0669614a5e
commit 565d3249e5
14 changed files with 483 additions and 32 deletions
@@ -0,0 +1,131 @@
using Govor.API.Controllers;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
namespace Govor.API.Tests.IntegrationTests.Controllers;
[TestFixture]
public class OnlinePingingControllerTests
{
private Mock<ILogger<OnlinePingingController>> _loggerMock;
private Mock<IPingHandlerService> _pingHandlerServiceMock;
private Mock<ICurrentUserService> _currentUserServiceMock;
private OnlinePingingController _controller;
[SetUp]
public void SetUp()
{
_loggerMock = new Mock<ILogger<OnlinePingingController>>();
_pingHandlerServiceMock = new Mock<IPingHandlerService>();
_currentUserServiceMock = new Mock<ICurrentUserService>();
_controller = new OnlinePingingController(_loggerMock.Object, _pingHandlerServiceMock.Object,
_currentUserServiceMock.Object);
}
[Test]
public async Task Ping_ValidUserId_ReturnsOk()
{
// Arrange
var userId = Guid.NewGuid();
_currentUserServiceMock.Setup(x => x.GetCurrentUserId()).Returns(userId);
_pingHandlerServiceMock.Setup(x => x.Ping(userId)).Returns(Task.CompletedTask);
// Act
var result = await _controller.Ping();
// Assert
Assert.That(result, Is.InstanceOf<OkResult>());
_pingHandlerServiceMock.Verify(x => x.Ping(userId), Times.Once());
_loggerMock.VerifyLog(LogLevel.Information, $"Ping from user {userId} processed successfully", Times.Once());
}
[Test]
public async Task Ping_InvalidOperationException_ReturnsBadRequest()
{
// Arrange
var userId = Guid.NewGuid();
var exception = new InvalidOperationException("User not found");
_currentUserServiceMock.Setup(x => x.GetCurrentUserId()).Returns(userId);
_pingHandlerServiceMock.Setup(x => x.Ping(userId)).ThrowsAsync(exception);
// Act
var result = await _controller.Ping();
// Assert
Assert.That(result, Is.InstanceOf<BadRequestObjectResult>());
var badRequestResult = (BadRequestObjectResult)result;
Assert.That(badRequestResult.Value, Is.EqualTo("User can't be found in our database."));
_loggerMock.VerifyLog(LogLevel.Error, exception.Message, Times.Once());
}
[Test]
public async Task Ping_UnauthorizedAccessException_ReturnsForbid()
{
// Arrange
var userId = Guid.NewGuid();
var exception = new UnauthorizedAccessException("Unauthorized");
_currentUserServiceMock.Setup(x => x.GetCurrentUserId()).Returns(userId);
_pingHandlerServiceMock.Setup(x => x.Ping(userId)).ThrowsAsync(exception);
// Act
var result = await _controller.Ping();
// Assert
Assert.That(result, Is.InstanceOf<ForbidResult>());
_loggerMock.VerifyLog(LogLevel.Error, exception.Message, Times.Once());
}
[Test]
public async Task Ping_GeneralException_ReturnsStatusCode500()
{
// Arrange
var userId = Guid.NewGuid();
var exception = new Exception("Unexpected error");
_currentUserServiceMock.Setup(x => x.GetCurrentUserId()).Returns(userId);
_pingHandlerServiceMock.Setup(x => x.Ping(userId)).ThrowsAsync(exception);
// Act
var result = await _controller.Ping();
// Assert
Assert.That(result, Is.InstanceOf<ObjectResult>());
var objectResult = (ObjectResult)result;
Assert.That(objectResult.StatusCode, Is.EqualTo(500));
_loggerMock.VerifyLog(LogLevel.Error, exception.Message, Times.Once());
}
[Test]
public async Task Ping_UnauthorizedUserId_ThrowsUnauthorizedAccessException()
{
// Arrange
var exception = new UnauthorizedAccessException("userID claim is missing or invalid");
_currentUserServiceMock.Setup(x => x.GetCurrentUserId()).Throws(exception);
// Act
var result = await _controller.Ping();
// Assert
Assert.That(result, Is.InstanceOf<ForbidResult>());
_loggerMock.VerifyLog(LogLevel.Error, exception.Message, Times.Once());
_pingHandlerServiceMock.Verify(x => x.Ping(It.IsAny<Guid>()), Times.Never());
}
}
// Helper extension for verifying logger calls
public static class LoggerMockExtensions
{
public static void VerifyLog<T>(this Mock<ILogger<T>> logger, LogLevel level, string message, Times times)
{
logger.Verify(
x => x.Log(
It.Is<LogLevel>(l => l == level),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString().Contains(message)),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
times);
}
}
@@ -0,0 +1,106 @@
using System.Security.Claims;
using Govor.Application.Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using Moq;
namespace Govor.API.Tests.UnitTests.Services;
[TestFixture]
public class CurrentUserServiceTests
{
private Mock<IHttpContextAccessor> _httpContextAccessorMock;
private CurrentUserService _currentUserService;
[SetUp]
public void SetUp()
{
_httpContextAccessorMock = new Mock<IHttpContextAccessor>();
_currentUserService = new CurrentUserService(_httpContextAccessorMock.Object);
}
[Test]
public void GetCurrentUserId_ValidUserIdClaim_ReturnsGuid()
{
// Arrange
var userId = Guid.NewGuid();
var claims = new[] { new Claim("userId", userId.ToString()) };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act
var result = _currentUserService.GetCurrentUserId();
// Assert
Assert.That(result, Is.EqualTo(userId));
}
[Test]
public void GetCurrentUserId_NoHttpContext_ThrowsUnauthorizedAccessException()
{
// Arrange
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns((HttpContext)null);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
[Test]
public void GetCurrentUserId_NoUserIdClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("otherClaim", "value") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
[Test]
public void GetCurrentUserId_InvalidUserIdClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("userId", "invalid-guid") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
[Test]
public void GetCurrentUserId_EmptyUserIdClaim_ThrowsUnauthorizedAccessException()
{
// Arrange
var claims = new[] { new Claim("userId", "") };
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(identity);
var httpContextMock = new Mock<HttpContext>();
httpContextMock.Setup(x => x.User).Returns(principal);
_httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
// Act & Assert
var ex = Assert.Throws<UnauthorizedAccessException>(() => _currentUserService.GetCurrentUserId());
Assert.That(ex.Message, Is.EqualTo("userID claim is missing or invalid"));
}
}
@@ -0,0 +1,58 @@
using Govor.Application.Services;
using Govor.Core.Models;
using Govor.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace Govor.Tests.Application.Services;
[TestFixture]
public class PingHandlerServiceTests
{
private GovorDbContext _dbContext = null!;
private IMemoryCache _memoryCache = null!;
private PingHandlerService _service = null!;
private Guid _userId;
[SetUp]
public void SetUp()
{
var options = new DbContextOptionsBuilder<GovorDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
_dbContext = new GovorDbContext(options);
_memoryCache = new MemoryCache(new MemoryCacheOptions());
_service = new PingHandlerService(_dbContext, _memoryCache);
_userId = Guid.NewGuid();
_dbContext.Users.Add(new User
{
Id = _userId,
Username = "TestUser",
WasOnline = DateTime.UtcNow.AddHours(-1),
Description = "Test description",
PasswordHash = "hashed_password_here"
});
_dbContext.SaveChanges();
}
[Test]
public async Task Ping_DoesNotUpdate_WhenPingTooRecent()
{
// Arrange
var initial = DateTime.UtcNow.AddMinutes(-1);
_memoryCache.Set($"LastPing_{_userId}", DateTime.UtcNow);
var user = await _dbContext.Users.FirstAsync(u => u.Id == _userId);
var originalTime = user.WasOnline;
// Act
await _service.Ping(_userId);
var updatedUser = await _dbContext.Users.FirstAsync(u => u.Id == _userId);
// Assert
Assert.That(updatedUser.WasOnline, Is.EqualTo(originalTime));
}
}