English
Users, profiles and tokens
Step 1. Use ASP.NET Core Identity for accounts
Why. Storing passwords safely is hard: they must be hashed with a slow, salted algorithm, compared in constant time, re-hashed when the algorithm improves; failed sign-ins must lock the account; user names and emails must be normalised for case-insensitive search. ASP.NET Core Identity is Microsoft's library that does all of this. Its base class IdentityUser<TKey> already has the properties of an account: UserName, Email, PasswordHash, LockoutEnd, AccessFailedCount, SecurityStamp and more. We derive our user from it and add only what is specific to Chatex.
Do. Add the Identity package with its EF Core store to the data project:
powershell
dotnet add Source/Chatex.Data package Microsoft.AspNetCore.Identity.EntityFrameworkCoreThanks to Central Package Management, the version comes from Directory.Packages.props, and the project file gets a reference without a version:
xml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
</ItemGroup>
</Project>Step 2. The user
Why. The User class is the account. Three decisions shape it:
- The key type is
Guid, not thestringof the non-genericIdentityUser, so users get UUIDv7 ids like every other entity. - The constructor sets
IdandSecurityStamp. The non-genericIdentityUserdoes the same in its constructor, butIdentityUser<Guid>leaves both empty. The security stamp is a random value that Identity changes whenever the credentials change; Identity expects every user to have one. Setting both in the constructor means that everyUseris valid from the moment it is created, also in tests that create users without the Identity services. UserNameis the public@handle— unique, lower case, shown in search and in direct chats. Everything a user shows to others besides the handle lives in the profile.
Do.
cs
using Microsoft.AspNetCore.Identity;
namespace Chatex.Data.Entities;
/// <summary>
/// Account and credentials (ASP.NET Core Identity). <see cref="IdentityUser{TKey}.UserName"/> is the public @handle.
/// Everything a user shows to others lives in <see cref="Profile"/>.
/// </summary>
public class User : IdentityUser<Guid>, IHasCreatedAt
{
public User()
{
Id = Guid.CreateVersion7();
SecurityStamp = Guid.NewGuid().ToString();
}
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? LastSeenAt { get; set; }
public UserProfile? Profile { get; set; }
public ICollection<ChatMember> Memberships { get; set; } = [];
public ICollection<RefreshToken> RefreshTokens { get; set; } = [];
}LastSeenAt is nullable (DateTimeOffset?): a user who has never connected has not been seen. Collections are initialised with the collection expression [], so they are never null.
DateTimeOffset, not DateTime
A DateTime does not say which time zone it is in, so "12:00" from a server in UTC and "12:00" from a laptop in Kyiv look the same. A DateTimeOffset carries its offset from UTC, and PostgreSQL stores it as timestamp with time zone. Chatex uses DateTimeOffset for every point in time, always in UTC.
Step 3. The profile
Why. Why not put the display name, the bio and the avatar straight into User? Because they are a different kind of data:
- the account holds credentials (password hash, lockout, security stamp) that must never leave the server; the profile holds public data that is sent to other users all the time. Keeping them in separate tables means a query for profiles cannot accidentally load a password hash;
- the account is managed by Identity, the profile by our own code (topic 9).
The relationship is one-to-one: the profile's primary key UserId is at the same time the foreign key to the user. The profile has no Id of its own.
Do.
cs
namespace Chatex.Data.Entities;
/// <summary>Public profile, one per <see cref="User"/>; created together with the user at registration.</summary>
public class UserProfile : IHasUpdatedAt
{
public Guid UserId { get; set; }
public required string DisplayName { get; set; }
public string? Bio { get; set; }
public string? AvatarPath { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
public User User { get; set; } = null!;
}DisplayName is a required member (C# 11): the compiler refuses new UserProfile() unless the object initializer sets DisplayName, so a profile without a name cannot be created by mistake. Bio and AvatarPath are optional, hence nullable.
User = null! deserves a word. A navigation property is not loaded unless we ask for it, so it is not really "never null". But declaring it User? would force a null check every time we use it after loading it. The null-forgiving operator ! tells the compiler "trust me, this will be set when it is used". It is the conventional way to declare required navigation properties in EF Core with nullable reference types.
Step 4. The refresh token
Why. The browser keeps a user signed in with two tokens (topic 8). The access token lives 15 minutes and is not stored on the server at all. The refresh token lives 30 days and is exchanged for new access tokens; the server must be able to revoke it, so it is stored in the database. Three decisions:
- Only a hash of the token is stored, never the token itself. If the database leaks, the attacker gets hashes that cannot be used to sign in — the same idea as storing password hashes.
- Rotation: each use of a refresh token revokes it (
RevokedAt) and issues a new one;ReplacedByTokenIdlinks the old token to its successor. If a revoked token is presented again, someone has stolen it, and the service ends all sessions of the user. UserAgentandCreatedByIprecord where the session was created, for a future "active sessions" page.
Do.
cs
namespace Chatex.Data.Entities;
/// <summary>
/// A long-lived token that is exchanged for a new JWT access token. Only a hash of the token is stored.
/// Rotation: on use the token is revoked and <see cref="ReplacedByTokenId"/> points to its successor.
/// </summary>
public class RefreshToken : IHasCreatedAt
{
public Guid Id { get; set; } = Guid.CreateVersion7();
public Guid UserId { get; set; }
public required string TokenHash { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset ExpiresAt { get; set; }
public DateTimeOffset? RevokedAt { get; set; }
public Guid? ReplacedByTokenId { get; set; }
public string? UserAgent { get; set; }
public string? CreatedByIp { get; set; }
public User User { get; set; } = null!;
public bool IsActiveAt(DateTimeOffset now) => RevokedAt is null && ExpiresAt > now;
}IsActiveAt is a rule that depends only on the token's own data, so it lives in the entity. Note that it takes the current time as a parameter instead of reading DateTimeOffset.UtcNow inside. The caller passes the time from an injected clock (TimeProvider, topic 7), so a test can ask "is the token active 31 days later?" without waiting a month. A method that reads the clock by itself could not be tested that way.
=> and is null
IsActiveAt is an expression-bodied member: => expression is a short form of { return expression; }. RevokedAt is null is a pattern test; unlike == null it cannot be redefined by an operator overload, so it always means "the reference is null".