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
@@ -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 });
}
}
}
@@ -0,0 +1,8 @@
using Govor.Domain;
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);
}
@@ -0,0 +1,7 @@
namespace Govor.Application.Authentication;
public interface IPasswordHasher
{
string Hash(string password);
bool Verify(string hashedPassword, string providedPassword);
}
@@ -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;
}
}
@@ -0,0 +1,11 @@
using System.Security.Claims;
using Govor.Domain.Models.Users;
namespace Govor.Application.Authentication.JWT;
public interface IJwtService
{
Task<string> GenerateAccessTokenAsync(User user, Guid sessionId);
Task<string> GenerateRefreshTokenAsync(User user);
ClaimsPrincipal GetPrincipalFromExpiredToken(string token);
}
@@ -0,0 +1,7 @@
namespace Govor.Application.Authentication.JWT;
public interface IJwtTokenHasher
{
string HashToken(string token);
bool VerifyToken(string token, string storedHash);
}
@@ -0,0 +1,6 @@
namespace Govor.Application.Authentication.JWT;
public class JwtAccessOption
{
public string SecretKey {get; set;}
public int Minutes { get; set; }
}
@@ -0,0 +1,6 @@
namespace Govor.Application.Authentication.JWT;
public class JwtRefreshOption
{
public int RefreshTokenLifetimeDays { get; set; }
}
@@ -0,0 +1,84 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Govor.Domain.Models.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Govor.Application.Authentication.JWT;
public class JwtService : IJwtService
{
private JwtAccessOption _jwtAccessOption;
private JwtRefreshOption _refreshOptions;
private IInvitesService _invitesService;
public JwtService(IOptions<JwtAccessOption> options, IOptions<JwtRefreshOption> refreshOptions, IInvitesService invitesService)
{
_refreshOptions = refreshOptions.Value;
_jwtAccessOption = options.Value;
_invitesService = invitesService;
}
public async Task<string> GenerateAccessTokenAsync(User user, Guid sessionId)
{
var claims = new[]
{
new Claim("userId", user.Id.ToString()),
new Claim("sid", sessionId.ToString()),
new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String)
};
var singing = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKey)),
SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
expires: DateTime.UtcNow.AddMinutes(_jwtAccessOption.Minutes),
signingCredentials: singing,
claims: claims);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public async Task<string> GenerateRefreshTokenAsync(User user)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim("userId", user.Id.ToString()),
new Claim("tokenType", "refresh")
};
var token = new JwtSecurityToken(
expires: DateTime.UtcNow.AddDays(_refreshOptions.RefreshTokenLifetimeDays),
signingCredentials: creds,
claims: claims
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKey)),
ValidateLifetime = false // << important
};
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(token, tokenValidationParameters, out var securityToken);
if (securityToken is not JwtSecurityToken jwtToken || jwtToken.Header.Alg != SecurityAlgorithms.HmacSha256)
throw new SecurityTokenException("Invalid token");
return principal;
}
}
@@ -0,0 +1,40 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Configuration;
namespace Govor.Application.Authentication.JWT;
public class JwtTokenHasher : IJwtTokenHasher
{
private readonly byte[] _pepperBytes;
public JwtTokenHasher(IConfiguration config)
{
var pepper = config["EncryptionOption:Secret"]
?? throw new InvalidOperationException("Pepper is missing");
_pepperBytes = Encoding.UTF8.GetBytes(pepper);
}
public string HashToken(string token)
{
using var hmac = new HMACSHA256(_pepperBytes);
var tokenBytes = Encoding.UTF8.GetBytes(token);
var hash = hmac.ComputeHash(tokenBytes);
return Convert.ToBase64String(hash);
}
public bool VerifyToken(string token, string storedHash)
{
using var hmac = new HMACSHA256(_pepperBytes);
var tokenBytes = Encoding.UTF8.GetBytes(token);
var computedHash = hmac.ComputeHash(tokenBytes);
var storedHashBytes = Convert.FromBase64String(storedHash);
return CryptographicOperations.FixedTimeEquals(computedHash, storedHashBytes);
}
}
@@ -0,0 +1,16 @@
using Govor.Domain.Common.Extensions;
namespace Govor.Application.Authentication;
public class PasswordHasher : IPasswordHasher
{
public string Hash(string password)
{
return BCrypt.Net.BCrypt.HashPassword(password);
}
public bool Verify(string hashedPassword, string providedPassword)
{
return BCrypt.Net.BCrypt.Verify(hashedPassword, providedPassword);
}
}