Refactor: migrate Core -> Domain and reorganize projects

Large refactor that renames/moves core types into a new Govor.Domain surface and reorganizes the Application layer. Models, configurations, migrations and many files moved from Govor.Core/Govor.Data to Govor.Domain; numerous Application services, interfaces and implementations were relocated or added (authentication, friends, messages, medias, push notifications, user sessions, storage, synching, private chats, etc.). Tests updated to use Govor.Domain namespaces and adjusted project references (removed Govor.Data reference from API tests). Also updated API, Hub and mapping code and project files to reflect the new structure and naming. This is primarily a codebase-wide namespace and module reorganization to establish a Domain project and restructure application services.
This commit is contained in:
Artemy
2026-07-16 19:27:45 +07:00
parent 1d35356c8c
commit 6d1c53beeb
371 changed files with 2729 additions and 6694 deletions
@@ -3,7 +3,7 @@ using Govor.API.Controllers;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.UserSession;
using Govor.Contracts.DTOs;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
-1
View File
@@ -27,6 +27,5 @@
<ItemGroup>
<ProjectReference Include="..\Govor.API\Govor.API.csproj" />
<ProjectReference Include="..\Govor.Data\Govor.Data.csproj" />
</ItemGroup>
</Project>
+2 -2
View File
@@ -2,8 +2,8 @@ using AutoFixture;
using Govor.API.Common.SignalR.Helpers;
using Govor.API.Hubs;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Users;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.Users;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
@@ -1,12 +1,12 @@
using AutoFixture;
using Govor.API.Controllers.Authentication;
using Govor.Application.Exceptions.AuthService;
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Exceptions.InvitesService;
using Govor.Application.Interfaces.Authentication;
using Govor.Application.Interfaces.UserSession;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
@@ -3,9 +3,10 @@ using AutoMapper;
using Govor.API.Controllers;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Messages;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses;
using Govor.Core.Models.Messages;
using Govor.Domain.Models.Messages;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
@@ -4,7 +4,7 @@ using Govor.API.Controllers.Friends;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Contracts.DTOs;
using Govor.Core.Models;
using Govor.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
@@ -5,7 +5,7 @@ using Govor.Application.Exceptions.FriendsService;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Contracts.DTOs;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
@@ -4,7 +4,7 @@ using Govor.API.Controllers;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias;
using Govor.Contracts.Requests;
using Govor.Core.Models.Messages;
using Govor.Domain.Models.Messages;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
@@ -1,6 +1,7 @@
using Govor.API.Controllers;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.PingHandler;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
@@ -8,8 +8,8 @@ using Govor.Application.Interfaces.Medias;
using Govor.Application.Profiles;
using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -7,7 +7,7 @@ using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses.SignalR;
using Govor.Core.Models;
using Govor.Domain.Models;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,7 +1,8 @@
using Govor.API.Hubs;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Interfaces;
using Govor.Core.Models;
using Govor.Domain.Models;
using Microsoft.AspNetCore.SignalR;
using Moq;
@@ -1,6 +1,5 @@
using AutoFixture;
using Govor.Application.Interfaces;
using Govor.Application.Services;
using Microsoft.AspNetCore.Hosting;
using Moq;
@@ -1,6 +1,6 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Domain.Common.Constants;
using Govor.Domain.Models;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
@@ -1,6 +1,6 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Domain.Common.Constants;
using Govor.Domain.Models;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
@@ -1,18 +1,18 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Domain.Common.Constants;
using Govor.Domain.Models;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
[TestFixture]
public class InvitationValidatorTests
public class InvitationConstantsTests
{
private IObjectValidator<Invitation> _messageValidator;
private Fixture _fixture;
public InvitationValidatorTests()
public InvitationConstantsTests()
{
_messageValidator = new InvitationValidator();
_messageValidator = new InvitationConstants();
_fixture = new Fixture();
@@ -1,7 +1,7 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Domain.Common.Constants;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
@@ -1,6 +1,6 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Domain.Common.Constants;
using Govor.Domain.Models;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
@@ -1,12 +1,12 @@
using AutoFixture;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Domain.Common.Constants;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.API.Tests.UnitTests.Infrastructure.Validators;
[TestFixture]
public class UserValidatorTests
public class UserConstantsTests
{
private IObjectValidator<User> _userValidator;
private Fixture _fixture;
@@ -14,7 +14,7 @@ public class UserValidatorTests
[SetUp]
public void SetUp()
{
_userValidator = new UserValidator();
_userValidator = new UserConstants();
_fixture = new Fixture();
@@ -1,4 +1,4 @@
using Govor.Application.Services.Authentication;
using Govor.Application.Authentication.JWT;
namespace Govor.API.Common.Extensions;
@@ -1,46 +1,27 @@
using Govor.API.Common.Mapping;
using Govor.API.Common.SignalR.Helpers;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Authentication;
using Govor.Application.Authentication.JWT;
using Govor.Application.Friends;
using Govor.Application.Groups;
using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Infrastructure.Validators;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Authentication;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias;
using Govor.Application.Interfaces.Messages;
using Govor.Application.Interfaces.PushNotifications;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Application.Interfaces.UserSession;
using Govor.Application.Interfaces.UserSession.Crypto;
using Govor.Application.Services;
using Govor.Application.Services.Authentication;
using Govor.Application.Services.Friends;
using Govor.Application.Services.Medias;
using Govor.Application.Services.Messages;
using Govor.Application.Services.PushNotifications;
using Govor.Application.Services.PushNotifications.Providers;
using Govor.Application.Services.UserOnlineStatus;
using Govor.Application.Services.UserSessions;
using Govor.Application.Services.UserSessions.Crypto;
using Govor.Core.Infrastructure.Extensions;
using Govor.Core.Infrastructure.Validators;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Admins;
using Govor.Core.Repositories.Friendships;
using Govor.Core.Repositories.Groups;
using Govor.Core.Repositories.Invaites;
using Govor.Core.Repositories.MediasAttachments;
using Govor.Core.Repositories.Messages;
using Govor.Core.Repositories.PrivateChats;
using Govor.Core.Repositories.PushTokens;
using Govor.Core.Repositories.Users;
using Govor.Core.Repositories.UserSessionsRepository;
using Govor.Data;
using Govor.Data.Repositories;
using Govor.Application.Medias;
using Govor.Application.Messages;
using Govor.Application.PingHandler;
using Govor.Application.PrivateUserChats;
using Govor.Application.Profiles;
using Govor.Application.PushNotifications;
using Govor.Application.PushNotifications.Providers;
using Govor.Application.Storage;
using Govor.Application.Synching;
using Govor.Application.Users;
using Govor.Application.Users.UserOnlineStatus;
using Govor.Application.Users.UserSessions;
using Govor.Application.Users.UserSessions.Crypto;
using Govor.Domain;
using Microsoft.EntityFrameworkCore;
namespace Govor.API.Common.Extensions;
@@ -56,6 +37,7 @@ public static class ConfigurationProgramExtensions
services.AddScoped<IAccountService, AuthService>();
services.AddScoped<IUsersAdministration, UsersService>();
services.AddScoped<IInvitesService, InvitesService>();
services.AddScoped<IInvitationGetter, InvitationGetter>();
services.AddScoped<IInvitationGenerator, InvitationGenerator>();
services.AddScoped<ISynchingService, SynchingService>();
@@ -80,7 +62,10 @@ public static class ConfigurationProgramExtensions
services.AddScoped<IUserGroupsGetterService, UserGroupsGetterService>();
services.AddScoped<IMessageCommandService, MessageCommandService>();
//services.AddScoped<IMessageCommandService, MessageCommandService>();
services.AddScoped<IMessageSendingService, MessageSendingService>();
services.AddScoped<IMessageEditingService, MessageEditingService>();
services.AddScoped<IMessageRemovingService, MessageRemovingService>();
services.AddScoped<IVerifyFriendship, VerifyFriendship>();
services.AddScoped<IUserPrivateChatsGetterService, UserPrivateChatsGetter>();
services.AddScoped<IUserPrivateChatsCreator, UserPrivateChatsCreator>();
@@ -88,6 +73,9 @@ public static class ConfigurationProgramExtensions
services.AddScoped<IMediaService, MediaService>();
services.AddScoped<IAccesserToDownloadMedia, AccesserToDownloadMediaService>();
// User
services.AddScoped<IUserNameExistValidator, UserNameExistValidator>();
// UserSession
services.AddScoped<IUserSessionOpener, UserSessionOpener>();
services.AddScoped<IUserSessionRefresher, UserSessionRefresher>();
@@ -104,6 +92,7 @@ public static class ConfigurationProgramExtensions
services.AddSingleton<IConnectionStore, ConnectionStore>();
// Pushs
services.AddScoped<IPushTokenService, PushTokenService>();
services.AddScoped<IPushNotificationService, PushNotificationService>();
services.AddSingleton<IPushNotificationProvider, FirebasePushProvider>();
@@ -123,33 +112,6 @@ public static class ConfigurationProgramExtensions
services.AddScoped<IProfileService, ProfileService>();
}
public static void AddRepositories(this IServiceCollection services)
{
services.AddScoped<IUsersRepository, UsersRepository>();
services.AddScoped<IMessagesRepository, MessagesRepository>();
services.AddScoped<IInvitesRepository, InvitesRepository>();
services.AddScoped<IAdminsRepository, AdminsRepository>();
services.AddScoped<IMediaAttachmentsRepository, MediaAttachmentsRepository>();
services.AddScoped<IFriendshipsRepository, FriendshipsRepository>();
services.AddScoped<IPrivateChatsRepository, PrivateChatsRepository>();
services.AddScoped<IGroupsRepository, GroupRepository>();
services.AddScoped<IUserSessionsRepository, UserSessionsRepository>();
services.AddScoped<IPushTokenRepository, PushTokenRepository>();
// other
}
public static void AddValidators(this IServiceCollection services)
{
services.AddScoped<IObjectValidator<User>, UserValidator>();
services.AddScoped<IObjectValidator<Message>, MessageValidator>();
services.AddScoped<IObjectValidator<MediaAttachments>, MediaAttachmentsValidator>();
services.AddScoped<IObjectValidator<Admin>, AdminValidator>();
services.AddScoped<IObjectValidator<Invitation>, InvitationValidator>();
services.AddScoped<IObjectValidator<Friendship>, FriendshipValidator>();
services.AddScoped<IObjectValidator<PrivateChat>, PrivateChatValidator>();
services.AddScoped<IObjectValidator<ChatGroup>, ChatGroupValidator>();
}
public static void AddGovorDbContext(this IServiceCollection services, IConfiguration configuration)
{
var useMySql = configuration.GetValue<bool>("UseMySql");
+3 -4
View File
@@ -1,11 +1,10 @@
using AutoMapper;
using Govor.API.Extensions.Mapping;
using Govor.Application.Profiles;
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Core.Models.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Users;
namespace Govor.API.Common.Mapping;
@@ -1,8 +1,7 @@
using AutoMapper;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Application.Profiles;
using Govor.Application.Users.UserOnlineStatus;
using Govor.Contracts.DTOs;
using Govor.Core.Models.Users;
namespace Govor.API.Common.Mapping;
@@ -1,9 +1,9 @@
using AutoMapper;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Application.Users.UserOnlineStatus;
using Govor.Contracts.DTOs;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
namespace Govor.API.Extensions.Mapping;
namespace Govor.API.Common.Mapping;
public class UserToUserDtoMappingAction : IMappingAction<User, UserDto>
{
@@ -1,8 +1,3 @@
using Govor.Contracts.DTOs;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Friendships;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -14,14 +9,8 @@ namespace Govor.API.Controllers.AdminStuff;
public class FriendshipsController : Controller
{
private readonly ILogger<FriendshipsController> _logger;
private readonly IFriendshipsRepository _friendshipsRepository;
public FriendshipsController(ILogger<FriendshipsController> logger, IFriendshipsRepository friendshipsRepository)
{
_logger = logger;
_friendshipsRepository = friendshipsRepository;
}
/*
[HttpGet]
public async Task<IActionResult> Get()
{
@@ -88,5 +77,5 @@ public class FriendshipsController : Controller
_logger.LogError(ex, ex.Message);
return StatusCode(500, new { error = "Internal server error." });
}
}
}*/
}
@@ -1,8 +1,6 @@
using Govor.Application.Interfaces;
using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Govor.Core.Repositories.Invaites;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.AdminStuff;
@@ -12,17 +10,17 @@ namespace Govor.API.Controllers.AdminStuff;
//[Authorize(Roles = "Admin")]
public class InviteUserController : Controller
{
private readonly IInvitesRepository _repository;
private readonly IInvitationGetter _invitationGetter;
private readonly IInvitationGenerator _invitationGenerator;
private readonly ILogger<InviteUserController> _logger;
public InviteUserController(IInvitationGenerator invitationGenerator,
IInvitesRepository repository,
IInvitationGetter invitationGetter,
ILogger<InviteUserController> logger)
{
_invitationGenerator = invitationGenerator;
_logger = logger;
_repository = repository;
_invitationGetter = invitationGetter;
}
[HttpPost("[action]")]
@@ -51,7 +49,7 @@ public class InviteUserController : Controller
{
_logger.LogInformation("Getting all active invitations by administrator");
var read = await _repository.GetAllAsync();
var read = await _invitationGetter.GetAllAsync();
var result = read.Where(x => x.IsActive).ToList();
List<InvitationResponses> dtos = new List<InvitationResponses>();
@@ -86,7 +84,7 @@ public class InviteUserController : Controller
try
{
_logger.LogInformation("Getting all invitations by administrator");
var read = await _repository.GetAllAsync();
var read = await _invitationGetter.GetAllAsync();
List<InvitationResponses> dtos = new List<InvitationResponses>();
@@ -120,18 +118,22 @@ public class InviteUserController : Controller
try
{
_logger.LogInformation("Getting invitations {id} by administrator");
var read = await _repository.FindByIdAsync(id);
var read = await _invitationGetter.FindByIdAsync(id);
if(read.IsFailure)
return NotFound(read.Error);
var dto = read.Value;
var response = new InvitationResponses(){
Id = read.Id,
Description = read.Description,
IsAdmin = read.IsAdmin,
MaxParticipants = read.MaxParticipants,
Code = read.Code,
CreatedAt = read.DateCreated,
EndAt = read.EndDate,
IsActive = read.IsActive,
ParticipantCount = read.Users.Count,
Id = dto.Id,
Description = dto.Description,
IsAdmin = dto.IsAdmin,
MaxParticipants = dto.MaxParticipants,
Code = dto.Code,
CreatedAt = dto.DateCreated,
EndAt = dto.EndDate,
IsActive = dto.IsActive,
ParticipantCount = dto.Users.Count,
};
return Ok(response);
@@ -1,10 +1,7 @@
using Govor.Application.Interfaces;
using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Contracts.Responses.Admins;
using Govor.Core.Infrastructure.Extensions;
using Govor.Core.Models.Users;
using Govor.Data.Repositories.Exceptions;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.AdminStuff;
@@ -54,11 +51,6 @@ public class UsersController : Controller
var read = await _users.GetUserById(id);
return Ok(BuildUserDtos([read]).First());
}
catch (NotFoundByKeyException<Guid> ex)
{
_logger.LogWarning(ex, ex.Message);
return NotFound(ex.Message);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
@@ -1,7 +1,6 @@
using Govor.Application.Exceptions.AuthService;
using Govor.Application.Exceptions.InvitesService;
using Govor.Application.Interfaces.Authentication;
using Govor.Application.Interfaces.UserSession;
using Govor.Application.Authentication;
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Users.UserSessions;
using Govor.Contracts.Requests;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -30,82 +29,83 @@ public class AuthController : Controller
_logger = logger;
}
//[RequireHttps]
[HttpPost("register")] // api/auth/register
public async Task<IActionResult> Register([FromBody] RegistrationRequest registrationRequest)
{
try
var inviteResult = await _invitesService.ValidateAsync(registrationRequest.InviteLink);
if (!inviteResult.IsSuccess)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var invite = await _invitesService.ValidateAsync(registrationRequest.InviteLink);
var user = await _accountService.RegistrationAsync(registrationRequest.Name, registrationRequest.Password,
invite);
_logger.LogInformation($"Register request for {user.Username} with id {user.Id} processed successfully");
var tokens = await _userSession.OpenSessionAsync(user, registrationRequest.DeviceInfo);
_logger.LogInformation($"Session for user {user.Username} with id {user.Id} has been opened");
return Ok(tokens);
_logger.LogWarning("Invite link invalid: {InviteLink}. Error: {Error}", registrationRequest.InviteLink,
inviteResult.Error);
return BadRequest($"Invite link invalid: {inviteResult.Error.Message}");
}
catch (UserAlreadyExistException ex)
var userResult = await _accountService.RegistrationAsync(
registrationRequest.Name,
registrationRequest.Password,
inviteResult.Value);
if (userResult.IsFailure)
{
_logger.LogWarning(ex, $"Registration failed for user {registrationRequest.Name}");
return BadRequest("Registration failed: user already exists.");
}
catch (InviteLinkInvalidException ex)
_logger.LogWarning("Registration failed for user {Name}. Error: {Error}", registrationRequest.Name,
userResult.Error);
return userResult.Error.Code switch
{
_logger.LogWarning(ex, $"Invite link invalid: {registrationRequest.InviteLink}");
return BadRequest("Invite link invalid.");
}
catch (InvalidUsernameException ex)
{
_logger.LogWarning(ex, $"Invalid username: {registrationRequest.Name}");
return BadRequest($"Invalid username: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error during registration for user {Name}", registrationRequest.Name);
return StatusCode(500, "An unexpected error occurred. Please try again later.");
}
nameof(UserAlreadyExistException) => BadRequest($"Registration failed: {userResult.Error.Message}"),
nameof(InvalidUsernameException) => BadRequest($"Invalid username: {userResult.Error.Message}"),
_ => BadRequest($"Registration failed: {userResult.Error.Message}")
};
}
//[RequireHttps]
var user = userResult.Value;
_logger.LogInformation("Register request for {Username} with id {Id} processed successfully", user.Username,
user.Id);
var sessionResult = await _userSession.OpenSessionAsync(user, registrationRequest.DeviceInfo);
if (sessionResult.IsFailure)
{
_logger.LogError("Failed to open session for user {Username}. Error: {Error}", user.Username,
sessionResult.Error.Message);
return StatusCode(500, "An error occurred while creating the session.");
}
_logger.LogInformation("Session for user {Username} with id {Id} has been opened", user.Username, user.Id);
return Ok(sessionResult.Value);
}
[HttpPost("login")] // api/auth/login
public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
{
try
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var userResult = await _accountService.LoginAsync(loginRequest.Name, loginRequest.Password);
var user = await _accountService.LoginAsync(loginRequest.Name, loginRequest.Password);
_logger.LogInformation($"Login request for {user.Username} with id {user.Id} processed successfully");
var tokens = await _userSession.OpenSessionAsync(user, loginRequest.DeviceInfo);
_logger.LogInformation($"Session for user {user.Username} with id {user.Id} has been opened");
return Ok(tokens);
}
catch (UserNotRegisteredException ex)
if (userResult.IsFailure)
{
_logger.LogWarning(ex, "Login failed for user {Name}", loginRequest.Name);
return BadRequest("Login failed: user does not exist.");
}
catch (LoginUserException ex)
_logger.LogWarning("Login failed for user {Name}. Error: {Code}", loginRequest.Name, userResult.Error);
return userResult.Error.Code switch
{
_logger.LogWarning(ex, "Login failed for user {Name}", loginRequest.Name);
return BadRequest("Login failed: username or password is incorrect.");
nameof(UserNotRegisteredException) => BadRequest("Login failed: user does not exist."),
nameof(InvalidOperationException) => BadRequest("Login failed: username or password is incorrect."),
_ => BadRequest($"Login failed: {userResult.Error.Message}")
};
}
catch (Exception ex)
var user = userResult.Value;
_logger.LogInformation("Login request for {Username} with id {Id} processed successfully", user.Username, user.Id);
var sessionResult = await _userSession.OpenSessionAsync(user, loginRequest.DeviceInfo);
if (sessionResult.IsFailure)
{
_logger.LogError(ex, "Unexpected error during login for user {Name}", loginRequest.Name);
return StatusCode(500, "An unexpected error occurred. Please try again later.");
}
_logger.LogError("Failed to open session for user {Username}. Error: {Error}", user.Username, sessionResult.Error);
return StatusCode(500, "An error occurred while creating the session.");
}
_logger.LogInformation("Session for user {Username} with id {Id} has been opened", user.Username, user.Id);
return Ok(sessionResult.Value);
}
}
@@ -1,4 +1,4 @@
using Govor.Application.Interfaces.UserSession;
using Govor.Application.Users.UserSessions;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses;
using Microsoft.AspNetCore.Authorization;
@@ -26,36 +26,30 @@ public class RefreshController : Controller
[HttpPost("refresh")] // api/auth/token/refresh
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest refreshRequest)
{
try
if (string.IsNullOrWhiteSpace(refreshRequest.RefreshToken))
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (string.IsNullOrEmpty(refreshRequest.RefreshToken))
throw new InvalidOperationException("Refresh token cant be empty.");
_logger.LogWarning("Refresh request failed: token is empty.");
return BadRequest("Refresh token can't be empty.");
}
var result = await _userSession.RefreshTokenAsync(refreshRequest.RefreshToken);
return Ok(new RefreshTokenResponse()
if (result.IsFailure)
{
AccessToken = result.accessToken,
RefreshToken = result.refreshToken
_logger.LogWarning("Refresh token failed. Error Code: {Code}", result.Error.Code);
return result.Error.Code switch
{
"Auth.EmptyToken" => BadRequest(result.Error.Message),
"Auth.InvalidToken" => Unauthorized(result.Error.Message),
_ => BadRequest($"Refresh failed: {result.Error.Message}")
};
}
return Ok(new RefreshTokenResponse
{
AccessToken = result.Value.accessToken,
RefreshToken = result.Value.refreshToken
});
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Invalid refresh token.");
return BadRequest(ex.Message);
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, "Refresh token failed.");
return Unauthorized("Invalid refresh token");
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return StatusCode(500, "An unexpected error occurred.");
}
}
}
@@ -1,7 +1,6 @@
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.UserSession;
using Govor.Application.Interfaces.UserSession.Crypto;
using Govor.Application.Friends;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Users.UserSessions.Crypto;
using Govor.Contracts.Requests;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+2 -28
View File
@@ -1,9 +1,8 @@
using AutoMapper;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Messages;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -52,16 +51,6 @@ public class ChatLoadController : Controller
return Ok(response);
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, ex.Message);
@@ -95,21 +84,6 @@ public class ChatLoadController : Controller
return Ok(response);
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, ex.Message);
@@ -1,8 +1,7 @@
using AutoMapper;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Friends;
using Govor.Application.Infrastructure.Extensions;
using Govor.Contracts.DTOs;
using Govor.Core.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -41,16 +40,6 @@ public class FriendsRequestQueryController : Controller
return Ok(response);
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, ex.Message);
return Ok(new List<FriendshipDto>());
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
@@ -72,16 +61,6 @@ public class FriendsRequestQueryController : Controller
return Ok(response);
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, ex.Message);
return Ok(new List<FriendshipDto>());
}
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
@@ -1,9 +1,7 @@
using AutoMapper;
using Govor.Application.Exceptions.FriendsService;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Friends;
using Govor.Application.Infrastructure.Extensions;
using Govor.Contracts.DTOs;
using Govor.Core.Models.Users;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.Friends;
+2 -2
View File
@@ -1,5 +1,5 @@
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Groups;
using Govor.Application.Infrastructure.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+3 -3
View File
@@ -1,7 +1,7 @@
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Medias;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Domain.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -1,6 +1,6 @@
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.PingHandler;
using Govor.Application.Users.UserOnlineStatus;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -40,16 +40,6 @@ public class OnlinePingingController : Controller
_logger.LogInformation($"Ping from user {id} processed successfully");
return Ok();
}
catch (InvalidOperationException e)
{
_logger.LogError(e, e.Message);
return BadRequest("User can't be found in our database.");
}
catch (UnauthorizedAccessException e)
{
_logger.LogError(e, e.Message);
return Forbid(e.Message);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
+10 -21
View File
@@ -1,10 +1,9 @@
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Exceptions.VerifyFriendship;
using Govor.Application.Friends;
using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.PrivateUserChats;
using Govor.Contracts.DTOs;
using Govor.Core.Models;
using Govor.Core.Repositories.PrivateChats;
using Govor.Core.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -16,7 +15,6 @@ namespace Govor.API.Controllers;
public class PrivateChatController : Controller
{
private readonly ICurrentUserService _currentUser;
private readonly IUsersRepository _usersRepository;
private readonly IVerifyFriendship _verifyFriendship;
private readonly IUserPrivateChatsCreator _userPrivateChatsCreator;
private readonly IUserPrivateChatsGetterService _privateChatsGetter;
@@ -24,15 +22,12 @@ public class PrivateChatController : Controller
public PrivateChatController(
ICurrentUserService currentUser,
IUsersRepository usersRepository,
IVerifyFriendship verifyFriendship,
IPrivateChatsRepository privateChats,
IUserPrivateChatsCreator userPrivateChatsCreator,
IUserPrivateChatsGetterService userPrivateChatsGetterService,
ILogger<ChatLoadController> logger)
{
_currentUser = currentUser;
_usersRepository = usersRepository;
_verifyFriendship = verifyFriendship;
_userPrivateChatsCreator = userPrivateChatsCreator;
_privateChatsGetter = userPrivateChatsGetterService;
@@ -46,12 +41,6 @@ public class PrivateChatController : Controller
{
var currentId = _currentUser.GetCurrentUserId();
if (!await _usersRepository.ExistsByIdAsync(friendId))
{
_logger.LogWarning("User not exist {0}", friendId);
return NotFound("User not exist.");
}
await _verifyFriendship.VerifyAsync(currentId, friendId);
var chat = await _userPrivateChatsCreator.CreateAsync(currentId, friendId);
@@ -62,16 +51,16 @@ public class PrivateChatController : Controller
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, ex.Message);
return BadRequest(ex.Message);
}
catch (FriendshipException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
+9 -16
View File
@@ -1,12 +1,11 @@
using AutoMapper;
using Govor.API.Hubs;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.Medias;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Medias;
using Govor.Application.Profiles;
using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Govor.Core.Models;
using Govor.Data.Repositories.Exceptions;
using Govor.Domain.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
@@ -91,8 +90,12 @@ public class ProfileController : ControllerBase
try
{
var userId = _currentUserService.GetCurrentUserId();
var user = await _profileService.GetUserProfileAsync(userId);
var result = await _profileService.GetUserProfileAsync(userId);
if(result.IsFailure)
return NotFound(result.Error);
var user = result.Value;
var dto = _mapper.Map<UserProfileDto>(user);
return Ok(dto);
}
@@ -101,11 +104,6 @@ public class ProfileController : ControllerBase
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return NotFound("Profile not found");
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
@@ -128,11 +126,6 @@ public class ProfileController : ControllerBase
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return NotFound("Profile not found");
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
@@ -1,6 +1,6 @@
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.PushNotifications;
using Govor.Contracts.Requests;
using Govor.Core.Repositories.PushTokens;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -13,15 +13,15 @@ public class PushTokensController : Controller
{
private readonly ICurrentUserService _currentUser;
private readonly ICurrentUserSessionService _currentSession;
private readonly IPushTokenRepository _pushTokenRepo;
private readonly IPushTokenService _pushTokenService;
public PushTokensController(
IPushTokenService pushTokenService,
ICurrentUserService currentUser,
ICurrentUserSessionService currentSession,
IPushTokenRepository pushTokenRepository)
ICurrentUserSessionService currentSession)
{
_pushTokenService = pushTokenService;
_currentUser = currentUser;
_pushTokenRepo = pushTokenRepository;
_currentSession = currentSession;
}
@@ -39,7 +39,7 @@ public class PushTokensController : Controller
var currentId = _currentUser.GetCurrentUserId();
var currentSessionId = _currentSession.GetUserSessionId();
await _pushTokenRepo.AddOrUpdateTokenAsync(
await _pushTokenService.AddOrUpdateTokenAsync(
userId: currentId,
sessionId: currentSessionId,
token: req.Token,
+21 -18
View File
@@ -1,9 +1,7 @@
using AutoMapper;
using Govor.Application.Interfaces.Infrastructure.Extensions;
using Govor.Application.Interfaces.UserSession;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Users.UserSessions;
using Govor.Contracts.DTOs;
using Govor.Core.Repositories.PushTokens;
using Govor.Data.Repositories.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -43,7 +41,11 @@ public class SessionController : Controller
try
{
var sessions = await _userSessionReader.GetAllSessionsAsync(_currentUserService.GetCurrentUserId());
return Ok(_mapper.Map<List<SessionDto>>(sessions));
if(sessions.IsFailure)
return NotFound(sessions.Error);
return Ok(_mapper.Map<List<SessionDto>>(sessions.Value));
}
catch (UnauthorizedAccessException ex)
{
@@ -65,8 +67,12 @@ public class SessionController : Controller
if (sessionId == Guid.Empty)
return BadRequest("Invalid sessionId.");
await _userSessionRevoker.CloseSessionByIdAsync(sessionId,
var res = await _userSessionRevoker.CloseSessionByIdAsync(sessionId,
_currentUserService.GetCurrentUserId());
if (res.IsFailure)
return BadRequest(res.Error);
return Ok();
}
catch (InvalidOperationException ex)
@@ -79,11 +85,6 @@ public class SessionController : Controller
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
@@ -96,10 +97,13 @@ public class SessionController : Controller
{
try
{
await _userSessionRevoker.CloseSessionByIdAsync(
var res = await _userSessionRevoker.CloseSessionByIdAsync(
_currentUserSessionService.GetUserSessionId(),
_currentUserService.GetCurrentUserId());
if(res.IsFailure)
return NotFound(res.Error);
return Ok();
}
catch (InvalidOperationException ex)
@@ -112,11 +116,6 @@ public class SessionController : Controller
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
}
catch (NotFoundException ex)
{
_logger.LogWarning(ex, ex.Message);
return NotFound(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
@@ -129,7 +128,11 @@ public class SessionController : Controller
{
try
{
await _userSessionRevoker.CloseAllSessionsAsync(_currentUserService.GetCurrentUserId());
var res = await _userSessionRevoker.CloseAllSessionsAsync(_currentUserService.GetCurrentUserId());
if(res.IsFailure)
return NotFound(res.Error);
return Ok();
}
catch (UnauthorizedAccessException ex)
-1
View File
@@ -70,7 +70,6 @@ public class HubExceptionFilter : IHubFilter
}
}
// Ничего не возвращаем, если не поддерживается
return null;
}
}
+1 -4
View File
@@ -24,10 +24,7 @@
<ItemGroup>
<ProjectReference Include="..\Govor.Application\Govor.Application.csproj" />
<ProjectReference Include="..\Govor.Contracts\Govor.Contracts.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Contracts\" />
<ProjectReference Include="..\Govor.Domain\Govor.Domain.csproj" />
</ItemGroup>
</Project>
+15 -11
View File
@@ -1,11 +1,11 @@
using Govor.API.Common.SignalR.Helpers;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Exceptions.VerifyFriendship;
using Govor.Application.Interfaces.Messages;
using Govor.Application.Interfaces.Messages.Parameters;
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Contracts.Requests.SignalR;
using Govor.Contracts.Responses.SignalR;
using Govor.Core.Models.Messages;
using Govor.Domain.Models.Messages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
@@ -15,20 +15,24 @@ namespace Govor.API.Hubs;
public class ChatsHub : Hub
{
private readonly ILogger<ChatsHub> _logger;
private readonly IMessageCommandService _commandService;
private readonly IMessageSendingService _messageSendingService;
private readonly IMessageEditingService _messageEditingService;
private readonly IMessageRemovingService _messageRemovingService;
private readonly IHubUserAccessor _userAccessor;
private readonly IChatNotificationService _notifier;
private readonly IConnectionManager _connectionManager;
public ChatsHub(
ILogger<ChatsHub> logger,
IMessageCommandService commandService,
public ChatsHub(ILogger<ChatsHub> logger,
IMessageSendingService messageSendingService,
IMessageEditingService messageEditingService,
IHubUserAccessor userAccessor,
IChatNotificationService notifier,
IConnectionManager connectionManager)
{
_logger = logger;
_commandService = commandService;
_messageSendingService = messageSendingService;
_messageEditingService = messageEditingService;
_userAccessor = userAccessor;
_notifier = notifier;
_connectionManager = connectionManager;
@@ -69,7 +73,7 @@ public class ChatsHub : Hub
ValidateMessageRequest(request);
var sendParams = MapToSendMessage(request, userId);
var result = await _commandService.SendMessageAsync(sendParams);
var result = await _messageSendingService.SendMessageAsync(sendParams);
if (!result.IsSuccess)
throw new InvalidOperationException(result.Exception.Message ?? "Failed to send message");
@@ -87,7 +91,7 @@ public class ChatsHub : Hub
{
return await SafeExecute(async (userId) =>
{
var result = await _commandService.DeleteMessageAsync(new DeleteMessage(userId, request.MessageId));
var result = await _messageRemovingService.DeleteMessageAsync(new DeleteMessage(userId, request.MessageId));
if (!result.IsSuccess || result.OriginalMessage == null)
throw new InvalidOperationException("Message deletion failed");
@@ -112,7 +116,7 @@ public class ChatsHub : Hub
return await SafeExecute(async (userId) =>
{
var editParams = new EditMessage(userId, request.MessageId, request.NewEncryptedContent, DateTime.UtcNow);
var result = await _commandService.EditMessageAsync(editParams);
var result = await _messageEditingService.EditMessageAsync(editParams);
if (!result.IsSuccess || result.OriginalMessage == null)
throw new InvalidOperationException("Edit message error");
+21 -4
View File
@@ -1,7 +1,7 @@
using AutoMapper;
using Govor.API.Common.SignalR.Helpers;
using Govor.Application.Exceptions.FriendsService;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Friends;
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.SignalR;
@@ -76,7 +76,12 @@ public class FriendsHub : Hub
try
{
var userId = _userAccessor.GetUserId(Context);
var friendship = await _friendRequestService.SendAsync(userId, targetUserId);
var result = await _friendRequestService.SendAsync(userId, targetUserId);
if(result.IsFailure)
return HubResult<object>.Error(result.Error.ToString());
var friendship = result.Value;
var dto = _mapper.Map<FriendshipDto>(friendship);
await Clients.Group(targetUserId.ToString())
@@ -115,7 +120,13 @@ public class FriendsHub : Hub
try
{
var userId = _userAccessor.GetUserId(Context);
var friendship = await _friendRequestService.AcceptAsync(friendshipId, userId);
var result = await _friendRequestService.AcceptAsync(friendshipId, userId);
if(result.IsFailure)
return HubResult<object>.BadRequest(result.Error.ToString());
var friendship = result.Value;
var dto = _mapper.Map<FriendshipDto>(friendship);
await Clients.Group(userId.ToString())
@@ -149,7 +160,13 @@ public class FriendsHub : Hub
try
{
var userId = _userAccessor.GetUserId(Context);
var friendship = await _friendRequestService.RejectAsync(friendshipId, userId);
var result = await _friendRequestService.RejectAsync(friendshipId, userId);
if(result.IsFailure)
return HubResult<object>.BadRequest(result.Error.ToString());
var friendship = result.Value;
var dto = _mapper.Map<FriendshipDto>(friendship);
await Clients.Group(userId.ToString())
@@ -1,9 +1,8 @@
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.PushNotifications;
using Govor.Application.PrivateUserChats;
using Govor.Application.Profiles;
using Govor.Application.PushNotifications;
using Govor.Contracts.Responses.SignalR;
using Govor.Core.Models.Messages;
using Govor.Core.Repositories.PrivateChats;
using Govor.Core.Repositories.PushTokens;
using Govor.Domain.Models.Messages;
using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Hubs.Infrastructure;
@@ -11,19 +10,20 @@ namespace Govor.API.Hubs.Infrastructure;
public class ChatNotificationService : IChatNotificationService
{
private readonly IHubContext<ChatsHub> _hubContext;
private readonly IPrivateChatsRepository _privateChatsRepository;
private readonly IPushNotificationService _notificationService;
private readonly IUserPrivateChatsGetterService _userPrivateChatsGetterService;
private readonly IProfileService _profileService;
public ChatNotificationService(
IProfileService profileService,
IHubContext<ChatsHub> hubContext,
IPushNotificationService notificationService,
IPrivateChatsRepository privateChatsRepository)
IUserPrivateChatsGetterService userPrivateChatsGetterService,
IProfileService profileService)
{
_hubContext = hubContext;
_profileService = profileService;
_notificationService = notificationService;
_privateChatsRepository = privateChatsRepository;
_userPrivateChatsGetterService = userPrivateChatsGetterService;
_profileService = profileService;
}
public async Task NotifyMessageSentAsync(UserMessageResponse message)
@@ -47,12 +47,22 @@ public class ChatNotificationService : IChatNotificationService
private async Task NotifyMessageReceivedInPrivateChatAsync(UserMessageResponse message)
{
var privateChat = await _privateChatsRepository.GetByIdAsync(message.RecipientId);
var result = await _userPrivateChatsGetterService.GetPrivateChatAsync(message.RecipientId);
if(result.IsFailure)
return;
var privateChat = result.Value;
var text = message.EncryptedContent.Substring(0, Math.Min(40, message.EncryptedContent.Length));
var userId = message.SenderId == privateChat.UserAId ? privateChat.UserBId : privateChat.UserAId;
var profile = await _profileService.GetUserProfileAsync(message.SenderId);
var resultProf = await _profileService.GetUserProfileAsync(message.SenderId);
if(resultProf.IsFailure)
return;
var profile = resultProf.Value;
var title = profile.Username;
Dictionary<string, string> data = new Dictionary<string, string>();
@@ -1,5 +1,8 @@
using System.Collections.Concurrent;
using Govor.Application.Groups;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Interfaces;
using Govor.Application.PrivateUserChats;
using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Hubs.Infrastructure;
@@ -1,5 +1,5 @@
using System.Collections.Concurrent;
using Govor.Application.Interfaces;
using Govor.Application.Infrastructure.Extensions;
namespace Govor.API.Hubs.Infrastructure;
@@ -1,7 +1,9 @@
using Govor.API.Hubs;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Interfaces;
using Govor.Core.Models;
using Govor.Application.PrivateUserChats;
using Govor.Domain.Models;
using Microsoft.AspNetCore.SignalR;
namespace Govor.API.Hubs.Infrastructure;
+2 -29
View File
@@ -1,6 +1,5 @@
using Govor.API.Common.SignalR.Helpers;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Core.Repositories.Users;
using Govor.Application.Users.UserOnlineStatus;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR;
@@ -15,17 +14,14 @@ public class PresenceHub : Hub
private readonly IUserNotificationScopeService _scopeService;
private readonly IOnlineUserStore _onlineUserStore;
private readonly IHubUserAccessor _userAccessor;
private readonly IUsersRepository _users;
public PresenceHub(
ILogger<PresenceHub> logger,
IUserNotificationScopeService scopeService,
IOnlineUserStore onlineUserStore,
IHubUserAccessor userAccessor,
IUsersRepository users)
IHubUserAccessor userAccessor)
{
_logger = logger;
_users = users;
_scopeService = scopeService;
_onlineUserStore = onlineUserStore;
_userAccessor = userAccessor;
@@ -78,33 +74,10 @@ public class PresenceHub : Hub
var isLastConnection = _onlineUserStore.RemoveConnection(userId, Context.ConnectionId);
if (isLastConnection)
{
_ = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5));
var currentConnections = _onlineUserStore.GetConnections(userId);
if (currentConnections == null || !currentConnections.Any())
{
var friends = await _scopeService.GetNotifiedUsers(userId);
await Clients.Groups(friends.Select(f => f.ToString()).ToList())
.SendAsync("UserOffline", userId);
try
{
var user = await _users.FindByIdAsync(userId);
if (user != null)
{
user.WasOnline = DateTime.UtcNow;
await _users.UpdateAsync(user);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating WasOnline for {UserId}", userId);
}
}
});
}
await base.OnDisconnectedAsync(exception);
+4 -7
View File
@@ -1,10 +1,10 @@
using Govor.API.Common.SignalR.Helpers;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.Medias;
using Govor.Application.Friends;
using Govor.Application.Medias;
using Govor.Application.Profiles;
using Govor.Application.Synching;
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses.SignalR;
using Govor.Core.Repositories.Groups;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
@@ -13,7 +13,6 @@ namespace Govor.API.Hubs;
[Authorize]
public class ProfileHub : Hub
{
private readonly IGroupsRepository _groupsRepository;
private readonly IFriendshipService _friendsService;
private readonly IProfileService _profileService;
private readonly IHubUserAccessor _userAccessor;
@@ -22,7 +21,6 @@ public class ProfileHub : Hub
private readonly IMediaService _mediaService;
public ProfileHub(
IGroupsRepository groupsRepository,
IFriendshipService friendsService,
IProfileService profileService,
IHubUserAccessor userAccessor,
@@ -30,7 +28,6 @@ public class ProfileHub : Hub
IMediaService mediaService,
ILogger<ProfileHub> logger)
{
_groupsRepository = groupsRepository;
_friendsService = friendsService;
_profileService = profileService;
_userAccessor = userAccessor;
+3 -6
View File
@@ -3,7 +3,7 @@ using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using Govor.API.Common.Extensions;
using Govor.API.Hubs;
using Govor.Application.Services.Authentication;
using Govor.Application.Authentication.JWT;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
@@ -29,7 +29,6 @@ builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnC
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("secrets/firebase-adminsdk.json")
// или FromStream(File.OpenRead("firebase-adminsdk.json"))
});
builder.Services.AddCors(options =>
@@ -81,9 +80,6 @@ builder.Services.AddControllers();
// Init DI
builder.Services.AddServices();
builder.Services.AddRepositories();
builder.Services.AddValidators();
builder.Services.AddOptionsConfiguration(configuration);
builder.Services.AddGovorDbContext(configuration); // GovorDbContext init
@@ -125,6 +121,7 @@ if (!app.Environment.IsDevelopment())
{
//app.MapOpenApi();
builder.WebHost.UseUrls("http://0.0.0.0:8080");
builder.WebHost.UseUrls("http://10.8.0.5:5000");
//builder.WebHost.UseUrls("http://192.168.1.107:8080");
}
@@ -142,7 +139,7 @@ app.UseAuthorization();
app.MapControllers();
app.Map("/server/ping",
app.MapGet("/server/ping",
() => new OkResult());
app.MapHub<ChatsHub>("/hubs/chats");
+1 -1
View File
@@ -5,7 +5,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://0.0.0.0:8080;http://localhost:7155",
"applicationUrl": "http://0.0.0.0:8080;http://localhost:7155;http://10.8.0.5:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
+1 -1
View File
@@ -6,7 +6,7 @@
}
},
"ConnectionStrings": {
"GovorDbContext": "Host=46.19.68.182;Port=5432;Database=default_db;Username=main;Password=1M^rf!1JKL:y,w;"
"GovorDbContext": "Host=localhost;Port=5432;Database=GovorDb;Username=postgres;Password=stalcker;"
},
"UseMySql": false,
"AllowedHosts": "*",
+1 -1
View File
@@ -6,7 +6,7 @@
}
},
"ConnectionStrings": {
"GovorDbContext": "Host=46.19.68.182;Port=5432;Database=default_db;Username=main;Password=1M^rf!1JKL:y,w;"
"GovorDbContext": "Host=localhost;Port=5432;Database=GovorDb;Username=postgres;Password=stalcker;"
},
"UseMySql": false,
"AllowedHosts": "*",
@@ -1,8 +1,8 @@
using AutoFixture;
using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Application.Interfaces;
using Govor.Core.Models;
using Govor.Core.Repositories.Invaites;
using Govor.Domain.Models;
using Govor.Domain.Repositories.Invaites;
using Moq;
namespace Govor.Application.Tests.Infrastructure.AdminsStuff;
@@ -1,4 +1,4 @@
using Govor.Application.Exceptions.AuthService;
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Infrastructure.Validators;
using Microsoft.Extensions.Configuration;
@@ -1,12 +1,12 @@
using AutoFixture;
using Govor.Core.Infrastructure.Extensions;
using Govor.Core.Models;
using Govor.Core.Repositories.Users;
using Govor.Application.Exceptions.AuthService;
using Govor.Domain.Infrastructure.Extensions;
using Govor.Domain.Models;
using Govor.Domain.Repositories.Users;
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Interfaces.Authentication;
using Govor.Application.Services.Authentication;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Admins;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.Admins;
using Moq;
namespace Govor.Application.Tests.Services.Authentication;
@@ -4,7 +4,7 @@ using System.Text;
using AutoFixture;
using Govor.Application.Interfaces.Authentication;
using Govor.Application.Services.Authentication;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Moq;
@@ -2,10 +2,11 @@ using AutoFixture;
using Govor.Application.Exceptions.FriendsService;
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Friends;
using Govor.Application.PrivateUserChats;
using Govor.Application.Services.Friends;
using Govor.Core.Models;
using Govor.Core.Repositories.Friendships;
using Govor.Core.Repositories.Users;
using Govor.Domain.Models;
using Govor.Domain.Repositories.Friendships;
using Govor.Domain.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Moq;
@@ -1,10 +1,10 @@
using AutoFixture;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Services.Friends;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Friendships;
using Govor.Core.Repositories.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.Friendships;
using Govor.Domain.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Moq;
@@ -1,10 +1,10 @@
using AutoFixture;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Services.Friends;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Friendships;
using Govor.Core.Repositories.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.Friendships;
using Govor.Domain.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Moq;
@@ -1,6 +1,6 @@
using Govor.Application.Services.Medias;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Data;
using Microsoft.EntityFrameworkCore;
@@ -2,13 +2,14 @@
using Govor.Application.Interfaces;
using Govor.Application.Interfaces.Medias;
using Govor.Application.Interfaces.Messages.Parameters;
using Govor.Application.PrivateUserChats;
using Govor.Application.Services.Messages;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Core.Repositories.Groups;
using Govor.Core.Repositories.Messages;
using Govor.Core.Repositories.PrivateChats;
using Govor.Core.Repositories.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Domain.Repositories.Groups;
using Govor.Domain.Repositories.Messages;
using Govor.Domain.Repositories.PrivateChats;
using Govor.Domain.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,9 +1,10 @@
using Govor.Application.Interfaces;
using Govor.Application.Messages;
using Govor.Application.Services.Messages;
using Govor.Core.Models;
using Govor.Core.Models.Messages;
using Govor.Core.Repositories.Groups;
using Govor.Core.Repositories.PrivateChats;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Domain.Repositories.Groups;
using Govor.Domain.Repositories.PrivateChats;
using Govor.Data;
using Microsoft.EntityFrameworkCore;
using Moq;
@@ -1,6 +1,6 @@
using AutoFixture;
using Govor.Application.Services.Authentication;
using Govor.Core.Infrastructure.Extensions;
using Govor.Domain.Infrastructure.Extensions;
namespace Govor.Application.Tests.Services;
@@ -1,5 +1,5 @@
using Govor.Application.Services;
using Govor.Core.Models.Users;
using Govor.Application.PingHandler;
using Govor.Domain.Models.Users;
using Govor.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
@@ -1,6 +1,5 @@
using Govor.Application.Services;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Users;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,7 +1,8 @@
using Govor.Application.Interfaces.PushNotifications;
using Govor.Application.Interfaces.PushNotifications.Models;
using Govor.Application.PushNotifications;
using Govor.Application.Services.PushNotifications;
using Govor.Core.Repositories.PushTokens;
using Govor.Domain.Repositories.PushTokens;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,4 +1,4 @@
using Govor.Application.Services;
using Govor.Application.Synching;
namespace Govor.Application.Tests.Services;
@@ -1,8 +1,8 @@
using AutoFixture;
using Govor.Application.Groups;
using Govor.Application.Interfaces;
using Govor.Application.Services;
using Govor.Core.Models;
using Govor.Core.Repositories.Groups;
using Govor.Domain.Models;
using Govor.Domain.Repositories.Groups;
using Govor.Data.Repositories.Exceptions;
using Moq;
@@ -2,8 +2,8 @@ using AutoFixture;
using Govor.Application.Interfaces.Friends;
using Govor.Application.Interfaces.UserOnlineStatus;
using Govor.Application.Services.UserOnlineStatus;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,8 +1,8 @@
using AutoFixture;
using Govor.Application.Interfaces;
using Govor.Application.Services;
using Govor.Core.Models;
using Govor.Core.Repositories.PrivateChats;
using Govor.Application.PrivateUserChats;
using Govor.Domain.Models;
using Govor.Domain.Repositories.PrivateChats;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,6 +1,6 @@
using Govor.Application.Services.UserSessions;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.UserSessionsRepository;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.UserSessionsRepository;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
@@ -1,9 +1,9 @@
using AutoFixture;
using Govor.Application.Interfaces.UserSession;
using Govor.Application.Services.UserSessions;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.UserSessionsRepository;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.UserSessionsRepository;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,10 +1,10 @@
using Govor.Application.Interfaces.Authentication;
using Govor.Application.Services.Authentication;
using Govor.Application.Services.UserSessions;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.Users;
using Govor.Core.Repositories.UserSessionsRepository;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.Users;
using Govor.Domain.Repositories.UserSessionsRepository;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -1,8 +1,8 @@
using Govor.Application.Services.UserSessions;
using Govor.Core.Models;
using Govor.Core.Models.Users;
using Govor.Core.Repositories.PushTokens;
using Govor.Core.Repositories.UserSessionsRepository;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Govor.Domain.Repositories.PushTokens;
using Govor.Domain.Repositories.UserSessionsRepository;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
@@ -1,8 +1,7 @@
using AutoFixture;
using Govor.Application.Exceptions.VerifyFriendship;
using Govor.Application.Services;
using Govor.Core.Models;
using Govor.Core.Repositories.Friendships;
using Govor.Domain.Models;
using Govor.Domain.Repositories.Friendships;
using Govor.Data.Repositories.Exceptions;
using Microsoft.Extensions.Logging;
using Moq;
@@ -0,0 +1,101 @@
using Govor.Application.Authentication.Exceptions;
using Govor.Application.Infrastructure.Validators;
using Govor.Application.Users;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Authentication;
public class AuthService : IAccountService
{
private readonly GovorDbContext _context;
private readonly IPasswordHasher _passwordHasher;
private readonly IUserNameExistValidator _userNameExistValidator;
private readonly IUsernameValidator _usernameValidator;
public AuthService(
GovorDbContext context,
IUserNameExistValidator existValidator,
IPasswordHasher passwordHasher,
IUsernameValidator usernameValidator)
{
_context = context;
_userNameExistValidator = existValidator;
_passwordHasher = passwordHasher;
_usernameValidator = usernameValidator;
}
public async Task<Result<User>> RegistrationAsync(string name, string password, Invitation invitation)
{
var validationResult = _usernameValidator.Validate(name);
if (validationResult.IsFailure)
{
return Result<User>.Failure(validationResult.Error);
}
if (await _userNameExistValidator.IsUsernameExistsAsync(name))
{
return Result<User>.Failure(new Error(
nameof(UserAlreadyExistException),
$"User with username '{name}' already exists."));
}
var passwordHash = _passwordHasher.Hash(password);
var user = new User
{
Id = Guid.NewGuid(),
Username = name,
PasswordHash = passwordHash,
Description = string.Empty,
CreatedOn = DateOnly.FromDateTime(DateTime.UtcNow),
IconId = Guid.Empty,
WasOnline = DateTime.UtcNow,
InviteId = invitation.Id
};
await _context.Users.AddAsync(user);
await SetRoleAsync(user, invitation);
await _context.SaveChangesAsync();
return user; // Success
}
public async Task<Result<User>> LoginAsync(string name, string password)
{
var user = await _context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Username == name);
if (user is null)
{
return Result<User>.Failure(new Error(
nameof(UserNotRegisteredException),
$"User '{name}' is not registered."));
}
if (!_passwordHasher.Verify(password, user.PasswordHash))
{
return Result<User>.Failure(new Error(
nameof(InvalidOperationException),
"The password provided is incorrect."));
}
return user; // Success
}
private async Task SetRoleAsync(User user, Invitation invitation)
{
if (invitation.IsAdmin)
{
await _context.Admins.AddAsync(new Admin { UserId = user.Id });
}
}
}
@@ -1,6 +1,6 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.AuthService;
namespace Govor.Application.Authentication.Exceptions;
public class InvalidUsernameException(string message) : GovorCoreException(message)
{
@@ -0,0 +1,5 @@
using Govor.Domain;
namespace Govor.Application.Authentication.Exceptions;
public class LoginUserException : GovorCoreException { }
@@ -0,0 +1,5 @@
using Govor.Domain;
namespace Govor.Application.Authentication.Exceptions;
public class UserAlreadyExistException(string username) : GovorCoreException($"{username} is already exists!") { }
@@ -0,0 +1,5 @@
using Govor.Domain;
namespace Govor.Application.Authentication.Exceptions;
public class UserNotRegisteredException(string username) : GovorCoreException($"{username} is not registered!") { }
@@ -0,0 +1,11 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Authentication;
public interface IAccountService
{
public Task<Result<User>> RegistrationAsync(string name, string password, Invitation invitation);
public Task<Result<User>> LoginAsync(string name, string password);
}
@@ -0,0 +1,12 @@
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
namespace Govor.Application.Authentication;
public interface IInvitesService
{
public Task<string> GetRoleNameAsync(User user);
public Task<string> GetRoleNameAsync(Guid sessionId);
public Task<Result<Invitation>> ValidateAsync(string inviteCode);
}
@@ -1,4 +1,4 @@
namespace Govor.Core.Infrastructure.Extensions;
namespace Govor.Application.Authentication;
public interface IPasswordHasher
{
@@ -0,0 +1,56 @@
using Govor.Application.Exceptions.InvitesService;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Authentication;
public class InvitesService : IInvitesService
{
private readonly GovorDbContext _context;
public InvitesService(GovorDbContext context)
{
_context = context;
}
public async Task<string> GetRoleNameAsync(User user)
{
return await GetRoleNameAsync(user.InviteId);
}
public async Task<string> GetRoleNameAsync(Guid sessionId)
{
var invitation = await _context.Invitations.FirstOrDefaultAsync(s => s.Id == sessionId);
if (invitation == null)
return "User";
return invitation.IsAdmin ? "Admin" : "User";
}
public async Task<Result<Invitation>> ValidateAsync(string inviteCode)
{
var invite = await _context.Invitations
.Include(s => s.Users)
.FirstOrDefaultAsync(s => s.Code == inviteCode);
if (invite == null)
return Result<Invitation>.Failure(Error.Null);
if (invite.EndDate < DateTime.Now || invite.MaxParticipants <= invite.Users.Count)
{
invite.IsActive = false;
await _context.SaveChangesAsync();
return Result<Invitation>.Failure(new Error(
"Auth.InviteLinkInvalid", $"Invite link invalid: {inviteCode}")
);
}
return invite;
}
}
@@ -1,7 +1,7 @@
using System.Security.Claims;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
namespace Govor.Application.Interfaces.Authentication;
namespace Govor.Application.Authentication.JWT;
public interface IJwtService
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Interfaces.Authentication;
namespace Govor.Application.Authentication.JWT;
public interface IJwtTokenHasher
{
@@ -1,4 +1,4 @@
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtAccessOption
{
public string SecretKey {get; set;}
@@ -1,4 +1,4 @@
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtRefreshOption
{
@@ -1,12 +1,11 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Govor.Application.Interfaces.Authentication;
using Govor.Core.Models.Users;
using Govor.Domain.Models.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtService : IJwtService
{
@@ -27,7 +26,7 @@ public class JwtService : IJwtService
{
new Claim("userId", user.Id.ToString()),
new Claim("sid", sessionId.ToString()),
new Claim(ClaimTypes.Role, await _invitesService.GetRoleAsync(user), ClaimValueTypes.String)
new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String)
};
var singing = new SigningCredentials(
@@ -1,9 +1,8 @@
using System.Security.Cryptography;
using System.Text;
using Govor.Application.Interfaces.Authentication;
using Microsoft.Extensions.Configuration;
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication.JWT;
public class JwtTokenHasher : IJwtTokenHasher
{
@@ -1,6 +1,6 @@
using Govor.Core.Infrastructure.Extensions;
using Govor.Domain.Common.Extensions;
namespace Govor.Application.Services.Authentication;
namespace Govor.Application.Authentication;
public class PasswordHasher : IPasswordHasher
{
@@ -1,5 +0,0 @@
using Govor.Core;
namespace Govor.Application.Exceptions.AuthService;
public class LoginUserException : GovorCoreException { }
@@ -1,5 +0,0 @@
using Govor.Core;
namespace Govor.Application.Exceptions.AuthService;
public class UserAlreadyExistException(string username) : GovorCoreException($"{username} is already exists!") { }
@@ -1,5 +0,0 @@
using Govor.Core;
namespace Govor.Application.Exceptions.AuthService;
public class UserNotRegisteredException(string username) : GovorCoreException($"{username} is not registered!") { }
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.FriendsService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.FriendsService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.FriendsService;
@@ -1,4 +1,4 @@
using Govor.Core;
using Govor.Domain;
namespace Govor.Application.Exceptions.InvitesService;

Some files were not shown because too many files have changed in this diff Show More