English
Commands, results and rules
Step 1. Commands and the result of signing in
Why. A service method receives a command — a record with what the client sent — and returns DTOs. For authentication the commands are small; the result of a successful sign-in carries both tokens with their expiry times and the user's own profile, so the client can show the user's name right away without another request.
Do.
cs
using Chatex.Core.Users;
namespace Chatex.Core.Auth;
public sealed record RegisterCommand(string UserName, string Email, string Password, string DisplayName);
/// <param name="Login">User name or email.</param>
public sealed record LoginCommand(string Login, string Password);
public sealed record RefreshCommand(string RefreshToken);
/// <summary>Where a request came from; stored with refresh tokens so users can review their sessions.</summary>
public sealed record ClientInfo(string? UserAgent, string? IpAddress)
{
public static ClientInfo Unknown { get; } = new(null, null);
}
/// <summary>Tokens for a signed-in user. The client sends the access token on each request and the refresh token to renew it.</summary>
public sealed record AuthResult(
string AccessToken,
DateTimeOffset AccessTokenExpiresAt,
string RefreshToken,
DateTimeOffset RefreshTokenExpiresAt,
MyProfileDto User);LoginCommand.Loginaccepts a user name or an email; the service decides by the@.ClientInfodescribes where a request came from (browser and IP). It is stored with each refresh token, so a future "active sessions" page can list them.ClientInfo.Unknownserves tests and internal calls.AuthResultis what the API turns into its response: the access token goes into the JSON body, the refresh token into a cookie (topic 13).
Step 2. User DTOs
Why. AuthResult contains a MyProfileDto, the first of the user DTOs. All of them live in one file: the user's own profile (with the email), another user's public profile (with "last seen"), and a summary that is shown next to every message and in every member list. Topic 9 uses the rest of the file; create it complete now.
Do. Create the folder Users:
cs
using Chatex.Data.Entities;
using Chatex.Data.Models;
namespace Chatex.Core.Users;
/// <summary>The signed-in user's own profile.</summary>
public sealed record MyProfileDto(
Guid Id,
string UserName,
string Email,
string DisplayName,
string? Bio,
bool HasAvatar,
DateTimeOffset CreatedAt);
/// <summary>Another user's public profile.</summary>
public sealed record UserDto(
Guid Id,
string UserName,
string DisplayName,
string? Bio,
bool HasAvatar,
DateTimeOffset? LastSeenAt);
/// <summary>Just enough to show a user next to a message or in a list.</summary>
public sealed record UserSummaryDto(Guid Id, string UserName, string DisplayName, bool HasAvatar);
public sealed record UpdateProfileCommand(string DisplayName, string? Bio);
public sealed record ChangePasswordCommand(string CurrentPassword, string NewPassword);
internal static class UserMappings
{
public static MyProfileDto ToMyProfileDto(this User user) => new(
user.Id,
user.UserName!,
user.Email!,
user.Profile?.DisplayName ?? user.UserName!,
user.Profile?.Bio,
user.Profile?.AvatarPath is not null,
user.CreatedAt);
public static UserDto ToDto(this User user) => new(
user.Id,
user.UserName!,
user.Profile?.DisplayName ?? user.UserName!,
user.Profile?.Bio,
user.Profile?.AvatarPath is not null,
user.LastSeenAt);
public static UserSummaryDto ToSummaryDto(this User user) => new(
user.Id,
user.UserName!,
user.Profile?.DisplayName ?? user.UserName!,
user.Profile?.AvatarPath is not null);
public static UserSummaryDto ToDto(this UserSummary user) =>
new(user.Id, user.UserName, user.DisplayName, user.AvatarPath is not null);
}HasAvataris abool, not a path: the storage path is an internal detail. The client downloads an avatar from/api/users/{id}/avatar(topic 13).- The mappings are extension methods in an
internal static class:user.ToMyProfileDto()reads well, and nothing outside Chatex.Core can call them. user.Profile?.DisplayName ?? user.UserName!— a user always has a profile, but if a profile was not loaded, the user name is a sensible fallback instead of an exception.ToDto(this UserSummary user)maps theUserSummarythat the chat list query of topic 5 returns.
Step 3. Errors that reveal nothing
Why. Authentication errors are a security topic. If sign-in said "no such user" for an unknown name and "wrong password" for a known one, an attacker could test which user names or emails exist. Chatex returns the same invalid_credentials in both cases. The registration errors, on the other hand, must be specific — the user needs to know that the name is taken.
Do.
cs
using Chatex.Core.Common;
namespace Chatex.Core.Auth;
public static class AuthErrors
{
/// <summary>Deliberately vague: does not say whether the user exists.</summary>
public static Error InvalidCredentials { get; } =
Error.Unauthorized("invalid_credentials", "The user name, email or password is wrong.");
public static Error LockedOut { get; } =
Error.Unauthorized("locked_out", "Too many failed attempts. Try again later.");
public static Error InvalidRefreshToken { get; } =
Error.Unauthorized("invalid_refresh_token", "The session has expired. Sign in again.");
public static Error UserNameTaken { get; } =
Error.Conflict("user_name_taken", "This user name is already taken.");
public static Error EmailTaken { get; } =
Error.Conflict("email_taken", "An account with this email already exists.");
}ErrorKind.Unauthorized becomes HTTP 401, Conflict becomes 409 (topic 12).
Step 4. Validators
Why. The registration form has four fields with clear rules. The user name follows the handle rule from topic 7 (3–32 characters, a letter first); the display name must fit the column of topic 4 (64 characters). That limit belongs to the profile, so it lives in ProfileValidators in the folder Users; topic 9 adds the profile validators to the same file.
Do. Create the class with the limits first:
cs
namespace Chatex.Core.Users;
internal static class ProfileValidators
{
public const int MaxDisplayName = 64;
public const int MaxBio = 500;
}Then the validators of the two auth commands:
cs
using Chatex.Core.Common;
using Chatex.Core.Users;
using FluentValidation;
namespace Chatex.Core.Auth;
internal sealed class RegisterCommandValidator : AbstractValidator<RegisterCommand>
{
public RegisterCommandValidator()
{
RuleFor(c => c.UserName).NotEmpty().Handle(3, 32);
RuleFor(c => c.Email).NotEmpty().EmailAddress().MaximumLength(256);
RuleFor(c => c.Password).NotEmpty().MaximumLength(128);
RuleFor(c => c.DisplayName).NotEmpty().MaximumLength(ProfileValidators.MaxDisplayName);
}
}
internal sealed class LoginCommandValidator : AbstractValidator<LoginCommand>
{
public LoginCommandValidator()
{
RuleFor(c => c.Login).NotEmpty().MaximumLength(256);
RuleFor(c => c.Password).NotEmpty().MaximumLength(128);
}
}- Each validator is an
internal sealedclass derived fromAbstractValidator<T>; the rules are declared in the constructor. - The password rules are not here. Length and digits are checked by Identity (configured in
AddCore), so there is one source of truth. The validator only caps the length at 128 characters, so nobody can make the server hash a megabyte of "password". - No rule says "the user name is free". Only the database can answer that reliably; the service turns Identity's
DuplicateUserNameintouser_name_taken.
Check
dotnet build succeeds.