Українська
Сервіс профілів
Крок 1. Сервіс
Навіщо. Сервіс профілів збирає операції над користувачами, що не належать до автентифікації: показати мій профіль, показати чужий, змінити ім’я й опис, змінити пароль, встановити чи прибрати аватар, шукати людей і записати «востаннє онлайн». Кожен метод короткий; разом вони показують форму, яку має кожен сервіс Chatex: перевірити, завантажити, звірити, змінити, зберегти, відобразити в DTO.
Що зробити.
cs
using Chatex.Core.Common;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using FluentValidation;
using Microsoft.AspNetCore.Identity;
namespace Chatex.Core.Users;
public interface IProfileService
{
Task<Result<MyProfileDto>> GetMyProfileAsync(Guid userId, CancellationToken cancellationToken = default);
Task<Result<UserDto>> GetUserAsync(Guid userId, CancellationToken cancellationToken = default);
Task<Result<MyProfileDto>> UpdateProfileAsync(Guid userId, UpdateProfileCommand command, CancellationToken cancellationToken = default);
/// <summary>Changes the password and signs the user out of every session.</summary>
Task<Result> ChangePasswordAsync(Guid userId, ChangePasswordCommand command, CancellationToken cancellationToken = default);
Task<Result<MyProfileDto>> SetAvatarAsync(Guid userId, FileUpload upload, CancellationToken cancellationToken = default);
Task<Result<MyProfileDto>> RemoveAvatarAsync(Guid userId, CancellationToken cancellationToken = default);
/// <summary>Opens the avatar image of any user.</summary>
Task<Result<Stream>> OpenAvatarAsync(Guid userId, CancellationToken cancellationToken = default);
Task<Result<UserSummaryDto[]>> SearchUsersAsync(string query, int? limit, CancellationToken cancellationToken = default);
/// <summary>
/// Records that the user is online now and returns the stored time. The SignalR hub calls it on the first
/// connection and when the user goes offline.
/// </summary>
Task<DateTimeOffset> TouchLastSeenAsync(Guid userId, CancellationToken cancellationToken = default);
}
internal sealed class ProfileService(
UserManager<User> userManager,
IUserRepository users,
IRefreshTokenRepository refreshTokens,
IUnitOfWork unitOfWork,
IFileStorage storage,
AvatarStore avatars,
TimeProvider timeProvider,
IValidator<UpdateProfileCommand> updateValidator,
IValidator<ChangePasswordCommand> passwordValidator) : IProfileService
{
private const int MinQueryLength = 2;
public async Task<Result<MyProfileDto>> GetMyProfileAsync(Guid userId, CancellationToken cancellationToken = default) =>
await users.GetWithProfileAsync(userId, cancellationToken) is { } user ? user.ToMyProfileDto() : UserErrors.NotFound;
public async Task<Result<UserDto>> GetUserAsync(Guid userId, CancellationToken cancellationToken = default) =>
await users.GetWithProfileAsync(userId, cancellationToken) is { } user ? user.ToDto() : UserErrors.NotFound;
public async Task<Result<MyProfileDto>> UpdateProfileAsync(
Guid userId, UpdateProfileCommand command, CancellationToken cancellationToken = default)
{
if (await updateValidator.ValidateToErrorAsync(command, cancellationToken) is { } invalid)
{
return invalid;
}
var user = await users.GetWithProfileAsync(userId, cancellationToken);
if (user?.Profile is null)
{
return UserErrors.NotFound;
}
user.Profile.DisplayName = command.DisplayName.Trim();
user.Profile.Bio = string.IsNullOrWhiteSpace(command.Bio) ? null : command.Bio.Trim();
await unitOfWork.SaveChangesAsync(cancellationToken);
return user.ToMyProfileDto();
}
public async Task<Result> ChangePasswordAsync(
Guid userId, ChangePasswordCommand command, CancellationToken cancellationToken = default)
{
if (await passwordValidator.ValidateToErrorAsync(command, cancellationToken) is { } invalid)
{
return invalid;
}
var user = await users.GetByIdAsync(userId, cancellationToken);
if (user is null)
{
return UserErrors.NotFound;
}
var changed = await userManager.ChangePasswordAsync(user, command.CurrentPassword, command.NewPassword);
if (!changed.Succeeded)
{
return changed.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.PasswordMismatch))
? Error.Validation("currentPassword", "wrong_password", "The current password is wrong.")
: IdentityErrors.ToValidationError(changed.Errors);
}
await refreshTokens.RevokeAllForUserAsync(userId, timeProvider.GetUtcNow(), cancellationToken);
return Result.Success;
}
public async Task<Result<MyProfileDto>> SetAvatarAsync(
Guid userId, FileUpload upload, CancellationToken cancellationToken = default)
{
var user = await users.GetWithProfileAsync(userId, cancellationToken);
if (user?.Profile is null)
{
return UserErrors.NotFound;
}
var saved = await avatars.SaveAsync(upload, cancellationToken);
if (!saved.IsSuccess)
{
return saved.Error;
}
var previous = user.Profile.AvatarPath;
user.Profile.AvatarPath = saved.Value;
await unitOfWork.SaveChangesAsync(cancellationToken);
await avatars.DeleteAsync(previous, cancellationToken);
return user.ToMyProfileDto();
}
public async Task<Result<MyProfileDto>> RemoveAvatarAsync(Guid userId, CancellationToken cancellationToken = default)
{
var user = await users.GetWithProfileAsync(userId, cancellationToken);
if (user?.Profile is null)
{
return UserErrors.NotFound;
}
var previous = user.Profile.AvatarPath;
user.Profile.AvatarPath = null;
await unitOfWork.SaveChangesAsync(cancellationToken);
await avatars.DeleteAsync(previous, cancellationToken);
return user.ToMyProfileDto();
}
public async Task<Result<Stream>> OpenAvatarAsync(Guid userId, CancellationToken cancellationToken = default)
{
var user = await users.GetWithProfileAsync(userId, cancellationToken);
if (user?.Profile?.AvatarPath is not { } path)
{
return CommonErrors.AvatarNotFound;
}
return await storage.OpenReadAsync(path, cancellationToken);
}
public async Task<Result<UserSummaryDto[]>> SearchUsersAsync(
string query, int? limit, CancellationToken cancellationToken = default)
{
query = query?.Trim() ?? "";
if (query.Length < MinQueryLength)
{
return CommonErrors.QueryTooShort;
}
var found = await users.SearchAsync(query, Paging.Clamp(limit), cancellationToken);
return found.Select(u => u.ToSummaryDto()).ToArray();
}
public async Task<DateTimeOffset> TouchLastSeenAsync(Guid userId, CancellationToken cancellationToken = default)
{
var now = timeProvider.GetUtcNow();
await users.UpdateLastSeenAsync(userId, now, cancellationToken);
return now;
}
}Читання профілів
GetMyProfileAsync і GetUserAsync – по одному виразу: await ... is { } user ? user.ToDto() : UserErrors.NotFound. Умовний оператор має дві гілки різних типів, DTO та Error; компілятор перетворює обидві на Result<…> методу через неявні оператори з теми 7.
Оновлення профілю
Команду перевіряють, користувача завантажують разом із профілем (з відстеженням, щоб зміну було збережено), значення обрізають від пробілів, а порожній опис стає null, а не порожнім рядком. user?.Profile is null охоплює і «такого користувача немає», і «профілю немає» однією перевіркою.
Зміна пароля
ChangePasswordAsyncз Identity перевіряє поточний пароль і правила для нового та зберігає новий хеш і новий штамп безпеки.- Хибний поточний пароль повертається як
PasswordMismatchвід Identity; сервіс перетворює його на помилку перевірки поляcurrentPassword, щоб форма налаштувань могла показати її під потрібним полем. Інші збої (слабкий новий пароль) стають помилками за полями черезIdentityErrors. - Після цього відкликаються всі токени оновлення. Хто б не змінив пароль – власник чи той, хто знав старий, – кожна інша сесія має завершитися. Чинний токен доступу користувача лишається дійсним щонайбільше 15 хвилин, після чого клієнт має увійти знову.
Аватари
SetAvatarAsync дотримується порядку з розділу Безпечні завантаження: зберегти новий файл, спрямувати на нього профіль, зберегти базу даних і лише тоді видалити попередній файл. Якби збереження бази даних не вдалося, старий аватар лишився б неушкодженим. RemoveAvatarAsync робить те саме без нового файлу. OpenAvatarAsync повертає потік файлу або avatar_not_found; шаблон user?.Profile?.AvatarPath is not { } path і перевіряє на null, і дає назву значенню.
Пошук і «востаннє онлайн»
SearchUsersAsyncвимагає щонайменше двох символів – пошук за однією літерою відповідав би майже всім – і обмежує ліміт черезPaging.Clamp. Репозиторій шукає за іменами користувачів і відображуваними іменами з екранованими шаблонамиILIKE(тема 5).TouchLastSeenAsyncзаписує поточний час однимUPDATEі повертає його. Хаб SignalR викликає його, коли користувач підключається й відключається (тема 14), і надсилає час контактам користувача.
Крок 2. Реєстрація сервісу
Що зробити. Розширте AddCore (нові рядки зеленим):
cs
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Chatex.Core.Users;
using Chatex.Data;
using FluentValidation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Chatex.Core;
public static class DependencyInjection
{
public static IServiceCollection AddCore(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("Chatex")
?? throw new InvalidOperationException("Connection string 'Chatex' is not configured.");
services.AddData(connectionString, o => o.RootPath = configuration["Storage:RootPath"] ?? "");
services.AddOptions<JwtOptions>()
.Bind(configuration.GetSection(JwtOptions.Section))
.ValidateDataAnnotations()
.ValidateOnStart();
services.Configure<IdentityOptions>(o =>
{
o.User.RequireUniqueEmail = true;
o.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz0123456789_";
o.Password.RequiredLength = 8;
o.Password.RequireDigit = true;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Lockout.MaxFailedAccessAttempts = 5;
o.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
});
services.AddValidatorsFromAssemblyContaining<AuthService>(includeInternalTypes: true);
services.AddSingleton<ITokenService, TokenService>();
services.AddScoped<AvatarStore>();
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IProfileService, ProfileService>();
return services;
}
}AvatarStore реєструється сам за себе, без інтерфейсу: це внутрішній допоміжний клас, а не контракт, який бачить API, і він має область дії scoped, як і сервіси, що його використовують.
Перевірка
dotnet build проходить успішно, і 12 бізнес-тестів із теми 8 і далі проходять:
powershell
dotnet test --project Tests/Chatex.Core.Tests