Separate password lockouts from account restrictions
What changed, and why it matters
This commit rewrites how BTCPay Server blocks users. Previously, the app reused ASP.NET Identity's password-lockout mechanism to disable accounts permanently (for admin bans) and for subscription/monetization reasons. That caused a side effect: too many wrong password attempts could lock an account and also disable its API keys. The change introduces a separate 'user access restrictions' table so that password lockouts and account disabling are independent. API keys now keep working during a temporary password lockout, while admin or monetization restrictions still block access. The commit also adds a migration that converts existing permanent lockouts into the new restriction records.
Review the migration SQL carefully before deploying, especially the classification of existing permanent lockouts into Administrative vs Monetization, because misclassification could unintentionally re-enable or restrict users. Verify that all authentication paths (API key, basic auth, password, FIDO2, LNURL-auth, authenticator) correctly distinguish lockout from restriction. Run the new integration tests and consider adding tests for concurrent restriction changes and for the migration's edge cases.
Security signals we found
Separation of authentication lockout from authorization restriction
New UserAccessRestriction table for administrative and monetization restrictions
API key authentication no longer disabled by password lockout
Migration of existing permanent lockouts to new restriction model
Security stamp invalidation still applied when restriction is added
Store noActiveUser flag recomputed based on access restrictions
Evidence from the diff
The patch adds a new UserAccessRestriction entity/table keyed on (user_id, type) with types ‘Administrative’ and ‘Monetization’. It removes the ApplicationUser.IsDisabled/IsDisabledTemporarily computed properties and replaces them with checks against AccessRestrictions. UserService.SetDisabled now delegates to SetAccessRestriction, which inserts/deletes rows in user_access_restrictions instead of setting LockoutEnd to DateTimeOffset.MaxValue. Login checks now use userManager.IsLockedOutAsync for temporary password lockouts and AccessRestrictions for administrative/monetization blocks. The migration 20261027000000_UserAccessRestrictions creates the table, classifies existing permanent lockouts as Administrative or Monetization based on subscription data, clears those permanent lockouts, and recalculates store noActiveUser flags using the new table. Tests confirm that API keys remain usable during password lockout but are rejected when an administrative restriction is set.
Changed components
BTCPayServer.Data/UserAccessRestrictionBTCPayServer/Services/UserService.csBTCPayServer/Controllers/UIAccountController.csBTCPayServer/Controllers/GreenField/GreenfieldUsersController.csBTCPayServer/Controllers/UIServerController.Users.csBTCPayServer/Plugins/Monetization/MonetizationHostedService.csBTCPayServer/Plugins/Monetization/MonetizationLoginExtension.csBTCPayServer/Security/GreenField/APIKeyRepository.csBTCPayServer/Security/GreenField/BasicAuthenticationHandler.csBTCPayServer.Data/Migrations/20261027000000_UserAccessRestrictions.csInspect captured patch +557 / −133
### BTCPayServer.Data/ApplicationDbContext.cs
@@ -47,6 +47,7 @@ public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
public DbSet<U2FDevice> U2FDevices { get; set; }
public DbSet<Fido2Credential> Fido2Credentials { get; set; }
public DbSet<UserStore> UserStore { get; set; }
+ public DbSet<UserAccessRestriction> UserAccessRestrictions { get; set; }
public DbSet<StoreLabelData> StoreLabels { get; set; }
public DbSet<StoreLabelLinkData> StoreLabelLinks { get; set; }
public DbSet<StoreRole> StoreRoles { get; set; }
@@ -104,6 +105,7 @@ protected override void OnModelCreating(ModelBuilder builder)
U2FDevice.OnModelCreating(builder);
Fido2Credential.OnModelCreating(builder, Database);
BTCPayServer.Data.UserStore.OnModelCreating(builder);
+ UserAccessRestriction.OnModelCreating(builder);
//WalletData.OnModelCreating(builder);
WalletObjectData.OnModelCreating(builder, Database);
WalletObjectLinkData.OnModelCreating(builder, Database);
### BTCPayServer.Data/ApplicationDbContextExtensions.Users.cs
@@ -37,22 +37,23 @@ public static Task UpdateStoreNoActiveUserCore(this DbSet<ApplicationUser> dbSet
=> dbSet.GetDbConnection()
.ExecuteAsync(GetUpdateStoreNoActiveUserQuery(selectStoresSql), parameters);
- internal static string GetUpdateStoreNoActiveUserQuery(string selectStoresSql)
+ private static string GetUpdateStoreNoActiveUserQuery(string selectStoresSql)
=> $$"""
WITH
-- Select all the stores belonging to the userIds
stores AS (
{{selectStoresSql}}
),
- -- Count all active users of the store
- active_users AS (
- SELECT s."Id",
- COUNT(u."Id") FILTER (WHERE u."LockoutEnd" IS NULL OR u."LockoutEnd" <= NOW()) AS active_users
- FROM stores st
- JOIN "Stores" s ON s."Id" = st.store_id
- LEFT JOIN "UserStore" us ON us."StoreDataId" = s."Id"
- LEFT JOIN "AspNetUsers" u ON u."Id" = us."ApplicationUserId"
- GROUP BY s."Id"
+ -- Count all active users of the store
+ active_users AS (
+ SELECT s."Id",
+ COUNT(DISTINCT u."Id") FILTER (WHERE uar.user_id IS NULL) AS active_users
+ FROM stores st
+ JOIN "Stores" s ON s."Id" = st.store_id
+ LEFT JOIN "UserStore" us ON us."StoreDataId" = s."Id"
+ LEFT JOIN "AspNetUsers" u ON u."Id" = us."ApplicationUserId"
+ LEFT JOIN user_access_restrictions uar ON uar.user_id = u."Id"
+ GROUP BY s."Id"
),
-- If the total is 0, then the store should have noActiveUser set to true
expected_disabled AS (
### BTCPayServer.Data/Data/ApplicationUser.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
@@ -27,6 +26,7 @@ public ApplicationUser()
public bool AuthenticatorEnabled { get; set; }
public List<NotificationData> Notifications { get; set; }
public List<UserStore> UserStores { get; set; }
+ public List<UserAccessRestriction> AccessRestrictions { get; set; }
public List<Fido2Credential> Fido2Credentials { get; set; }
[Obsolete("Use Blob2 instead")]
@@ -35,14 +35,6 @@ public ApplicationUser()
public List<IdentityUserRole<string>> UserRoles { get; set; }
- [NotMapped]
- public bool IsDisabled =>
- this is { LockoutEnabled: true, LockoutEnd: { } lockoutEnd } &&
- DateTimeOffset.UtcNow < lockoutEnd.UtcDateTime;
- [NotMapped]
- public bool IsDisabledTemporarily =>
- IsDisabled && DateTimeOffset.MaxValue - LockoutEnd!.Value >= TimeSpan.FromSeconds(1);
-
public static void OnModelCreating(ModelBuilder builder, DatabaseFacade databaseFacade)
{
builder.Entity<ApplicationUser>()
### BTCPayServer.Data/Data/UserAccessRestriction.cs
@@ -0,0 +1,36 @@
+using System;
+using System.ComponentModel.DataAnnotations.Schema;
+using Microsoft.EntityFrameworkCore;
+
+namespace BTCPayServer.Data;
+
+public static class UserAccessRestrictionConstants
+{
+ public const string Administrative = "Administrative";
+ public const string Monetization = "Monetization";
+}
+
+[Table("user_access_restrictions")]
+[PrimaryKey(nameof(ApplicationUserId), nameof(Type))]
+public class UserAccessRestriction
+{
+ [Column("user_id")]
+ public string ApplicationUserId { get; set; }
+
+ [ForeignKey(nameof(ApplicationUserId))]
+ public ApplicationUser ApplicationUser { get; set; }
+
+ [Column("type")]
+ public string Type { get; set; }
+
+ [Column("created_at", TypeName = "timestamptz")]
+ public DateTimeOffset CreatedAt { get; set; }
+
+ public static void OnModelCreating(ModelBuilder builder)
+ {
+ var entity = builder.Entity<UserAccessRestriction>();
+ entity.HasOne(restriction => restriction.ApplicationUser)
+ .WithMany(user => user.AccessRestrictions)
+ .OnDelete(DeleteBehavior.Cascade);
+ }
+}
### BTCPayServer.Data/Migrations/20260112034124_disable_orphan_stores.cs
@@ -10,6 +10,28 @@ public class disable_orphan_stores : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
- migrationBuilder.Sql(ApplicationDbContextExtensions.GetUpdateStoreNoActiveUserQuery("SELECT DISTINCT \"Id\" store_id FROM \"Stores\""));
+ migrationBuilder.Sql("""
+ WITH
+ stores AS (
+ SELECT DISTINCT "Id" store_id FROM "Stores"
+ ),
+ active_users AS (
+ SELECT s."Id",
+ COUNT(u."Id") FILTER (WHERE u."LockoutEnd" IS NULL OR u."LockoutEnd" <= NOW()) AS active_users
+ FROM stores st
+ JOIN "Stores" s ON s."Id" = st.store_id
+ LEFT JOIN "UserStore" us ON us."StoreDataId" = s."Id"
+ LEFT JOIN "AspNetUsers" u ON u."Id" = us."ApplicationUserId"
+ GROUP BY s."Id"
+ ),
+ expected_disabled AS (
+ SELECT s."Id", COALESCE(s."StoreBlob"->'noActiveUser' = 'true'::JSONB, false) current_value, t.active_users = 0 expected_value FROM active_users t
+ JOIN "Stores" s ON s."Id" = t."Id"
+ )
+ UPDATE "Stores" s
+ SET "StoreBlob" = jsonb_set("StoreBlob", '{noActiveUser}', to_jsonb(ed.expected_value))
+ FROM expected_disabled ed
+ WHERE s."Id" = ed."Id" AND ed.expected_value <> ed.current_value;
+ """);
}
}
### BTCPayServer.Data/Migrations/20261027000000_UserAccessRestrictions.cs
@@ -0,0 +1,117 @@
+using System;
+using BTCPayServer.Data;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace BTCPayServer.Migrations;
+
+[DbContext(typeof(ApplicationDbContext))]
+[Migration("20261027000000_UserAccessRestrictions")]
+public partial class UserAccessRestrictions : Migration
+{
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "user_access_restrictions",
+ columns: table => new
+ {
+ user_id = table.Column<string>(type: "text", nullable: false),
+ type = table.Column<string>(type: "text", nullable: false),
+ created_at = table.Column<DateTimeOffset>(type: "timestamptz", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_user_access_restrictions", x => new { x.user_id, x.type });
+ table.ForeignKey(
+ name: "FK_user_access_restrictions_AspNetUsers_user_id",
+ column: x => x.user_id,
+ principalTable: "AspNetUsers",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ // Permanent Identity lockouts did not record whether they came from an administrator or monetization.
+ // Classify users whose current monetization data clearly denies access as monetization-restricted and
+ // conservatively treat every other permanent lockout as administrative.
+ migrationBuilder.Sql("""
+ WITH permanent_lockouts AS (
+ SELECT users."Id" AS user_id
+ FROM "AspNetUsers" users
+ WHERE users."LockoutEnd" >= '9999-12-31 23:59:58+00'::timestamptz
+ ),
+ monetization_lockouts AS (
+ SELECT DISTINCT permanent_lockouts.user_id
+ FROM permanent_lockouts
+ JOIN "AspNetUsers" users ON users."Id" = permanent_lockouts.user_id
+ JOIN "Settings" settings
+ ON settings."Id" = 'BTCPayServer.Plugins.Monetization.MonetizationSettings'
+ JOIN customers_identities identity
+ ON identity.type = 'ApplicationUserId'
+ AND identity.value = permanent_lockouts.user_id
+ JOIN subs_subscribers subscriber
+ ON subscriber.customer_id = identity.customer_id
+ AND subscriber.offering_id = settings."Value"->>'OfferingId'
+ WHERE NOT users."BypassMonetization"
+ AND subscriber.suspension_reason IS DISTINCT FROM 'Account disabled by administrator'
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "AspNetUserRoles" user_role
+ JOIN "AspNetRoles" role ON role."Id" = user_role."RoleId"
+ WHERE user_role."UserId" = permanent_lockouts.user_id
+ AND role."Name" = 'ServerAdmin'
+ )
+ AND (
+ NOT subscriber.active
+ OR NOT EXISTS (
+ SELECT 1
+ FROM subs_plans_features plan_feature
+ JOIN subs_features feature ON feature.id = plan_feature.feature_id
+ WHERE plan_feature.plan_id = subscriber.plan_id
+ AND feature.custom_id = 'can-access'
+ )
+ )
+ )
+ INSERT INTO user_access_restrictions (user_id, type, created_at)
+ SELECT permanent_lockouts.user_id,
+ CASE WHEN monetization_lockouts.user_id IS NULL
+ THEN 'Administrative'
+ ELSE 'Monetization'
+ END,
+ NOW()
+ FROM permanent_lockouts
+ LEFT JOIN monetization_lockouts USING (user_id);
+
+ UPDATE "AspNetUsers"
+ SET "LockoutEnd" = NULL, "AccessFailedCount" = 0
+ WHERE "LockoutEnd" >= '9999-12-31 23:59:58+00'::timestamptz;
+ """);
+
+ // The previous active-user calculation treated temporary Identity lockouts as inactive.
+ // Recalculate every store using access restrictions as the source of account availability.
+ migrationBuilder.Sql("""
+ WITH active_users AS (
+ SELECT stores."Id",
+ COUNT(DISTINCT users."Id") FILTER (WHERE restrictions.user_id IS NULL) AS active_users
+ FROM "Stores" stores
+ LEFT JOIN "UserStore" user_store ON user_store."StoreDataId" = stores."Id"
+ LEFT JOIN "AspNetUsers" users ON users."Id" = user_store."ApplicationUserId"
+ LEFT JOIN user_access_restrictions restrictions ON restrictions.user_id = users."Id"
+ GROUP BY stores."Id"
+ ),
+ expected_disabled AS (
+ SELECT stores."Id",
+ COALESCE(stores."StoreBlob"->'noActiveUser' = 'true'::jsonb, false) AS current_value,
+ active_users.active_users = 0 AS expected_value
+ FROM active_users
+ JOIN "Stores" stores ON stores."Id" = active_users."Id"
+ )
+ UPDATE "Stores" stores
+ SET "StoreBlob" = jsonb_set(stores."StoreBlob", '{noActiveUser}', to_jsonb(expected_disabled.expected_value))
+ FROM expected_disabled
+ WHERE stores."Id" = expected_disabled."Id"
+ AND expected_disabled.expected_value <> expected_disabled.current_value;
+ """);
+ }
+}
### BTCPayServer.Data/Migrations/ApplicationDbContextModelSnapshot.cs
@@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
- .HasAnnotation("ProductVersion", "10.0.11")
+ .HasAnnotation("ProductVersion", "10.0.14")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -1795,6 +1795,25 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.ToTable("U2FDevices");
});
+ modelBuilder.Entity("BTCPayServer.Data.UserAccessRestriction", b =>
+ {
+ b.Property<string>("ApplicationUserId")
+ .HasColumnType("text")
+ .HasColumnName("user_id");
+
+ b.Property<string>("Type")
+ .HasColumnType("text")
+ .HasColumnName("type");
+
+ b.Property<DateTimeOffset>("CreatedAt")
+ .HasColumnType("timestamptz")
+ .HasColumnName("created_at");
+
+ b.HasKey("ApplicationUserId", "Type");
+
+ b.ToTable("user_access_restrictions");
+ });
+
modelBuilder.Entity("BTCPayServer.Data.UserStore", b =>
{
b.Property<string>("ApplicationUserId")
@@ -2588,6 +2607,17 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Navigation("ApplicationUser");
});
+ modelBuilder.Entity("BTCPayServer.Data.UserAccessRestriction", b =>
+ {
+ b.HasOne("BTCPayServer.Data.ApplicationUser", "ApplicationUser")
+ .WithMany("AccessRestrictions")
+ .HasForeignKey("ApplicationUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ApplicationUser");
+ });
+
modelBuilder.Entity("BTCPayServer.Data.UserStore", b =>
{
b.HasOne("BTCPayServer.Data.ApplicationUser", "ApplicationUser")
@@ -2709,6 +2739,8 @@ protected override void BuildModel(ModelBuilder modelBuilder)
{
b.Navigation("APIKeys");
+ b.Navigation("AccessRestrictions");
+
b.Navigation("Fido2Credentials");
b.Navigation("Notifications");
### BTCPayServer.Tests/GreenfieldAPITests.cs
@@ -3797,6 +3797,58 @@ await AssertAPIError("unauthenticated", async () =>
await newUserBasicClient.GetCurrentUser();
}
+ [Fact(Timeout = 60 * 2 * 1000)]
+ [Trait("Integration", "Integration")]
+ public async Task PasswordLockoutDoesNotDisableApiKeys()
+ {
+ using var tester = CreateServerTester();
+ await tester.StartAsync();
+ var account = tester.NewAccount();
+ await account.GrantAccessAsync();
+ var apiKeyClient = await account.CreateClient(Policies.CanViewProfile);
+ var basicClient = new BTCPayServerClient(apiKeyClient.Host, account.RegisterDetails.Email,
+ account.RegisterDetails.Password);
+ var wrongPasswordClient = new BTCPayServerClient(apiKeyClient.Host, account.RegisterDetails.Email,
+ "not-the-password");
+
+ using (var scope = tester.PayTester.ServiceProvider.CreateScope())
+ {
+ var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
+ for (var i = 0; i < userManager.Options.Lockout.MaxFailedAccessAttempts; i++)
+ await AssertAPIError("unauthenticated", () => wrongPasswordClient.GetCurrentUser());
+ var user = await userManager.FindByIdAsync(account.UserId);
+ Assert.True(await userManager.IsLockedOutAsync(user!));
+ }
+
+ Assert.Equal(account.UserId, (await apiKeyClient.GetCurrentUser()).Id);
+ await AssertAPIError("unauthenticated", () => basicClient.GetCurrentUser());
+
+ var userService = tester.PayTester.GetService<UserService>();
+ Assert.Contains(await userService.GetUsersWithRoles(), user =>
+ user.User.Id == account.UserId && !user.Disabled);
+ Assert.IsType<UserService.SetDisabledResult.Success>(await userService.SetDisabled(account.UserId, true));
+ await AssertAPIError("unauthenticated", () => apiKeyClient.GetCurrentUser());
+ var storeRepository = tester.PayTester.GetService<StoreRepository>();
+ Assert.True((await storeRepository.FindStore(account.StoreId))!.GetStoreBlob().NoActiveUser);
+ Assert.IsType<UserService.SetDisabledResult.Success>(await userService.SetDisabled(account.UserId, false));
+
+ Assert.Equal(account.UserId, (await apiKeyClient.GetCurrentUser()).Id);
+ await AssertAPIError("unauthenticated", () => basicClient.GetCurrentUser());
+ Assert.False((await storeRepository.FindStore(account.StoreId))!.GetStoreBlob().NoActiveUser);
+
+ Assert.IsType<UserService.SetDisabledResult.Success>(
+ await userService.SetAccessRestriction(account.UserId, "Custom", true));
+ using (var scope = tester.PayTester.ServiceProvider.CreateScope())
+ {
+ var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
+ var user = await userManager.FindByIdAsync(account.UserId);
+ var loginContext = new UserService.CanLoginContext(user);
+ Assert.False(await userService.CanLogin(loginContext));
+ Assert.Contains(loginContext.Failures,
+ failure => failure.Text.Value == "Your user account is currently restricted.");
+ }
+ }
+
[Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")]
public async Task ApproveUserTests()
### BTCPayServer.Tests/MonetizationTests.cs
@@ -1,4 +1,5 @@
#nullable enable
+using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Data;
@@ -77,6 +78,8 @@ public async Task DoesNotLockOutAdminSubscriber()
Assert.NotNull(userId);
var userService = s.Server.PayTester.GetService<UserService>();
Assert.True(await userService.SetAdminUser(userId, true));
+ Assert.IsType<UserService.SetDisabledResult.Success>(
+ await userService.SetAccessRestriction(userId, UserAccessRestrictionConstants.Monetization, true));
var eventAggregator = s.Server.PayTester.GetService<EventAggregator>();
eventAggregator.Publish(new SubscriptionEvent.SubscriberDisabled(
@@ -89,10 +92,34 @@ public async Task DoesNotLockOutAdminSubscriber()
}, evt => evt.Subscriber.Customer.Email.Get() == "queue-marker@gmail.com");
var dbContextFactory = s.Server.PayTester.GetService<ApplicationDbContextFactory>();
- await using var ctx = dbContextFactory.CreateContext();
- var admin = await ctx.Users.FindAsync(userId);
- Assert.NotNull(admin);
- Assert.Null(admin.LockoutEnd);
+ ApplicationUser admin;
+ await using (var ctx = dbContextFactory.CreateContext())
+ {
+ admin = (await ctx.Users.FindAsync(userId))!;
+ Assert.NotNull(admin);
+ Assert.Null(await ctx.UserAccessRestrictions.FindAsync(userId, UserAccessRestrictionConstants.Monetization));
+ admin.EmailConfirmed = true;
+ admin.Approved = true;
+ var subscriber = await ctx.Subscribers.FindAsync(newSubscriber.Subscriber.Id);
+ Assert.NotNull(subscriber);
+ subscriber.IsActive = false;
+ await ctx.SaveChangesAsync();
+ }
+
+ Assert.IsType<UserService.SetDisabledResult.Success>(
+ await userService.SetAccessRestriction(userId, UserAccessRestrictionConstants.Monetization, true));
+ await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(() =>
+ {
+ eventAggregator.Publish(new UserEvent.BypassMonetizationChanged(admin, false, newSubscriber.RequestBaseUrl));
+ return Task.CompletedTask;
+ }, update => update.Updated.Contains((userId, false)));
+
+ await using (var ctx = dbContextFactory.CreateContext())
+ {
+ admin = (await ctx.Users.FindAsync(userId))!;
+ Assert.Null(await ctx.UserAccessRestrictions.FindAsync(userId, UserAccessRestrictionConstants.Monetization));
+ }
+ Assert.True(await userService.CanLogin(new UserService.CanLoginContext(admin)));
}
[Fact]
@@ -234,12 +261,12 @@ public async Task CanMonetizeServer()
var edit = await offeringPMO.Edit("Starter Plan");
edit.DisableFeatures = ["can-access"];
- var lockoutUpdated = await s.Server.WaitForEvent<MonetizationHostedService.MonetizationLockoutUpdated>(async () =>
+ var accessUpdated = await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(async () =>
{
await edit.Save();
});
- Assert.Equal(4, lockoutUpdated.Updated.Length);
- Assert.All(lockoutUpdated.Updated, (o) => Assert.True(o.LockoutEnabled));
+ Assert.Equal(4, accessUpdated.Updated.Length);
+ Assert.All(accessUpdated.Updated, (o) => Assert.True(o.Restricted));
// Subscribers aren't suspended... they have a valid subscription, just not one allowing access.
await s.FastReloadAsync();
@@ -283,7 +310,7 @@ public async Task CanMonetizeServer()
}
await offeringPMO.GoToSubscribers();
- await s.Server.WaitForEvent<MonetizationHostedService.MonetizationLockoutUpdated>(async () =>
+ await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(async () =>
{
await offeringPMO.Suspend("normal-guest@gmail.com", "You are banned!");
});
@@ -339,6 +366,23 @@ public async Task CanBypassMonetizationForUsers()
await SetBypassMonetization(s, "enrolled-invited@gmail.com", true);
await CanLog(s, "enrolled-invited@gmail.com");
+ // Plan updates should clear stale monetization restrictions for bypass users.
+ var userId = ev.Subscriber.GetApplicationUserId();
+ Assert.NotNull(userId);
+ var userService = s.Server.PayTester.GetService<UserService>();
+ Assert.IsType<UserService.SetDisabledResult.Success>(
+ await userService.SetAccessRestriction(userId, UserAccessRestrictionConstants.Monetization, true));
+ await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(() =>
+ {
+ s.Server.PayTester.GetService<EventAggregator>().Publish(new SubscriptionEvent.PlanUpdated(ev.Subscriber.Plan));
+ return Task.CompletedTask;
+ }, update => update.Updated.Contains((userId, false)));
+ var dbContextFactory = s.Server.PayTester.GetService<ApplicationDbContextFactory>();
+ await using (var ctx = dbContextFactory.CreateContext())
+ {
+ Assert.Null(await ctx.UserAccessRestrictions.FindAsync(userId, UserAccessRestrictionConstants.Monetization));
+ }
+
// Case 4: Edit user — remove bypass from user with no subscriber
var ev2 = await s.Server.WaitForEvent<SubscriptionEvent.NewSubscriber>(async () =>
{
@@ -355,9 +399,9 @@ public async Task CanBypassMonetizationForUsers()
await s.FindAlertMessage(partialText: "is now test");
await using (var portal = await offeringPMO.GoToPortal("enrolled-invited@gmail.com", closeAfter: false))
{
- await s.Server.WaitForEvent<MonetizationHostedService.MonetizationLockoutUpdated>(portal.GoToNextPhase);
+ await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(portal.GoToNextPhase);
}
- await s.Server.WaitForEvent<MonetizationHostedService.MonetizationLockoutUpdated>(async () =>
+ await s.Server.WaitForEvent<MonetizationHostedService.MonetizationAccessUpdated>(async () =>
{
await SetBypassMonetization(s, "enrolled-invited@gmail.com", false);
});
### BTCPayServer/Controllers/GreenField/GreenfieldUsersController.cs
@@ -139,7 +139,7 @@ public async Task<ActionResult<ApplicationUserData[]>> GetUsers()
List<ApplicationUserData> users = [];
foreach (var user in usersWithRoles)
{
- users.Add(await UserService.ForAPI<ApplicationUserData>(user.User, user.Roles, _callbackGenerator, _uriResolver, Request, canManageUsers));
+ users.Add(await UserService.ForAPI<ApplicationUserData>(user.User, user.Roles, _callbackGenerator, _uriResolver, Request, canManageUsers, user.Disabled));
}
return Ok(users);
}
@@ -471,7 +471,8 @@ public async Task<IActionResult> DeleteUser(string idOrEmail)
private async Task<ApplicationUserData> ForAPI(ApplicationUser data, bool includeInvitationUrl)
{
var roles = (await _userManager.GetRolesAsync(data)).ToArray();
- return await UserService.ForAPI<ApplicationUserData>(data, roles, _callbackGenerator, _uriResolver, Request, includeInvitationUrl);
+ var disabled = await _userService.IsRestricted(data.Id, UserAccessRestrictionConstants.Administrative);
+ return await UserService.ForAPI<ApplicationUserData>(data, roles, _callbackGenerator, _uriResolver, Request, includeInvitationUrl, disabled);
}
}
}
### BTCPayServer/Controllers/UIAccountController.cs
@@ -177,9 +177,8 @@ public async Task<IActionResult> Login(LoginViewModel model, string returnUrl =
if (model.Method == "Password")
{
user = await userManager.FindByEmailAsync(model.Email ?? "");
- success = user is not null && await userManager.CheckPasswordAsync(user, model.Password ?? "");
- if (!success && user is not null && !user.IsDisabledTemporarily)
- await userManager.AccessFailedAsync(user);
+ success = user is not null &&
+ (await signInManager.CheckPasswordSignInAsync(user, model.Password ?? "", true)).Succeeded;
}
if (model.Method == "LoginCode" && model.LoginCode is not null)
@@ -196,7 +195,7 @@ public async Task<IActionResult> Login(LoginViewModel model, string returnUrl =
}
}
- if (user?.IsDisabledTemporarily is true)
+ if (user is not null && await userManager.IsLockedOutAsync(user))
return LockoutView(user);
var errorMessage = StringLocalizer["Invalid login attempt."].Value;
@@ -337,7 +336,7 @@ public async Task<IActionResult> LoginWithLNURLAuth(LoginWithLNURLAuthViewModel
{
return RedirectToAction("Login");
}
- if (user.IsDisabledTemporarily)
+ if (await userManager.IsLockedOutAsync(user))
return LockoutView(user);
var session = LoginSession.Load(HttpContext.Session);
@@ -400,7 +399,7 @@ public async Task<IActionResult> LoginWithFido2(LoginWithFido2ViewModel viewMode
{
return RedirectToAction("Login");
}
- if (user.IsDisabledTemporarily)
+ if (await userManager.IsLockedOutAsync(user))
return LockoutView(user);
var session = LoginSession.Load(HttpContext.Session);
@@ -457,7 +456,7 @@ public async Task<IActionResult> LoginWithAuthenticator(LoginWithAuthenticatorMo
{
return RedirectToAction("Login");
}
- if (user.IsDisabledTemporarily)
+ if (await userManager.IsLockedOutAsync(user))
return LockoutView(user);
var session = LoginSession.Load(HttpContext.Session);
### BTCPayServer/Controllers/UIServerController.Users.cs
@@ -56,6 +56,7 @@ public async Task<IActionResult> ListUsers(
.Include(user => user.UserRoles)
.Include(user => user.UserStores)
.ThenInclude(data => data.StoreData)
+ .Include(user => user.AccessRestrictions)
.Skip(model.Skip)
.Take(model.Count)
.ToListAsync())
@@ -76,7 +77,7 @@ public async Task<IActionResult> ListUsers(
Approved = u.RequiresApproval ? u.Approved : null,
Created = u.Created,
Roles = u.UserRoles.Select(role => role.RoleId),
- Disabled = u.IsDisabled,
+ Disabled = u.AccessRestrictions.Any(r => r.Type == UserAccessRestrictionConstants.Administrative),
Stores = u.UserStores.OrderBy(s => !s.StoreData.Archived).ToList()
};
})
### BTCPayServer/Plugins/Monetization/MonetizationHostedService.cs
@@ -29,9 +29,9 @@ public class MonetizationHostedService(
SubscriptionHostedService subsService,
Logs logger) : EventHostedServiceBase(eventAggregator, logger)
{
- public class MonetizationLockoutUpdated((string UserId, bool LockoutEnabled)[] updated)
+ public class MonetizationAccessUpdated((string UserId, bool Restricted)[] updated)
{
- public (string UserId, bool LockoutEnabled)[] Updated { get; } = updated;
+ public (string UserId, bool Restricted)[] Updated { get; } = updated;
}
protected override void SubscribeToEvents()
@@ -78,20 +78,20 @@ protected override async Task ProcessEvent(object evt, CancellationToken cancell
if (evt is SubscriptionEvent.SubscriberActivated or SubscriptionEvent.SubscriberDisabled)
{
- await UpdateUserLockout((SubscriptionEvent.SubscriberEvent)evt, userManager, evt is SubscriptionEvent.SubscriberActivated);
+ await UpdateUserAccessRestriction((SubscriptionEvent.SubscriberEvent)evt, userManager, evt is SubscriptionEvent.SubscriberActivated);
}
if (evt is SubscriptionEvent.PlanStarted ps && ps.PreviousPlan.Id != ps.Subscriber.Plan.Id)
{
await using var ctx = dbContextFactory.CreateContext();
var canAccess = await ctx.Plans.HasFeature(ps.Subscriber.PlanId, MonetizationFeatures.CanAccess);
- await UpdateUserLockout(ps, userManager, canAccess);
+ await UpdateUserAccessRestriction(ps, userManager, canAccess);
}
if (evt is SubscriptionEvent.PlanUpdated pu)
{
await using var ctx = dbContextFactory.CreateContext();
- await UpdateUserLockoutStatus(ctx, pu.Plan);
+ await UpdateUserAccessRestrictions(ctx, pu.Plan);
}
@@ -107,8 +107,8 @@ protected override async Task ProcessEvent(object evt, CancellationToken cancell
var userSub = await ctx.Subscribers.GetBySelector(byPassOfferingId, CustomerSelector.ByIdentity(SubscriberDataExtensions.IdentityType, changed.User.Id));
if (userSub is not null)
{
- await userService.SetDisabled(changed.User.Id, false, nameof(MonetizationHostedService));
- EventAggregator.Publish(new MonetizationLockoutUpdated([(changed.User.Id, false)]));
+ await userService.SetAccessRestriction(changed.User.Id, UserAccessRestrictionConstants.Monetization, false);
+ EventAggregator.Publish(new MonetizationAccessUpdated([(changed.User.Id, false)]));
}
}
else
@@ -117,13 +117,10 @@ protected override async Task ProcessEvent(object evt, CancellationToken cancell
var userSub = await ctx.Subscribers.GetBySelector(byPassOfferingId, CustomerSelector.ByIdentity(SubscriberDataExtensions.IdentityType, changed.User.Id));
if (userSub is not null)
{
- var shouldBeLocked = !userSub.IsActive || userSub.Phase == SubscriberData.PhaseTypes.Expired;
- if (shouldBeLocked)
- {
- await userService.SetDisabled(changed.User.Id, true, nameof(MonetizationHostedService));
- securityStampInvalidator.Invalidate(changed.User.Id);
- EventAggregator.Publish(new MonetizationLockoutUpdated([(changed.User.Id, true)]));
- }
+ var restricted = (!userSub.IsActive || userSub.Phase == SubscriberData.PhaseTypes.Expired) &&
+ !await userService.IsAdminUser(changed.User);
+ await userService.SetAccessRestriction(changed.User.Id, UserAccessRestrictionConstants.Monetization, restricted);
+ EventAggregator.Publish(new MonetizationAccessUpdated([(changed.User.Id, restricted)]));
}
else
{
@@ -199,15 +196,17 @@ DELETE FROM customers_identities ci
}
}
- private async Task UpdateUserLockout(SubscriptionEvent.SubscriberEvent evt, UserManager<ApplicationUser> userManager, bool activated)
+ private async Task UpdateUserAccessRestriction(SubscriptionEvent.SubscriberEvent evt, UserManager<ApplicationUser> userManager, bool activated)
{
var userId = evt.Subscriber.GetApplicationUserId();
var user = await userManager.FindByIdAsync(userId ?? "");
- if (user is not null &&
- !await userService.IsAdminUser(user) &&
- await userService.SetDisabled(user.Id, !activated, nameof(MonetizationHostedService)) is not UserService.SetDisabledResult.Error)
+ if (user is null)
+ return;
+
+ var restricted = !activated && !user.BypassMonetization && !await userService.IsAdminUser(user);
+ if (await userService.SetAccessRestriction(user.Id, UserAccessRestrictionConstants.Monetization, restricted) is not UserService.SetDisabledResult.Error)
{
- EventAggregator.Publish(new MonetizationLockoutUpdated([(user.Id, !activated)]));
+ EventAggregator.Publish(new MonetizationAccessUpdated([(user.Id, restricted)]));
}
}
@@ -357,53 +356,101 @@ FROM inserted_subs i
if (userIds.Length != 0)
{
await SubscriptionHostedService.UpdatePlanStats(ctx, plan.Id);
- await UpdateUserLockoutStatus(ctx, plan, userIds.Select(c => c.UserId).ToArray());
+ await UpdateUserAccessRestrictions(ctx, plan, userIds.Select(c => c.UserId).ToArray());
// We expect the caller to call NewSubscriberEvent.
}
return userIds;
}
- private async Task UpdateUserLockoutStatus(ApplicationDbContext ctx, PlanData plan, string[]? userIds = null)
+ private async Task UpdateUserAccessRestrictions(ApplicationDbContext ctx, PlanData plan, string[]? userIds = null)
{
if (userIds is null)
userIds = await GetUserIdsInPlan(ctx, plan);
if (userIds.Length == 0)
return;
var canAccess = await ctx.Plans.HasFeature(plan.Id, MonetizationFeatures.CanAccess);
var updated = (await ctx.Database.GetDbConnection()
- .QueryAsync<(string UserId, bool LockoutEnabled)>("""
- WITH
- subs AS (
- SELECT user_id AS user_id,
- NOT (ss.active AND @canAccess) AS lockout_enabled,
- CASE WHEN (ss.active AND @canAccess) THEN NULL ELSE 'infinity'::timestamptz END lockout_end
- FROM unnest(@userIds) AS user_id
- JOIN customers_identities ci ON ci.type = @applicationUserId AND ci.value = user_id
- JOIN subs_subscribers ss ON ss.customer_id = ci.customer_id
- JOIN "AspNetUsers" ON "AspNetUsers"."Id" = user_id
+ .QueryAsync<(string UserId, bool Restricted)>("""
+ WITH exempt_users AS (
+ SELECT "Id" AS user_id
+ FROM "AspNetUsers"
+ WHERE "BypassMonetization"
+ UNION
+ SELECT user_role."UserId"
+ FROM "AspNetUserRoles" user_role
+ JOIN "AspNetRoles" role ON role."Id" = user_role."RoleId"
+ WHERE role."Name" = @adminRole
+ ),
+ desired AS (
+ SELECT requested.user_id, NOT (ss.active AND @canAccess) AS restricted
+ FROM unnest(@userIds) AS requested(user_id)
+ JOIN customers_identities ci ON ci.type = @applicationUserId AND ci.value = requested.user_id
+ JOIN subs_subscribers ss ON ss.customer_id = ci.customer_id
+ JOIN "AspNetUsers" ON "AspNetUsers"."Id" = requested.user_id
+ LEFT JOIN exempt_users exempt ON exempt.user_id = requested.user_id
WHERE ss.plan_id = @planId
+ AND exempt.user_id IS NULL
+ ),
+ deleted AS (
+ DELETE FROM user_access_restrictions restriction
+ USING desired
+ WHERE restriction.user_id = desired.user_id
+ AND restriction.type = @restrictionType
+ AND NOT desired.restricted
+ RETURNING restriction.user_id, false AS restricted
+ ),
+ inserted AS (
+ INSERT INTO user_access_restrictions (user_id, type, created_at)
+ SELECT user_id, @restrictionType, NOW()
+ FROM desired
+ WHERE restricted
+ ON CONFLICT DO NOTHING
+ RETURNING user_id, true AS restricted
+ ),
+ exempt_deleted AS (
+ DELETE FROM user_access_restrictions restriction
+ USING exempt_users exempt
+ WHERE restriction.user_id = exempt.user_id
+ AND restriction.type = @restrictionType
+ RETURNING restriction.user_id, false AS restricted
+ ),
+ changed AS (
+ SELECT * FROM deleted
+ UNION ALL
+ SELECT * FROM inserted
+ UNION ALL
+ SELECT * FROM exempt_deleted
+ ),
+ stamps AS (
+ UPDATE "AspNetUsers" users
+ SET "SecurityStamp" = translate(encode(decode(md5(users."Id" || @salt), 'hex'), 'base64'), '/=+-', '')
+ FROM changed
+ WHERE users."Id" = changed.user_id AND changed.restricted
+ RETURNING users."Id"
)
- UPDATE "AspNetUsers"
- SET "LockoutEnabled" = subs.lockout_enabled,
- "LockoutEnd" = subs.lockout_end,
- "SecurityStamp" = translate(encode(decode(md5("Id" || @salt), 'hex'), 'base64'), '/=+-', '')
- FROM subs WHERE "AspNetUsers"."Id" = subs.user_id AND ("AspNetUsers"."LockoutEnabled" IS DISTINCT FROM subs.lockout_enabled OR "AspNetUsers"."LockoutEnd" IS DISTINCT FROM subs.lockout_end)
- RETURNING "Id", "LockoutEnabled";
+ SELECT user_id, restricted
+ FROM changed
""",
- new{
+ new
+ {
userIds,
planId = plan.Id,
- salt = RandomUtils.GetUInt256().ToString(),
applicationUserId = SubscriberDataExtensions.IdentityType,
- canAccess
+ canAccess,
+ adminRole = Roles.ServerAdmin,
+ restrictionType = UserAccessRestrictionConstants.Monetization,
+ salt = RandomUtils.GetUInt256().ToString()
})).ToArray();
- foreach (var update in updated)
- if (update.LockoutEnabled)
- securityStampInvalidator.Invalidate(update.UserId);
- await ctx.Users.UpdateStoreNoActiveUserForUsers(updated.Select(u => u.UserId).ToArray());
- EventAggregator.Publish(new MonetizationLockoutUpdated(updated));
+ foreach (var update in updated.Where(update => update.Restricted))
+ securityStampInvalidator.Invalidate(update.UserId);
+
+ if (updated.Length == 0)
+ return;
+
+ await ctx.Users.UpdateStoreNoActiveUserForUsers(updated.Select(update => update.UserId).ToArray());
+ EventAggregator.Publish(new MonetizationAccessUpdated(updated));
}
private static async Task<string[]> GetUserIdsInPlan(ApplicationDbContext ctx, PlanData plan)
### BTCPayServer/Plugins/Monetization/MonetizationLoginExtension.cs
@@ -15,7 +15,8 @@ public class MonetizationLoginExtension(
{
public override async Task Check(UserService.CanLoginContext context)
{
- if (context.User.BypassMonetization)
+ if (context.User.BypassMonetization ||
+ context.User.AccessRestrictions?.Exists(restriction => restriction.Type == UserAccessRestrictionConstants.Monetization) is not true)
return;
if (settings.Settings is { OfferingId: { } offeringId })
### BTCPayServer/Security/GreenField/APIKeyRepository.cs
@@ -71,7 +71,7 @@ public async Task<APIKeyData> GetKey(Selector selector, bool includeUser = false
var id = selector.GetId();
await using var context = applicationDbContextFactory.CreateContext();
var result = includeUser ?
- await context.ApiKeys.Include(data => data.User).SingleOrDefaultAsync(data => data.Id == id) :
+ await context.ApiKeys.Include(data => data.User).ThenInclude(u => u.AccessRestrictions).SingleOrDefaultAsync(data => data.Id == id) :
await context.ApiKeys.SingleOrDefaultAsync(data => data.Id == id);
if (result != null && selector is Selector.ByApiKey apiKey && apiKey.GetHash() != result.Hash)
result = null;
### BTCPayServer/Security/GreenField/BasicAuthenticationHandler.cs
@@ -59,6 +59,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
var user = await userManager.Users
.Include(applicationUser => applicationUser.Fido2Credentials)
+ .Include(applicationUser => applicationUser.AccessRestrictions)
.FirstOrDefaultAsync(applicationUser =>
applicationUser.NormalizedUserName == userManager.NormalizeName(username));
### BTCPayServer/Services/UserService.cs
@@ -9,6 +9,7 @@
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Storage.Services;
+using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Localization;
@@ -51,7 +52,7 @@ public UserService(
_logger = logger;
}
- public record ApplicationUserWithRoles(ApplicationUser User, string[] Roles);
+ public record ApplicationUserWithRoles(ApplicationUser User, string[] Roles, bool Disabled);
public async Task<List<ApplicationUserWithRoles>> GetUsersWithRoles()
{
await using var context = _applicationDbContextFactory.CreateContext();
@@ -60,10 +61,11 @@ public async Task<List<ApplicationUserWithRoles>> GetUsersWithRoles()
{
User = p,
Roles = p.UserRoles.Join(context.Roles, userRole => userRole.RoleId,
- role => role.Id, (userRole, role) => role.Name).ToArray()
+ role => role.Id, (userRole, role) => role.Name).ToArray(),
+ Disabled = p.AccessRestrictions.Any(r => r.Type == UserAccessRestrictionConstants.Administrative)
})
.ToListAsync();
- return res.Select(p => new ApplicationUserWithRoles(p.User, (p.Roles ?? [])!)).ToList();
+ return res.Select(p => new ApplicationUserWithRoles(p.User, (p.Roles ?? [])!, p.Disabled)).ToList();
}
public static async Task<T> ForAPI<T>(
@@ -72,7 +74,8 @@ public static async Task<T> ForAPI<T>(
CallbackGenerator callbackGenerator,
UriResolver uriResolver,
HttpRequest request,
- bool includeInvitationUrl) where T : ApplicationUserData, new()
+ bool includeInvitationUrl,
+ bool disabled) where T : ApplicationUserData, new()
{
var blob = data.GetBlob() ?? new UserBlob();
return new T
@@ -86,7 +89,7 @@ public static async Task<T> ForAPI<T>(
Created = data.Created,
Name = blob.Name,
Roles = roles,
- Disabled = data.IsDisabled,
+ Disabled = disabled,
StoreQuota = blob.StoreQuota,
AllowGreenfieldBasicAuth = blob.AllowGreenfieldBasicAuth,
ImageUrl = string.IsNullOrEmpty(blob.ImageUrl)
@@ -124,7 +127,6 @@ public class CanLoginContext(
IViewLocalizer? viewLocalizer = null,
RequestBaseUrl? baseUrl = null)
{
- public CanLoginContext Clone(ApplicationUser? user) => new(user, stringLocalizer, viewLocalizer, BaseUrl);
public IStringLocalizer StringLocalizer { get; } = stringLocalizer ?? NullStringLocalizer.Instance;
public IViewLocalizer ViewLocalizer { get; } = viewLocalizer ?? NullViewLocalizer.Instance;
public RequestBaseUrl? BaseUrl { get; } = baseUrl;
@@ -145,6 +147,14 @@ public async Task<bool> CanLogin(CanLoginContext context)
return false;
}
+ if (context.User.AccessRestrictions is null)
+ {
+ await using var dbContext = _applicationDbContextFactory.CreateContext();
+ context.User.AccessRestrictions = await dbContext.UserAccessRestrictions
+ .Where(restriction => restriction.ApplicationUserId == context.User.Id)
+ .ToListAsync();
+ }
+
foreach (var loginExtension in _loginExtensions)
{
await loginExtension.Check(context);
@@ -163,8 +173,17 @@ public override Task Check(CanLoginContext context)
if (context.User is { Approved: false, RequiresApproval: true })
context.Failures.Add(new(context.StringLocalizer["Your user account requires approval by an admin before you can log in."]));
- if (context.User is { IsDisabled: true })
- context.Failures.Add(new(context.StringLocalizer["Your user account is currently disabled."]));
+
+ foreach (var restriction in context.User.AccessRestrictions)
+ {
+ var failure = restriction.Type switch
+ {
+ UserAccessRestrictionConstants.Administrative => context.StringLocalizer["Your user account is currently disabled."],
+ UserAccessRestrictionConstants.Monetization => context.StringLocalizer["Your subscription does not currently allow access."],
+ _ => context.StringLocalizer["Your user account is currently restricted."]
+ };
+ context.Failures.Add(new(failure));
+ }
return Task.CompletedTask;
}
}
@@ -203,39 +222,79 @@ public async Task<bool> SetUserApproval(string userId, bool approved, string log
public record SetDisabledResult
{
public record Unchanged : SetDisabledResult;
- public record Success : SetDisabledResult;
+ public record Success : SetDisabledResult
+ {
+ internal ApplicationUser? User { get; init; }
+ }
public record Error(IdentityError[] Errors) : SetDisabledResult;
}
+ public async Task<bool> IsRestricted(string userId, string type)
+ {
+ await using var ctx = _applicationDbContextFactory.CreateContext();
+ return await ctx.UserAccessRestrictions.AnyAsync(r =>
+ r.ApplicationUserId == userId &&
+ r.Type == type);
+ }
+
public Task<SetDisabledResult> SetDisabled(string userId, bool disabled)
=> SetDisabled(userId, disabled, null);
public async Task<SetDisabledResult> SetDisabled(string userId, bool disabled, string? source)
+ {
+ var result = await SetAccessRestriction(userId, UserAccessRestrictionConstants.Administrative, disabled);
+ if (result is SetDisabledResult.Success { User: { } user })
+ _eventAggregator.Publish(new UserEvent.DisabledChanged(user, disabled, source));
+ return result;
+ }
+
+ public async Task<SetDisabledResult> SetAccessRestriction(
+ string userId,
+ string type,
+ bool restricted)
{
using var scope = _serviceProvider.CreateScope();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var user = await userManager.FindByIdAsync(userId);
- if (user is null || disabled == user.IsDisabled)
+ if (user is null)
return new SetDisabledResult.Unchanged();
- if (!user.LockoutEnabled)
- await userManager.SetLockoutEnabledAsync(user, true);
- var lockedOutDeadline = disabled ? DateTimeOffset.MaxValue : (DateTimeOffset?)null;
- var res = await userManager.SetLockoutEndDateAsync(user, lockedOutDeadline);
+ await using var ctx = _applicationDbContextFactory.CreateContext();
+ var existing = await ctx.UserAccessRestrictions.FindAsync(userId, type);
+ if (restricted == (existing is not null))
+ return new SetDisabledResult.Unchanged();
- if (res.Succeeded)
+ try
{
- if (disabled)
+ if (restricted)
+ {
+ ctx.UserAccessRestrictions.Add(new UserAccessRestriction
+ {
+ ApplicationUserId = userId,
+ Type = type,
+ CreatedAt = DateTimeOffset.UtcNow
+ });
+ }
+ else
+ {
+ ctx.UserAccessRestrictions.Remove(existing!);
+ }
+
+ await ctx.SaveChangesAsync();
+
+ if (restricted)
{
await userManager.UpdateSecurityStampAsync(user);
// Force immediate cookie revalidation instead of waiting for the stamp validation interval.
_securityStampInvalidator.Invalidate(user.Id);
}
- await using var ctx = _applicationDbContextFactory.CreateContext();
await ctx.Users.UpdateStoreNoActiveUserForUsers([userId]);
- _eventAggregator.Publish(new UserEvent.DisabledChanged(user, disabled, source));
+ return new SetDisabledResult.Success { User = user };
+ }
+ catch (DbUpdateException ex)
+ {
+ _logger.LogError(ex, "Failed to update {RestrictionType} access restriction for user {Email}", type, user.Email);
+ return new SetDisabledResult.Error([new IdentityError { Description = ex.Message }]);
}
-
- return res.Succeeded ? new SetDisabledResult.Success() : new SetDisabledResult.Error(res.Errors.ToArray());
}
[Obsolete("Use SetDisabled instead")]
@@ -306,23 +365,24 @@ public async Task DeleteUserAndAssociatedData(ApplicationUser user)
public async Task<bool> IsUserTheOnlyOneAdmin(CanLoginContext canLoginContext)
{
- using var scope = _serviceProvider.CreateScope();
- var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
- var roles = await userManager.GetRolesAsync(canLoginContext.User);
- if (!Roles.HasServerAdmin(roles))
+ await using var ctx = _applicationDbContextFactory.CreateContext();
+ return await ctx.Database.GetDbConnection().QuerySingleAsync<bool>("""
+ SELECT COUNT(*) = 1
+ AND COALESCE(BOOL_OR(users."Id" = @userId), false)
+ FROM "AspNetUsers" users
+ JOIN "AspNetUserRoles" user_roles ON user_roles."UserId" = users."Id"
+ JOIN "AspNetRoles" roles ON roles."Id" = user_roles."RoleId"
+ LEFT JOIN user_access_restrictions restrictions ON restrictions.user_id = users."Id"
+ WHERE roles."Name" = @adminRole
+ AND users."PasswordHash" IS NOT NULL
+ AND (users."EmailConfirmed" OR NOT users."RequiresEmailConfirmation")
+ AND (users."Approved" OR NOT users."RequiresApproval")
+ AND restrictions.user_id IS NULL;
+ """, new
{
- return false;
- }
- var adminUsers = await userManager.GetUsersInRoleAsync(Roles.ServerAdmin);
- var enabledAdminUsers = new List<string>();
- foreach (var admin in adminUsers)
- {
- var loginContext = canLoginContext.Clone(admin);
- if (await CanLogin(loginContext))
- enabledAdminUsers.Add(admin.Id);
- }
-
- return enabledAdminUsers.Count == 1 && enabledAdminUsers.Contains(canLoginContext.User.Id);
+ userId = canLoginContext.User.Id,
+ adminRole = Roles.ServerAdmin
+ });
}
}
}
### BTCPayServer/Views/UIAccount/Lockout.cshtml
@@ -1,14 +1,7 @@
@model ApplicationUser
@{
- ViewData.SetTitle("Account disabled");
+ ViewData.SetTitle("Account locked");
Layout = "_LayoutSignedOut";
}
-@if (Model.IsDisabledTemporarily)
-{
- <p class="mb-0"><span text-translate="true">This account has been locked out. Please try again</span> @Model.LockoutEnd!.Value.ToBrowserDate(ViewsRazor.DateDisplayFormat.Relative).</p>
-}
-else
-{
- <p class="mb-0" text-translate="true">Your account has been disabled. Please contact server administrator.</p>
-}
+<p class="mb-0"><span text-translate="true">This account has been locked out. Please try again</span> @Model.LockoutEnd!.Value.ToBrowserDate(ViewsRazor.DateDisplayFormat.Relative).</p>
### docs/maintainers/coding-conventions.md
@@ -23,6 +23,29 @@
diagnostic purposes unless there is a specific reason to believe they contain
sensitive data.
+## PostgreSQL Schema Naming
+
+Use PostgreSQL-style physical names for new tables while keeping normal .NET
+naming in the entity classes:
+
+- Use lowercase, plural `snake_case` table names, such as `email_rules`.
+- Use lowercase `snake_case` column names, including foreign keys and timestamps,
+ such as `store_id` and `created_at`.
+- Map CLR names explicitly with `[Table]`, `[Column]`, and related attributes
+ whenever possible. Use fluent configuration only for mappings that attributes
+ cannot express. Do not rely on EF's default PascalCase names for new schema
+ objects.
+- Use lowercase PostgreSQL type names such as `text`, `jsonb`, `text[]`, and
+ `timestamptz` when specifying a database type explicitly.
+- Let EF derive primary key, foreign key, and index names from the physical
+ table and column names unless a stable custom name is required.
+- Use unquoted lowercase identifiers in raw SQL for new schema objects. Quote
+ existing mixed-case identifiers when referencing legacy tables or columns.
+
+These rules apply to new schema objects. Do not rename established tables or
+columns solely for consistency; preserve compatibility with existing databases
+and integrations.
+
## Pull Requests
Write descriptions for users, merchants, operators, support contributors,Why this scored 61/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.