English
The profile service
Step 1. The service
Why. The profile service collects the operations on users that are not authentication: show my profile, show somebody else's, change name and bio, change the password, set or remove the avatar, search for people, and record "last seen". Each method is short; together they show the shape every service of Chatex has — validate, load, check, change, save, map to a DTO.
Do.
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;
}
}Reading profiles
GetMyProfileAsync and GetUserAsync are one expression each: await ... is { } user ? user.ToDto() : UserErrors.NotFound. The conditional operator has two branches of different types, a DTO and an Error; the compiler converts both to the method's Result<…> through the implicit operators of topic 7.
Updating the profile
The command is validated, the user is loaded with the profile (tracked, so the change is saved), the values are trimmed, and an empty bio becomes null rather than an empty string. user?.Profile is null covers both "no such user" and "no profile" in one check.
Changing the password
- Identity's
ChangePasswordAsyncchecks the current password and the rules for the new one and saves the new hash and a new security stamp. - A wrong current password comes back as Identity's
PasswordMismatch; the service turns it into a validation error on the fieldcurrentPassword, so the settings form can show it under the right input. Other failures (a weak new password) become per-field errors throughIdentityErrors. - All refresh tokens are revoked afterwards. Whoever changed the password — the owner, or someone who knew the old one — every other session must end. The user's current access token stays valid for at most 15 minutes, after which the client must sign in again.
Avatars
SetAvatarAsync follows the order from Safe uploads: save the new file, point the profile at it, save the database, and only then delete the previous file. If the database save failed, the old avatar would still be intact. RemoveAvatarAsync does the same without a new file. OpenAvatarAsync returns the stream of the file, or avatar_not_found; the pattern user?.Profile?.AvatarPath is not { } path both checks for null and names the value.
Search and last seen
SearchUsersAsyncrequires at least two characters — a one-letter search would match almost everyone — and clamps the limit withPaging.Clamp. The repository searches user names and display names with escapedILIKEpatterns (topic 5).TouchLastSeenAsyncwrites the current time with oneUPDATEand returns it. The SignalR hub calls it when a user connects and disconnects (topic 14), and sends the time to the user's contacts.
Step 2. Register the service
Do. Extend AddCore (new lines in green):
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 is registered as itself, without an interface: it is an internal helper, not a contract the API sees, and scoped like the services that use it.
Check
dotnet build succeeds, and the 12 business tests of topic 8 still pass:
powershell
dotnet test --project Tests/Chatex.Core.Tests