From 0691ec971348ba2505ebda2ff40a9b02ce09bd2c Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:20:48 +0100 Subject: [PATCH 1/3] M24, second part: display names and last login for accounts Accounts get an optional display name and a last login, kept in a new StaffProfiles table and shown to admins only. The activity log keeps the account's email as at the time. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- CHANGELOG.md | 2 + docs/operations.md | 4 + docs/roadmap.md | 3 +- docs/security.md | 1 + src/Commonage.Web/Audit/AuditText.cs | 3 +- src/Commonage.Web/Data/CommonageDbContext.cs | 8 + .../20261115180842_StaffProfiles.Designer.cs | 1060 +++++++++++++++++ .../20261115180842_StaffProfiles.cs | 41 + .../CommonageDbContextModelSnapshot.cs | 26 + src/Commonage.Web/Domain/AuditEntry.cs | 1 + src/Commonage.Web/Domain/StaffProfile.cs | 18 + src/Commonage.Web/Identity/StaffProfiles.cs | 45 + .../Pages/Account/Login.cshtml.cs | 7 +- .../Pages/Account/LoginTwoFactor.cshtml.cs | 2 + .../Pages/Admin/Users/Edit.cshtml | 31 + .../Pages/Admin/Users/Edit.cshtml.cs | 34 + .../Pages/Admin/Users/Index.cshtml | 13 + .../Pages/Admin/Users/Index.cshtml.cs | 9 +- .../Resources/SharedResource.de.resx | 5 + .../Resources/SharedResource.resx | 5 + tests/Commonage.Tests/AccountTests.cs | 32 + 21 files changed, 1344 insertions(+), 6 deletions(-) create mode 100644 src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.Designer.cs create mode 100644 src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.cs create mode 100644 src/Commonage.Web/Domain/StaffProfile.cs create mode 100644 src/Commonage.Web/Identity/StaffProfiles.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ca30a9..f8c31dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ version may change things that need attention when updating, and these notes say ### For people running an archive +- Accounts have a **name** (optional, set by an admin) and show when the person last logged in. Both are visible to admins + only, on the Accounts pages. The activity log still names the account by its email address as it was at the time. - A new account type, **Helper**, for volunteers: they describe items and add photos, but cannot publish, unpublish, delete, open contributions that are still to be reviewed, or see who contributed something. Admins choose the type under Accounts. The handbook has a section on a scanning evening with helpers. diff --git a/docs/operations.md b/docs/operations.md index 8f14833..871c325 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -16,6 +16,10 @@ their own email, a message, or in person), and the person chooses their own pass and for seven days. If someone forgets their password, an admin creates a new setup link; earlier links stop working then. +An account can have a display name, and Commonage remembers when it last logged in (table `StaffProfiles`). Both are shown to +admins on the Accounts pages only, and are not part of the export, which holds no accounts. The activity log names the account +by the email address it had when something was done, so it stays true after a rename or a deleted account. + Disabling an account ends its logins within a minute. Admins cannot change, disable or delete their own account, so there is always at least one admin left. Everyone changes their own password under "Change password". diff --git a/docs/roadmap.md b/docs/roadmap.md index 0df1ae8..284b763 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -503,7 +503,8 @@ shows the years of its published items. M19 is complete. **M24 Helpers and accounts** -- Part 1 is done: the `Helper` role. Display names and a last login are still to do. +- Part 1 is done: the `Helper` role. Part 2: `StaffProfiles` (display name, last login), shown to admins only; the activity log + keeps the email address as at the time, so it stays true after a rename. - A `Helper` role: describes and uploads. Publishing, the bin, contributors, notes, export and settings stay with curators, and contributors' names and email addresses are not shown. `EndpointAccessTests` checks every role against every admin address. Display names and a last login for accounts. diff --git a/docs/security.md b/docs/security.md index 5935e0b..8a6cb17 100644 --- a/docs/security.md +++ b/docs/security.md @@ -24,6 +24,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Access | Public pages and public image addresses read only from published items (`PublishedItems`). Admin pages are protected by policy per folder; admin-only pages (accounts, export, activity log) by a second policy. Originals and previews of unpublished items are served only to curators. What a curator chooses ahead of publishing, such as a draft's photo as a collection's cover, is passed over until its item is published. Tested in `PublicationTests`, `MediaTests`, `AccountTests`, `ExportTests`, `CollectionTests`. `EndpointAccessTests` lists every address that is open without a login, so a new one cannot be open by accident. | | Accounts | Passwords of at least 12 characters (length over forced symbols, NIST SP 800-63B). Five wrong passwords lock an account for five minutes, and one address can try 100 logins an hour. Accounts are created with one-time setup links, valid seven days. Disabling an account, or a password change, ends its logins within a minute. Admins cannot lock themselves out. An authenticator app (TOTP) can be added to each login, and admins can require it of everyone who manages the archive; wrong codes count towards the lockout like wrong passwords. Ten recovery codes, each usable once. Turning the app off or making new codes asks for the password again, and wrong passwords there and on "Change password" count towards the lockout too. Tested in `TwoFactorTests`. | | Forms | Every form carries an antiforgery token. Redirects after login and language change only go to addresses on this site. | +| Staff names and last login | `StaffProfiles` holds an optional display name and the time of the last login per account, written after a successful login (password, authenticator code or recovery code). Read only on the admin-only Accounts pages, never on a public page, feed or link preview, and not in the export or the activity log (which keeps the email address). Changing a name is logged. The row goes with the account (cascade). `AccountTests`. | | Helpers | The `Helper` role (policy `Describe`) reaches only the item list, the item form, "Add many photos", the preview and the generated pictures under `/admin/media` (not the original). Everything else under `/Admin` needs `ManageArchive` (curator or admin) or `Administer`. A helper only gets draft items, in the list, the form, the preview and the pictures, never published, submitted, rejected or withdrawn ones: what visitors see changes only through a curator, and no contribution or contributor name or email reaches a helper (the contribution is not even loaded). The start page counts, the "already in the archive" file check and the reference-number check show a helper drafts only. Publishing, unpublishing, accepting, rejecting, deleting, withdrawing and removing a photo are refused with 403 on the server, not only hidden. Accepted: a helper can read "received from" and the internal notes of the items they open; the handbook says so. `HelperTests` (including a test that lists every `/Admin` address a helper can reach), `AccountTests`. | | Import | Only curators (the `/Admin` policy). The sheet and ZIP are kept in `import-staging` on the media volume, which is never served by path, for a day at most. A sheet is read as strict UTF-8, at most 20 MB and 100,000 rows; a ZIP at most 4 GB and 200,000 entries; every entry is counted as it is unpacked into a temporary file, and a name inside it is never used in a path. A folder to import from is chosen from a listing of `import/`, links and hidden files are skipped. Files go through the same checks as an upload. One import at a time. Everything imported is a draft; the activity log records each item and the import, never the spreadsheet or the contributors' details. `ImportTests`. | | PDF files | Only curators can add a PDF; contribution links refuse it. A PDF is recognised by `%PDF-` and read by poppler (`pdfinfo`, `pdftoppm`), a large C++ parser, so it runs as separate processes, never inside the app: each call has a time limit (`Uploads:PdfTimeoutSeconds`, 60) and is killed with its children when it takes longer, the size of the drawn picture is set by us with `-scale-to` whatever size the page claims, at most 300 pages are drawn, and no part of the file or its name reaches a command line (arguments are passed as a list, the file is copied to a random name in an owner-only temporary folder that is removed afterwards). Pages are served only for published items; the PDF stays private. Accepted: a hostile PDF made by a curator could still exploit poppler, which runs with the app's rights in the container; build with `WITH_PDF=false` to remove it. `poppler-utils` comes from the distribution at build time and is not pinned to a version, so a rebuild of the same commit can ship another poppler (accepted; the base image digest is pinned). The text of a PDF (`pdftotext`, same limits, control characters removed, at most 200,000 characters) is only matched by search, never shown, and it is in the index only while the item is not in the bin and the PDF is not in the bin; a draft is found only by curators, as before. The preview queue is single, so a very long PDF delays other previews (at most 60 s per page); copies of a PDF left by a stopped app are removed at the next start. | diff --git a/src/Commonage.Web/Audit/AuditText.cs b/src/Commonage.Web/Audit/AuditText.cs index 69b9ecd..a123165 100644 --- a/src/Commonage.Web/Audit/AuditText.cs +++ b/src/Commonage.Web/Audit/AuditText.cs @@ -52,6 +52,7 @@ public static class AuditText AuditAction.ContributionLinkChanged => localizer["Changed the contribution link"], AuditAction.AccountCreated => localizer["Created the account"], AuditAction.AccountRoleChanged => localizer["Changed the account's role"], + AuditAction.AccountNameChanged => localizer["Changed the name of an account"], AuditAction.AccountDisabled => localizer["Disabled the account"], AuditAction.AccountEnabled => localizer["Enabled the account"], AuditAction.AccountDeleted => localizer["Deleted the account"], @@ -93,7 +94,7 @@ or AuditAction.VisitorNoteReceived or AuditAction.VisitorNoteHandled or AuditAct AuditAction.CollectionCreated or AuditAction.CollectionChanged or AuditAction.CollectionMoved or AuditAction.CollectionDeleted => AuditKind.Collections, AuditAction.TagChanged or AuditAction.TagsMerged or AuditAction.TagDeleted or AuditAction.UnusedTagsDeleted => AuditKind.Tags, - AuditAction.AccountCreated or AuditAction.AccountRoleChanged or AuditAction.AccountDisabled or AuditAction.AccountEnabled + AuditAction.AccountCreated or AuditAction.AccountRoleChanged or AuditAction.AccountNameChanged or AuditAction.AccountDisabled or AuditAction.AccountEnabled or AuditAction.AccountDeleted or AuditAction.SetupLinkCreated or AuditAction.PasswordChanged or AuditAction.TwoFactorEnabled or AuditAction.TwoFactorDisabled or AuditAction.TwoFactorTurnedOff or AuditAction.RecoveryCodesCreated or AuditAction.RecoveryCodeUsed => AuditKind.Accounts, diff --git a/src/Commonage.Web/Data/CommonageDbContext.cs b/src/Commonage.Web/Data/CommonageDbContext.cs index 7410c0e..8fbcc5f 100644 --- a/src/Commonage.Web/Data/CommonageDbContext.cs +++ b/src/Commonage.Web/Data/CommonageDbContext.cs @@ -14,6 +14,7 @@ public class CommonageDbContext(DbContextOptions options) public DbSet ArchiveItems => Set(); public DbSet MediaFiles => Set(); public DbSet ItemFileTexts => Set(); + public DbSet StaffProfiles => Set(); public DbSet Tags => Set(); public DbSet ContributionLinks => Set(); public DbSet Contributions => Set(); @@ -132,6 +133,13 @@ protected override void OnModelCreating(ModelBuilder builder) .OnDelete(DeleteBehavior.Cascade); }); + builder.Entity(profile => + { + profile.HasKey(p => p.UserId); + profile.Property(p => p.DisplayName).HasMaxLength(StaffProfile.DisplayNameMaxLength); + profile.HasOne().WithOne().HasForeignKey(p => p.UserId).OnDelete(DeleteBehavior.Cascade); + }); + builder.Entity(text => { text.HasKey(t => t.ArchiveItemId); diff --git a/src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.Designer.cs b/src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.Designer.cs new file mode 100644 index 0000000..b2fc212 --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.Designer.cs @@ -0,0 +1,1060 @@ +// +using System; +using Commonage.Web.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using NpgsqlTypes; + +#nullable disable + +namespace Commonage.Web.Data.Migrations +{ + [DbContext(typeof(CommonageDbContext))] + [Migration("20261115180842_StaffProfiles")] + partial class StaffProfiles + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ArchiveItemTag", b => + { + b.Property("ItemsId") + .HasColumnType("integer"); + + b.Property("TagsId") + .HasColumnType("integer"); + + b.HasKey("ItemsId", "TagsId"); + + b.HasIndex("TagsId"); + + b.ToTable("ArchiveItemTag"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CollectionId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Credit") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("DateFrom") + .HasColumnType("date"); + + b.Property("DateText") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("DateTo") + .HasColumnType("date"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("HelpWanted") + .HasColumnType("boolean"); + + b.Property("InternalNotes") + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.Property("NeedsTranscription") + .HasColumnType("boolean"); + + b.Property("OriginalLocation") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("PublishedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReceivedFrom") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ReceivedOn") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ReferenceNumber") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RejectedOrWithdrawnAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RightsHolder") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("RightsUri") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("SearchVector") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("tsvector") + .HasComputedColumnSql("setweight(to_tsvector('simple', commonage_fold(coalesce(\"Title\", ''))), 'A') || setweight(to_tsvector('simple', commonage_fold(coalesce(\"TagNames\", '') || ' ' || coalesce(\"DateText\", ''))), 'B') || setweight(to_tsvector('simple', commonage_fold(coalesce(\"Description\", ''))), 'C')", true); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TagNames") + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("xid") + .HasColumnName("xmin"); + + b.HasKey("Id"); + + b.HasIndex("CollectionId"); + + b.HasIndex("DateFrom"); + + b.HasIndex("DateTo"); + + b.HasIndex("ReferenceNumber") + .IsUnique(); + + b.HasIndex("SearchVector"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("SearchVector"), "GIN"); + + b.HasIndex("Status"); + + b.ToTable("ArchiveItems"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveSettings", b => + { + b.Property("Id") + .HasColumnType("integer"); + + b.Property("AccentColor") + .HasMaxLength(7) + .HasColumnType("character varying(7)"); + + b.Property("AcceptVisitorNotes") + .HasColumnType("boolean"); + + b.Property("ActivityLogKeptYears") + .HasColumnType("integer"); + + b.Property("AllowSearchEngines") + .HasColumnType("boolean"); + + b.Property("ContentLanguage") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("DefaultLanguage") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("DefaultRightsUri") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ImprintNotNeeded") + .HasColumnType("boolean"); + + b.Property("LargePhotos") + .HasColumnType("boolean"); + + b.Property("LogoId") + .HasColumnType("uuid"); + + b.Property("OtherContentLanguages") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PrivacyReviewed") + .HasColumnType("boolean"); + + b.Property("RejectedKeptMonths") + .HasColumnType("integer"); + + b.Property("RequireTwoFactor") + .HasColumnType("boolean"); + + b.Property("RestoreTestedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeZone") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.ToTable("ArchiveSettings"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveText", b => + { + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("Kind") + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("character varying(20000)"); + + b.HasKey("Language", "Kind"); + + b.ToTable("ArchiveTexts"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.AuditEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("At") + .HasColumnType("timestamp with time zone"); + + b.Property("Subject") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("At"); + + b.ToTable("AuditEntries"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Collection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CoverMediaFileId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("Sort") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("CoverMediaFileId"); + + b.HasIndex("Position"); + + b.ToTable("Collections"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Contribution", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("ConsentCoversSharing") + .HasColumnType("boolean"); + + b.Property("ConsentText") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("ContributionLinkId") + .HasColumnType("integer"); + + b.Property("ContributorEmail") + .HasMaxLength(254) + .HasColumnType("character varying(254)"); + + b.Property("ContributorName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PersonalDetailsRemovedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReferenceCode") + .HasMaxLength(9) + .HasColumnType("character varying(9)"); + + b.Property("Reuse") + .HasColumnType("integer"); + + b.Property("ReviewedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Rights") + .HasColumnType("integer"); + + b.Property("RightsHolder") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("SendingFingerprint") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ShowName") + .HasColumnType("boolean"); + + b.Property("SubmittedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId") + .IsUnique(); + + b.HasIndex("ContributionLinkId"); + + b.HasIndex("ReferenceCode") + .IsUnique(); + + b.HasIndex("SendingFingerprint") + .IsUnique(); + + b.ToTable("Contributions"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ContributionLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CollectionId") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Introduction") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("InviteOnCollectionPage") + .HasColumnType("boolean"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CollectionId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("ContributionLinks"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ItemFileText", b => + { + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("SearchVector") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("tsvector") + .HasComputedColumnSql("setweight(to_tsvector('simple', commonage_fold(coalesce(\"Text\", ''))), 'D')", true); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("ArchiveItemId"); + + b.HasIndex("SearchVector"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("SearchVector"), "GIN"); + + b.ToTable("ItemFileTexts"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.MediaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AltText") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("Caption") + .HasColumnType("text"); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DerivativeVersion") + .HasColumnType("integer"); + + b.Property("ExtractedText") + .HasColumnType("text"); + + b.Property("HasLarge") + .HasColumnType("boolean"); + + b.Property("OriginalFileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("PageCount") + .HasColumnType("integer"); + + b.Property("Position") + .HasColumnType("integer"); + + b.Property("PreviewHeight") + .HasColumnType("integer"); + + b.Property("PreviewWidth") + .HasColumnType("integer"); + + b.Property("ProcessingAttempts") + .HasColumnType("integer"); + + b.Property("ProcessingError") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("RenderedRotation") + .HasColumnType("integer"); + + b.Property("Rotation") + .HasColumnType("integer"); + + b.Property("Sha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character(64)") + .IsFixedLength(); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("StorageId") + .HasColumnType("uuid"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("Sha256"); + + b.HasIndex("Status"); + + b.HasIndex("StorageId") + .IsUnique(); + + b.ToTable("MediaFiles"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.StaffProfile", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LastLoginAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId"); + + b.ToTable("StaffProfiles"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Tag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("NormalizedName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique(); + + b.ToTable("Tags"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.VisitorNote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ArchiveItemId") + .HasColumnType("integer"); + + b.Property("Email") + .HasMaxLength(254) + .HasColumnType("character varying(254)"); + + b.Property("HandledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PersonalDetailsRemovedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReceivedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ArchiveItemId"); + + b.HasIndex("HandledAt"); + + b.ToTable("VisitorNotes"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("text"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("ArchiveItemTag", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", null) + .WithMany() + .HasForeignKey("ItemsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Commonage.Web.Domain.Tag", null) + .WithMany() + .HasForeignKey("TagsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveItem", b => + { + b.HasOne("Commonage.Web.Domain.Collection", "Collection") + .WithMany("Items") + .HasForeignKey("CollectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Collection"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.AuditEntry", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Collection", b => + { + b.HasOne("Commonage.Web.Domain.MediaFile", null) + .WithMany() + .HasForeignKey("CoverMediaFileId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Contribution", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithOne("Contribution") + .HasForeignKey("Commonage.Web.Domain.Contribution", "ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Commonage.Web.Domain.ContributionLink", "ContributionLink") + .WithMany("Contributions") + .HasForeignKey("ContributionLinkId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ArchiveItem"); + + b.Navigation("ContributionLink"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ContributionLink", b => + { + b.HasOne("Commonage.Web.Domain.Collection", "Collection") + .WithMany() + .HasForeignKey("CollectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Collection"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ItemFileText", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithOne("FileText") + .HasForeignKey("Commonage.Web.Domain.ItemFileText", "ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.MediaFile", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany("MediaFiles") + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.StaffProfile", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithOne() + .HasForeignKey("Commonage.Web.Domain.StaffProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Commonage.Web.Domain.VisitorNote", b => + { + b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") + .WithMany() + .HasForeignKey("ArchiveItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ArchiveItem"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ArchiveItem", b => + { + b.Navigation("Contribution"); + + b.Navigation("FileText"); + + b.Navigation("MediaFiles"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.Collection", b => + { + b.Navigation("Items"); + }); + + modelBuilder.Entity("Commonage.Web.Domain.ContributionLink", b => + { + b.Navigation("Contributions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.cs b/src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.cs new file mode 100644 index 0000000..8d8cfab --- /dev/null +++ b/src/Commonage.Web/Data/Migrations/20261115180842_StaffProfiles.cs @@ -0,0 +1,41 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Commonage.Web.Data.Migrations +{ + /// + public partial class StaffProfiles : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "StaffProfiles", + columns: table => new + { + UserId = table.Column(type: "text", nullable: false), + DisplayName = table.Column(type: "character varying(100)", maxLength: 100, nullable: true), + LastLoginAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_StaffProfiles", x => x.UserId); + table.ForeignKey( + name: "FK_StaffProfiles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "StaffProfiles"); + } + } +} diff --git a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs index a25b533..b840a2d 100644 --- a/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs +++ b/src/Commonage.Web/Data/Migrations/CommonageDbContextModelSnapshot.cs @@ -561,6 +561,23 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("MediaFiles"); }); + modelBuilder.Entity("Commonage.Web.Domain.StaffProfile", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("DisplayName") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("LastLoginAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId"); + + b.ToTable("StaffProfiles"); + }); + modelBuilder.Entity("Commonage.Web.Domain.Tag", b => { b.Property("Id") @@ -945,6 +962,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("ArchiveItem"); }); + modelBuilder.Entity("Commonage.Web.Domain.StaffProfile", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithOne() + .HasForeignKey("Commonage.Web.Domain.StaffProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Commonage.Web.Domain.VisitorNote", b => { b.HasOne("Commonage.Web.Domain.ArchiveItem", "ArchiveItem") diff --git a/src/Commonage.Web/Domain/AuditEntry.cs b/src/Commonage.Web/Domain/AuditEntry.cs index 156e38d..28834dc 100644 --- a/src/Commonage.Web/Domain/AuditEntry.cs +++ b/src/Commonage.Web/Domain/AuditEntry.cs @@ -58,6 +58,7 @@ public enum AuditAction VisitorNoteDetailsRemoved, VisitorNoteDeleted, ItemsImported, + AccountNameChanged, } /// diff --git a/src/Commonage.Web/Domain/StaffProfile.cs b/src/Commonage.Web/Domain/StaffProfile.cs new file mode 100644 index 0000000..b6bdc93 --- /dev/null +++ b/src/Commonage.Web/Domain/StaffProfile.cs @@ -0,0 +1,18 @@ +namespace Commonage.Web.Domain; + +/// +/// What the app knows about a curator, helper or admin besides what Identity keeps: a name to show, and when they last +/// logged in. Staff only, and only on the accounts pages an admin sees; never on a public page, in a feed or in the export. +/// It lives in its own table so that Identity's own tables stay as they are. +/// +public class StaffProfile +{ + public const int DisplayNameMaxLength = 100; + + /// The id of the Identity account. The profile goes when the account does. + public required string UserId { get; set; } + + public string? DisplayName { get; set; } + + public DateTime? LastLoginAt { get; set; } +} diff --git a/src/Commonage.Web/Identity/StaffProfiles.cs b/src/Commonage.Web/Identity/StaffProfiles.cs new file mode 100644 index 0000000..5a84399 --- /dev/null +++ b/src/Commonage.Web/Identity/StaffProfiles.cs @@ -0,0 +1,45 @@ +using Commonage.Web.Data; +using Commonage.Web.Domain; +using Microsoft.EntityFrameworkCore; + +namespace Commonage.Web.Identity; + +/// Reads and writes , which exists only once there is something to keep. +public static class StaffProfiles +{ + /// Remembers a login. Called after the person has passed every check. + public static async Task RecordLoginAsync(CommonageDbContext db, TimeProvider clock, string userId, CancellationToken cancellationToken = default) + { + var profile = await db.StaffProfiles.FindAsync([userId], cancellationToken); + if (profile is null) + db.StaffProfiles.Add(profile = new StaffProfile { UserId = userId }); + profile.LastLoginAt = clock.GetUtcNow().UtcDateTime; + try + { + await db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Two logins at the same moment both tried to add the row. A time that is a second off must not fail a valid login. + db.ChangeTracker.Clear(); + } + } + + /// Sets the name to show. Empty means none. Returns false when it did not change. + public static async Task SetDisplayNameAsync(CommonageDbContext db, string userId, string? name, CancellationToken cancellationToken = default) + { + name = string.IsNullOrWhiteSpace(name) ? null : name.Trim(); + var profile = await db.StaffProfiles.FindAsync([userId], cancellationToken); + if (profile is null) + { + if (name is null) + return false; + db.StaffProfiles.Add(new StaffProfile { UserId = userId, DisplayName = name }); + return true; + } + if (profile.DisplayName == name) + return false; + profile.DisplayName = name; + return true; + } +} diff --git a/src/Commonage.Web/Pages/Account/Login.cshtml.cs b/src/Commonage.Web/Pages/Account/Login.cshtml.cs index 37178f3..da1e5a4 100644 --- a/src/Commonage.Web/Pages/Account/Login.cshtml.cs +++ b/src/Commonage.Web/Pages/Account/Login.cshtml.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using Commonage.Web.Data; using Commonage.Web.Identity; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; @@ -7,7 +8,7 @@ namespace Commonage.Web.Pages.Account; -public class LoginModel(SignInManager signInManager, IStringLocalizer localizer) : PageModel +public class LoginModel(SignInManager signInManager, CommonageDbContext db, TimeProvider clock, IStringLocalizer localizer) : PageModel { [BindProperty] public InputModel Input { get; set; } = new(); @@ -35,7 +36,11 @@ public async Task OnPostAsync(string? returnUrl) var result = await signInManager.PasswordSignInAsync(Input.Email, Input.Password, isPersistent: false, lockoutOnFailure: true); if (result.Succeeded) + { + if (await signInManager.UserManager.FindByNameAsync(Input.Email) is { } account) + await StaffProfiles.RecordLoginAsync(db, clock, account.Id, HttpContext.RequestAborted); return LocalRedirect(Url.IsLocalUrl(returnUrl) ? returnUrl : "/Admin"); + } if (result.RequiresTwoFactor) return RedirectToPage("LoginTwoFactor", new { returnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : null }); diff --git a/src/Commonage.Web/Pages/Account/LoginTwoFactor.cshtml.cs b/src/Commonage.Web/Pages/Account/LoginTwoFactor.cshtml.cs index 5e4a1e2..568cd96 100644 --- a/src/Commonage.Web/Pages/Account/LoginTwoFactor.cshtml.cs +++ b/src/Commonage.Web/Pages/Account/LoginTwoFactor.cshtml.cs @@ -15,6 +15,7 @@ public class LoginTwoFactorModel( SignInManager signIn, AuditLog audit, CommonageDbContext db, + TimeProvider clock, IStringLocalizer localizer) : PageModel { [BindProperty] @@ -53,6 +54,7 @@ public async Task OnPostAsync(string? returnUrl) audit.RecordFor(user, AuditAction.RecoveryCodeUsed, user.Email); await db.SaveChangesAsync(); } + await StaffProfiles.RecordLoginAsync(db, clock, user.Id, HttpContext.RequestAborted); return LocalRedirect(Url.IsLocalUrl(returnUrl) ? returnUrl : "/Admin"); } diff --git a/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml b/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml index fad3fff..4a3455f 100644 --- a/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml +++ b/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml @@ -31,6 +31,32 @@ } + @if (Model.Account is not null) + { +
+
@T["Last login"]
+
+ @if (Model.LastLoginAt is { } lastLogin) + { + + } + else + { + @T["Never"] + } +
+
+
+
+ + +
@T["Shown to admins on this page and in the list of accounts. Never to visitors."]
+ +
+ +
+ } + @if (Model.Account is null) {

@T["The new account gets a setup link instead of a password. Commonage sends no emails, so you pass the link on yourself."]

@@ -41,6 +67,11 @@ +
+ + + +
diff --git a/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml.cs b/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml.cs index f16cd22..01ca440 100644 --- a/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Users/Edit.cshtml.cs @@ -26,6 +26,7 @@ public class EditModel( public IdentityUser? Account { get; private set; } public AccountState State { get; private set; } public bool IsOwnAccount { get; private set; } + public DateTime? LastLoginAt { get; private set; } /// Shown once, right after it was created. It is never stored by the app. public string? SetupLink { get; private set; } @@ -38,6 +39,10 @@ public class InputModel [Display(Name = "Email address")] public string Email { get; set; } = ""; + [StringLength(StaffProfile.DisplayNameMaxLength, ErrorMessage = "The name can be at most {1} characters long.")] + [Display(Name = "Name")] + public string? DisplayName { get; set; } + [Display(Name = "Role")] public string Role { get; set; } = Roles.Curator; } @@ -51,6 +56,7 @@ public async Task OnGetAsync(string? id) return NotFound(); Input.Email = account.Email ?? ""; Input.Role = await RoleOfAsync(account); + Input.DisplayName = (await db.StaffProfiles.FindAsync(id))?.DisplayName; return Page(); } @@ -72,6 +78,7 @@ public async Task OnPostCreateAsync() } await users.AddToRoleAsync(account, Input.Role); + await StaffProfiles.SetDisplayNameAsync(db, account.Id, Input.DisplayName); audit.Record(AuditAction.AccountCreated, $"{email} ({Input.Role})"); await db.SaveChangesAsync(); return await ShowSetupLinkAsync(account); @@ -97,6 +104,31 @@ public async Task OnPostRoleAsync(string id) return RedirectToPage(new { id }); } + /// The name to show. An admin may set their own too, unlike the role. + public async Task OnPostNameAsync(string id) + { + if (await LoadForChangeAsync(id) is not { } account) + return NotFound(); + Input.DisplayName = Input.DisplayName?.Trim(); + if (Input.DisplayName is { Length: > StaffProfile.DisplayNameMaxLength }) + { + ModelState.AddModelError("Input.DisplayName", + localizer["The name can be at most {1} characters long.", "", StaffProfile.DisplayNameMaxLength]); + Input.Email = account.Email ?? ""; + Input.Role = await RoleOfAsync(account); + return Page(); + } + + if (await StaffProfiles.SetDisplayNameAsync(db, account.Id, Input.DisplayName)) + { + audit.Record(AuditAction.AccountNameChanged, account.Email); + await db.SaveChangesAsync(); + } + + TempData["Message"] = localizer["Your changes are saved."].Value; + return RedirectToPage(new { id }); + } + public async Task OnPostDisableAsync(string id) { if (await LoadForChangeAsync(id) is not { } account) @@ -181,6 +213,7 @@ private async Task ShowSetupLinkAsync(IdentityUser account) await LoadAsync(account.Id); Input.Email = account.Email ?? ""; Input.Role = await RoleOfAsync(account); + Input.DisplayName = (await db.StaffProfiles.FindAsync(account.Id))?.DisplayName; // Shown on this response only, so the link is not kept in the browser's history or in a cookie. Response.Headers.CacheControl = "no-store"; return Page(); @@ -192,6 +225,7 @@ private async Task ShowSetupLinkAsync(IdentityUser account) if (Account is not null) { State = AccountStates.Of(Account); + LastLoginAt = (await db.StaffProfiles.FindAsync(id))?.LastLoginAt; IsOwnAccount = Account.Id == users.GetUserId(User); } return Account; diff --git a/src/Commonage.Web/Pages/Admin/Users/Index.cshtml b/src/Commonage.Web/Pages/Admin/Users/Index.cshtml index fa35bf3..3d33700 100644 --- a/src/Commonage.Web/Pages/Admin/Users/Index.cshtml +++ b/src/Commonage.Web/Pages/Admin/Users/Index.cshtml @@ -15,20 +15,33 @@ + + @foreach (var account in Model.Accounts) { + + } diff --git a/src/Commonage.Web/Pages/Admin/Users/Index.cshtml.cs b/src/Commonage.Web/Pages/Admin/Users/Index.cshtml.cs index 7fcb10c..f5b77b4 100644 --- a/src/Commonage.Web/Pages/Admin/Users/Index.cshtml.cs +++ b/src/Commonage.Web/Pages/Admin/Users/Index.cshtml.cs @@ -1,3 +1,4 @@ +using Commonage.Web.Data; using Commonage.Web.Identity; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -5,21 +6,23 @@ namespace Commonage.Web.Pages.Admin.Users; -public class IndexModel(UserManager users) : PageModel +public class IndexModel(UserManager users, CommonageDbContext db) : PageModel { - public record Account(string Id, string Name, string? Role, AccountState State, bool TwoFactor); + public record Account(string Id, string Name, string? Role, AccountState State, bool TwoFactor, string? DisplayName, DateTime? LastLoginAt); public IReadOnlyList Accounts { get; private set; } = []; public async Task OnGetAsync() { + var profiles = await db.StaffProfiles.ToDictionaryAsync(p => p.UserId); var list = new List(); foreach (var user in await users.Users.OrderBy(u => u.NormalizedEmail).ToListAsync()) { var roles = await users.GetRolesAsync(user); list.Add(new Account(user.Id, user.Email ?? user.UserName ?? user.Id, roles.Contains(Roles.Admin) ? Roles.Admin : roles.Contains(Roles.Curator) ? Roles.Curator : roles.FirstOrDefault(), - AccountStates.Of(user), user.TwoFactorEnabled)); + AccountStates.Of(user), user.TwoFactorEnabled, + profiles.GetValueOrDefault(user.Id)?.DisplayName, profiles.GetValueOrDefault(user.Id)?.LastLoginAt)); } Accounts = list; } diff --git a/src/Commonage.Web/Resources/SharedResource.de.resx b/src/Commonage.Web/Resources/SharedResource.de.resx index 600d4e5..6885229 100644 --- a/src/Commonage.Web/Resources/SharedResource.de.resx +++ b/src/Commonage.Web/Resources/SharedResource.de.resx @@ -987,4 +987,9 @@ Helferin/Helfer Beschreibt Einträge und fügt Fotos hinzu. Kann nichts veröffentlichen oder löschen, keine Beiträge prüfen und keine Angaben zu Beitragenden sehen. Diese Signatur wird bereits von einem anderen Eintrag verwendet. + Name eines Kontos geändert + Nie + Letzte Anmeldung + Namen speichern + Wird Admins auf dieser Seite und in der Liste der Konten gezeigt, nie Besucherinnen und Besuchern. diff --git a/src/Commonage.Web/Resources/SharedResource.resx b/src/Commonage.Web/Resources/SharedResource.resx index 602fadd..4da5519 100644 --- a/src/Commonage.Web/Resources/SharedResource.resx +++ b/src/Commonage.Web/Resources/SharedResource.resx @@ -107,6 +107,7 @@ Changed the collection Changed the contribution link Changed the item + Changed the name of an account Changed the order of the collections Changed the order or direction of photos Changed the tag @@ -344,6 +345,7 @@ Last backup: {0} Last changed Last database change + Last login Later Later: {0} Leave this field empty @@ -406,6 +408,7 @@ Names, places, events … Needed for both buttons, so that nobody else can use a computer you left logged in. Needs attention + Never New account New collection New contribution link @@ -605,6 +608,7 @@ Save and next Save and publish Save as draft + Save name Save password Save role Save these details @@ -644,6 +648,7 @@ Show everything Show my name with what I send in Showing the newest {0}. + Shown to admins on this page and in the list of accounts. Never to visitors. Six digits. Without your phone, type one of your recovery codes instead. Each one works once. Skip to content Software diff --git a/tests/Commonage.Tests/AccountTests.cs b/tests/Commonage.Tests/AccountTests.cs index 334aa99..bf73e3f 100644 --- a/tests/Commonage.Tests/AccountTests.cs +++ b/tests/Commonage.Tests/AccountTests.cs @@ -171,4 +171,36 @@ public async Task Half_a_setup_link_does_not_say_whose_account_it_is() Assert.DoesNotContain(email, half); Assert.Contains("This link is no longer valid", half); } + + [Fact] + public async Task An_account_shows_its_name_and_last_login_to_admins_and_the_activity_log_keeps_the_email() + { + using var admin = app.CreateClient(); + await Browser.LogInAsCuratorAsync(admin); + var (curator, id, email, password) = await app.CreateAccountAsync(admin); + curator.Dispose(); + var name = $"Volunteer {Guid.NewGuid():N}"; + + await Browser.PostFormAsync(admin, $"/Admin/Users/Edit/{id}?handler=Name", new() { ["Input.DisplayName"] = name }, pageUrl: $"/Admin/Users/Edit/{id}"); + var list = await admin.GetStringAsync("/Admin/Users"); + var log = await admin.GetStringAsync("/Admin/Activity"); + var profile = await app.WithDbAsync(db => db.StaffProfiles.SingleAsync(p => p.UserId == id)); + + Assert.Contains(name, list); + Assert.Contains(email, log); + Assert.DoesNotContain(name, log); + Assert.Contains("Changed the name of an account", log); + // Creating the account logged it in once. + Assert.NotNull(profile.LastLoginAt); + using var wrong = app.CreateClient(); + await Browser.SendFormAsync(wrong, "/Account/Login", new() { ["Input.Email"] = email, ["Input.Password"] = "Wrong-password-1" }); + Assert.Equal(profile.LastLoginAt, (await app.WithDbAsync(db => db.StaffProfiles.SingleAsync(p => p.UserId == id))).LastLoginAt); + using var again = app.CreateClient(); + await Browser.LogInAsync(again, email, password); + Assert.True((await app.WithDbAsync(db => db.StaffProfiles.SingleAsync(p => p.UserId == id))).LastLoginAt > profile.LastLoginAt); + // Visitors and curators never see it. + using var visitor = app.CreateClient(); + Assert.DoesNotContain(name, await visitor.GetStringAsync("/")); + Assert.Equal(HttpStatusCode.Forbidden, (await again.GetAsync("/Admin/Users")).StatusCode); + } } From 35b9cf53560e3f17b6df81caeac34a5fa890765f Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:41:16 +0100 Subject: [PATCH 2/3] Show what the database holds when the PDF search test fails The test fails now and then on CI only, where poppler is installed, and the cause is not known yet. A failure now says what was stored. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- tests/Commonage.Tests/PdfTests.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/Commonage.Tests/PdfTests.cs b/tests/Commonage.Tests/PdfTests.cs index fa4d0c1..bd19609 100644 --- a/tests/Commonage.Tests/PdfTests.cs +++ b/tests/Commonage.Tests/PdfTests.cs @@ -198,7 +198,17 @@ public async Task A_PDF_is_found_by_its_text_until_it_goes_to_the_bin_and_again_ if (!found.Contains("Items found: 1")) await Task.Delay(100); } - Assert.Contains("Items found: 1", found); + if (!found.Contains("Items found: 1")) + { + // Shown only on a failure: what the database holds, so that a failure on a machine that is not this one can be understood. + var state = await app.WithDbAsync(async db => + { + var stored = await db.MediaFiles.IgnoreQueryFilters().AsNoTracking().SingleAsync(f => f.Id == file.Id); + var row = await db.ItemFileTexts.IgnoreQueryFilters().AsNoTracking().FirstOrDefaultAsync(t => t.ArchiveItemId == item.Id); + return $"status {stored.Status}, error '{stored.ProcessingError}', extracted '{stored.ExtractedText}', index row '{row?.Text}', word '{word}'"; + }); + Assert.Fail("The text was not found. " + state); + } var itemPage = await visitor.GetStringAsync($"/items/{item.Id}"); Assert.Contains($"/media/{file.Id}/page/3", itemPage); Assert.Contains("Page 2 of 3", itemPage); From 6b0f08cdf4cf2e124227f6aab10c3943722eb240 Mon Sep 17 00:00:00 2001 From: "Seb H." <138793908+SebHenn@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:49:08 +0100 Subject: [PATCH 3/3] Set the text of the test PDF small enough to stay on the page A long random word at 24 pt ran past the page edge, and poppler leaves out what falls outside the page, so the last letter was missing and the PDF search test failed now and then. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Seb H. <138793908+SebHenn@users.noreply.github.com> --- tests/Commonage.Tests/PdfTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Commonage.Tests/PdfTests.cs b/tests/Commonage.Tests/PdfTests.cs index bd19609..67bf67d 100644 --- a/tests/Commonage.Tests/PdfTests.cs +++ b/tests/Commonage.Tests/PdfTests.cs @@ -52,7 +52,7 @@ internal static byte[] MakePdf(int pages, string word = "") }; for (var page = 1; page <= pages; page++) { - var content = $"BT /F1 24 Tf 50 700 Td (Page {page} {word}) Tj ET"; + var content = $"BT /F1 10 Tf 50 700 Td (Page {page} {word}) Tj ET"; objects.Add($"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents {5 + (page - 1) * 2} 0 R >>"); objects.Add($"<< /Length {content.Length} >>\nstream\n{content}\nendstream"); }
@T["Name"] @T["Email address"] @T["Role"] @T["Status"] @T["Authenticator app"]@T["Last login"]
@account.DisplayName @account.Name @(account.Role is null ? T["No role"] : T[account.Role]) @(account.TwoFactor ? T["Yes"] : T["No"]) + @if (account.LastLoginAt is { } lastLogin) + { + + } + else + { + @T["Never"] + } +