diff --git a/SS14.Auth.Shared/Config/PatreonConfiguration.cs b/SS14.Auth.Shared/Config/PatreonConfiguration.cs index f3e5ccbf..25ef3c35 100644 --- a/SS14.Auth.Shared/Config/PatreonConfiguration.cs +++ b/SS14.Auth.Shared/Config/PatreonConfiguration.cs @@ -1,13 +1,13 @@ -using System.Collections.Generic; - -namespace SS14.Auth.Shared.Config; +namespace SS14.Auth.Shared.Config; public sealed class PatreonConfiguration { public string ClientId { get; set; } public string ClientSecret { get; set; } - public Dictionary TierMap { get; set; } - public Dictionary TierNames { get; set; } - public string WebhookSecret { get; set; } public bool LogWebhooks { get; set; } = true; -} \ No newline at end of file + + /// + /// Public base URL of the auth API, used to tell Patreon where to send webhook messages + /// + public string WebhookBaseUrl { get; set; } +} diff --git a/SS14.Auth.Shared/Data/ApplicationDbContext.cs b/SS14.Auth.Shared/Data/ApplicationDbContext.cs index 1ffe0298..23992664 100644 --- a/SS14.Auth.Shared/Data/ApplicationDbContext.cs +++ b/SS14.Auth.Shared/Data/ApplicationDbContext.cs @@ -61,6 +61,47 @@ protected override void OnModelCreating(ModelBuilder builder) .HasIndex(p => p.SpaceUserId) .IsUnique(); + builder.Entity() + .HasIndex(c => c.Key) + .IsUnique(); + + builder.Entity() + .HasIndex(c => c.PatreonCampaignId) + .IsUnique(); + + builder.Entity() + .HasOne() + .WithMany() + .HasForeignKey(c => c.OwnerUserId) + .OnDelete(DeleteBehavior.SetNull); + + // At most one campaign per owner, campaigns without an owner don't count. + builder.Entity() + .HasIndex(c => c.OwnerUserId) + .IsUnique(); + + builder.Entity() + .HasIndex(c => c.ServerTokenHash) + .IsUnique(); + + builder.Entity() + .HasIndex(c => c.IsFirstParty) + .IsUnique() + .HasFilter("\"IsFirstParty\""); + + builder.Entity() + .HasIndex(m => new { m.CampaignId, m.PatreonUserId }) + .IsUnique(); + + builder.Entity() + .HasIndex(m => m.PatreonUserId); + + builder.Entity() + .HasOne() + .WithMany() + .HasForeignKey(l => l.CampaignId) + .OnDelete(DeleteBehavior.SetNull); + builder.Entity() .HasIndex(p => new { p.ClientId }) .IsUnique(); @@ -124,6 +165,8 @@ protected override void OnModelCreating(ModelBuilder builder) public DbSet WhitelistEmails { get; set; } public DbSet Patrons { get; set; } public DbSet PatreonWebhookLogs { get; set; } + public DbSet PatreonCampaigns { get; set; } + public DbSet PatreonMemberships { get; set; } public DbSet UserOAuthClients { get; set; } public DbSet PastAccountNames { get; set; } public DbSet AccountLogs { get; set; } diff --git a/SS14.Auth.Shared/Data/Migrations/20261016222412_PatreonCampaigns.Designer.cs b/SS14.Auth.Shared/Data/Migrations/20261016222412_PatreonCampaigns.Designer.cs new file mode 100644 index 00000000..f531b7af --- /dev/null +++ b/SS14.Auth.Shared/Data/Migrations/20261016222412_PatreonCampaigns.Designer.cs @@ -0,0 +1,1945 @@ +// +using System; +using System.Collections.Generic; +using System.Net; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SS14.Auth.Shared.Data; + +#nullable disable + +namespace SS14.Auth.Shared.Data.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261016222412_PatreonCampaigns")] + partial class PatreonCampaigns + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AllowedAccessTokenSigningAlgorithms") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DisplayName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastAccessed") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NonEditable") + .HasColumnType("boolean"); + + b.Property("ShowInDiscoveryDocument") + .HasColumnType("boolean"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiResources", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiResourceClaims", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiResourceProperties", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiResourceScopes", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceSecret", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ApiResourceId") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Id"); + + b.HasIndex("ApiResourceId"); + + b.ToTable("ApiResourceSecrets", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DisplayName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Emphasize") + .HasColumnType("boolean"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ShowInDiscoveryDocument") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiScopes", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ScopeId") + .HasColumnType("integer"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ScopeId"); + + b.ToTable("ApiScopeClaims", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("ScopeId") + .HasColumnType("integer"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("ScopeId"); + + b.ToTable("ApiScopeProperties", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AbsoluteRefreshTokenLifetime") + .HasColumnType("integer"); + + b.Property("AccessTokenLifetime") + .HasColumnType("integer"); + + b.Property("AccessTokenType") + .HasColumnType("integer"); + + b.Property("AllowAccessTokensViaBrowser") + .HasColumnType("boolean"); + + b.Property("AllowOfflineAccess") + .HasColumnType("boolean"); + + b.Property("AllowPlainTextPkce") + .HasColumnType("boolean"); + + b.Property("AllowRememberConsent") + .HasColumnType("boolean"); + + b.Property("AllowedIdentityTokenSigningAlgorithms") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("AlwaysIncludeUserClaimsInIdToken") + .HasColumnType("boolean"); + + b.Property("AlwaysSendClientClaims") + .HasColumnType("boolean"); + + b.Property("AuthorizationCodeLifetime") + .HasColumnType("integer"); + + b.Property("BackChannelLogoutSessionRequired") + .HasColumnType("boolean"); + + b.Property("BackChannelLogoutUri") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ClientClaimsPrefix") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ClientId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ClientName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ClientUri") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ConsentLifetime") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DeviceCodeLifetime") + .HasColumnType("integer"); + + b.Property("EnableLocalLogin") + .HasColumnType("boolean"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("FrontChannelLogoutSessionRequired") + .HasColumnType("boolean"); + + b.Property("FrontChannelLogoutUri") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("IdentityTokenLifetime") + .HasColumnType("integer"); + + b.Property("IncludeJwtId") + .HasColumnType("boolean"); + + b.Property("LastAccessed") + .HasColumnType("timestamp with time zone"); + + b.Property("LogoUri") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("NonEditable") + .HasColumnType("boolean"); + + b.Property("PairWiseSubjectSalt") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ProtocolType") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RefreshTokenExpiration") + .HasColumnType("integer"); + + b.Property("RefreshTokenUsage") + .HasColumnType("integer"); + + b.Property("RequireClientSecret") + .HasColumnType("boolean"); + + b.Property("RequireConsent") + .HasColumnType("boolean"); + + b.Property("RequirePkce") + .HasColumnType("boolean"); + + b.Property("RequireRequestObject") + .HasColumnType("boolean"); + + b.Property("SlidingRefreshTokenLifetime") + .HasColumnType("integer"); + + b.Property("UpdateAccessTokenClaimsOnRefresh") + .HasColumnType("boolean"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.Property("UserCodeType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UserSsoLifetime") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ClientId") + .IsUnique(); + + b.ToTable("Clients", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientClaims", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Origin") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientCorsOrigins", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("GrantType") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientGrantTypes", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientIdPRestrictions", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("PostLogoutRedirectUri") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientPostLogoutRedirectUris", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientProperties", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("RedirectUri") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientRedirectUris", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientScopes", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ClientSecrets", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => + { + b.Property("UserCode") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ClientId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreationTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Data") + .IsRequired() + .HasMaxLength(50000) + .HasColumnType("character varying(50000)"); + + b.Property("Description") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("DeviceCode") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Expiration") + .IsRequired() + .HasColumnType("timestamp with time zone"); + + b.Property("SessionId") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SubjectId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("UserCode"); + + b.HasIndex("DeviceCode") + .IsUnique(); + + b.HasIndex("Expiration"); + + b.ToTable("DeviceCodes", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("DisplayName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Emphasize") + .HasColumnType("boolean"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NonEditable") + .HasColumnType("boolean"); + + b.Property("Required") + .HasColumnType("boolean"); + + b.Property("ShowInDiscoveryDocument") + .HasColumnType("boolean"); + + b.Property("Updated") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("IdentityResources", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdentityResourceId") + .HasColumnType("integer"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityResourceClaims", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("IdentityResourceId") + .HasColumnType("integer"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("character varying(250)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("IdentityResourceId"); + + b.ToTable("IdentityResourceProperties", "IS4"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => + { + b.Property("Key") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ClientId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("ConsumedTime") + .HasColumnType("timestamp with time zone"); + + b.Property("CreationTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Data") + .IsRequired() + .HasMaxLength(50000) + .HasColumnType("character varying(50000)"); + + b.Property("Description") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("SessionId") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("SubjectId") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Key"); + + b.HasIndex("Expiration"); + + b.HasIndex("SubjectId", "ClientId", "Type"); + + b.HasIndex("SubjectId", "SessionId", "Type"); + + b.ToTable("PersistedGrants", "IS4"); + }); + + 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.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") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (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") + .HasColumnType("uuid"); + + 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") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + 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("SS14.Auth.Shared.Data.AccountLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Actor") + .HasColumnType("uuid"); + + b.Property("ActorAddress") + .HasColumnType("inet"); + + b.Property("Data") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.Property("Time") + .HasColumnType("timestamp with time zone"); + + b.Property("Type") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SpaceUserId"); + + b.ToTable("AccountLogs"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.AuthHash", b => + { + b.Property("AuthHashId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("AuthHashId")); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("Hash") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("HwidId") + .HasColumnType("bigint"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.HasKey("AuthHashId"); + + b.HasIndex("HwidId"); + + b.HasIndex("SpaceUserId"); + + b.HasIndex("Hash", "SpaceUserId") + .IsUnique(); + + b.ToTable("AuthHashes"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.BurnerEmail", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Domain") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Domain") + .IsUnique(); + + b.ToTable("BurnerEmails"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.Hwid", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientData") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("TypeCode") + .HasColumnType("integer"); + + b.Property("Value") + .IsRequired() + .HasColumnType("bytea"); + + b.HasKey("Id"); + + b.HasIndex("ClientData") + .IsUnique(); + + b.ToTable("Hwids"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.HwidUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FirstSeen") + .HasColumnType("timestamp with time zone"); + + b.Property("HwidId") + .HasColumnType("bigint"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("SpaceUserId"); + + b.HasIndex("HwidId", "SpaceUserId") + .IsUnique(); + + b.ToTable("HwidUsers"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.LoginSession", b => + { + b.Property("LoginSessionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("LoginSessionId")); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.Property("Token") + .IsRequired() + .HasColumnType("bytea"); + + b.HasKey("LoginSessionId"); + + b.HasIndex("SpaceUserId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("ActiveSessions"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PastAccountName", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChangeTime") + .HasColumnType("timestamp with time zone"); + + b.Property("PastName") + .IsRequired() + .HasColumnType("text"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("SpaceUserId"); + + b.ToTable("PastAccountNames"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonCampaign", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccessToken") + .HasColumnType("text"); + + b.Property("DisabledTierIds") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsFirstParty") + .HasColumnType("boolean"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastFullSyncAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastWebhookAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerUserId") + .HasColumnType("uuid"); + + b.Property("PatreonCampaignId") + .IsRequired() + .HasColumnType("text"); + + b.Property("RefreshToken") + .HasColumnType("text"); + + b.Property("ServerTokenHash") + .HasColumnType("text"); + + b.Property>("TierMap") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property>("TierNames") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("WebhookSecret") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("IsFirstParty") + .IsUnique() + .HasFilter("\"IsFirstParty\""); + + b.HasIndex("Key") + .IsUnique(); + + b.HasIndex("OwnerUserId") + .IsUnique(); + + b.HasIndex("PatreonCampaignId") + .IsUnique(); + + b.HasIndex("ServerTokenHash") + .IsUnique(); + + b.ToTable("PatreonCampaigns"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonMembership", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CampaignId") + .HasColumnType("integer"); + + b.Property("CurrentTier") + .HasColumnType("text"); + + b.Property("EntitledTierIds") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("Hidden") + .HasColumnType("boolean"); + + b.Property("PatreonMemberId") + .IsRequired() + .HasColumnType("text"); + + b.Property("PatreonUserId") + .IsRequired() + .HasColumnType("text"); + + b.Property("PatronStatus") + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("PatreonUserId"); + + b.HasIndex("CampaignId", "PatreonUserId") + .IsUnique(); + + b.ToTable("PatreonMemberships"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonWebhookLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CampaignId") + .HasColumnType("integer"); + + b.Property("Content") + .HasColumnType("jsonb"); + + b.Property("Time") + .HasColumnType("timestamp with time zone"); + + b.Property("Trigger") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CampaignId"); + + b.ToTable("PatreonWebhookLogs"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.Patron", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("PatreonId") + .IsRequired() + .HasColumnType("text"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PatreonId") + .IsUnique(); + + b.HasIndex("SpaceUserId") + .IsUnique(); + + b.ToTable("Patrons"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.SpaceRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + 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("SS14.Auth.Shared.Data.SpaceUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdminLocked") + .HasColumnType("boolean"); + + b.Property("AdminNotes") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedTime") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LastUsernameChange") + .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("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("SS14.Auth.Shared.Data.UserOAuthClient", b => + { + b.Property("UserOAuthClientId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("UserOAuthClientId")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("SpaceUserId") + .HasColumnType("uuid"); + + b.HasKey("UserOAuthClientId"); + + b.HasIndex("ClientId") + .IsUnique(); + + b.HasIndex("SpaceUserId"); + + b.ToTable("UserOAuthClients"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.WhitelistEmail", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Domain") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Domain") + .IsUnique(); + + b.ToTable("WhitelistEmails"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("UserClaims") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Properties") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceScope", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Scopes") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceSecret", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") + .WithMany("Secrets") + .HasForeignKey("ApiResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ApiResource"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "Scope") + .WithMany("UserClaims") + .HasForeignKey("ScopeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Scope"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "Scope") + .WithMany("Properties") + .HasForeignKey("ScopeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Scope"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("Claims") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedCorsOrigins") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedGrantTypes") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("IdentityProviderRestrictions") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("PostLogoutRedirectUris") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("Properties") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("RedirectUris") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("AllowedScopes") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany("ClientSecrets") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceClaim", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("UserClaims") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("IdentityResource"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") + .WithMany("Properties") + .HasForeignKey("IdentityResourceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("IdentityResource"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.AccountLog", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithMany("AccountLogs") + .HasForeignKey("SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.AuthHash", b => + { + b.HasOne("SS14.Auth.Shared.Data.Hwid", "Hwid") + .WithMany() + .HasForeignKey("HwidId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithMany("AuthHashes") + .HasForeignKey("SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Hwid"); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.HwidUser", b => + { + b.HasOne("SS14.Auth.Shared.Data.Hwid", "Hwid") + .WithMany("Users") + .HasForeignKey("HwidId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithMany() + .HasForeignKey("SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Hwid"); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.LoginSession", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithMany("LoginSessions") + .HasForeignKey("SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PastAccountName", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithMany("PastAccountNames") + .HasForeignKey("SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonCampaign", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonMembership", b => + { + b.HasOne("SS14.Auth.Shared.Data.PatreonCampaign", "Campaign") + .WithMany("Memberships") + .HasForeignKey("CampaignId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Campaign"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonWebhookLog", b => + { + b.HasOne("SS14.Auth.Shared.Data.PatreonCampaign", null) + .WithMany() + .HasForeignKey("CampaignId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.Patron", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithOne("Patron") + .HasForeignKey("SS14.Auth.Shared.Data.Patron", "SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.UserOAuthClient", b => + { + b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") + .WithMany() + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") + .WithMany() + .HasForeignKey("SpaceUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("SpaceUser"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => + { + b.Navigation("Properties"); + + b.Navigation("Scopes"); + + b.Navigation("Secrets"); + + b.Navigation("UserClaims"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => + { + b.Navigation("Properties"); + + b.Navigation("UserClaims"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => + { + b.Navigation("AllowedCorsOrigins"); + + b.Navigation("AllowedGrantTypes"); + + b.Navigation("AllowedScopes"); + + b.Navigation("Claims"); + + b.Navigation("ClientSecrets"); + + b.Navigation("IdentityProviderRestrictions"); + + b.Navigation("PostLogoutRedirectUris"); + + b.Navigation("Properties"); + + b.Navigation("RedirectUris"); + }); + + modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => + { + b.Navigation("Properties"); + + b.Navigation("UserClaims"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.Hwid", b => + { + b.Navigation("Users"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonCampaign", b => + { + b.Navigation("Memberships"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.SpaceUser", b => + { + b.Navigation("AccountLogs"); + + b.Navigation("AuthHashes"); + + b.Navigation("LoginSessions"); + + b.Navigation("PastAccountNames"); + + b.Navigation("Patron"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SS14.Auth.Shared/Data/Migrations/20261016222412_PatreonCampaigns.cs b/SS14.Auth.Shared/Data/Migrations/20261016222412_PatreonCampaigns.cs new file mode 100644 index 00000000..e304a197 --- /dev/null +++ b/SS14.Auth.Shared/Data/Migrations/20261016222412_PatreonCampaigns.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace SS14.Auth.Shared.Data.Migrations +{ + public partial class PatreonCampaigns : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + // Existing patrons have to relink + migrationBuilder.Sql("DELETE FROM \"Patrons\";"); + + migrationBuilder.DropColumn( + name: "CurrentTier", + table: "Patrons"); + + migrationBuilder.AddColumn( + name: "CampaignId", + table: "PatreonWebhookLogs", + type: "integer", + nullable: true); + + migrationBuilder.CreateTable( + name: "PatreonCampaigns", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Key = table.Column(type: "text", nullable: false), + PatreonCampaignId = table.Column(type: "text", nullable: false), + Name = table.Column(type: "text", nullable: false), + TierMap = table.Column>(type: "jsonb", nullable: false), + TierNames = table.Column>(type: "jsonb", nullable: false), + DisabledTierIds = table.Column(type: "text[]", nullable: false), + WebhookSecret = table.Column(type: "text", nullable: true), + AccessToken = table.Column(type: "text", nullable: true), + RefreshToken = table.Column(type: "text", nullable: true), + TokenExpiresAt = table.Column(type: "timestamp with time zone", nullable: true), + ServerTokenHash = table.Column(type: "text", nullable: true), + IsFirstParty = table.Column(type: "boolean", nullable: false), + OwnerUserId = table.Column(type: "uuid", nullable: true), + Enabled = table.Column(type: "boolean", nullable: false), + LastFullSyncAt = table.Column(type: "timestamp with time zone", nullable: true), + LastWebhookAt = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PatreonCampaigns", x => x.Id); + table.ForeignKey( + name: "FK_PatreonCampaigns_AspNetUsers_OwnerUserId", + column: x => x.OwnerUserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + }); + + migrationBuilder.CreateTable( + name: "PatreonMemberships", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + CampaignId = table.Column(type: "integer", nullable: false), + PatreonUserId = table.Column(type: "text", nullable: false), + PatreonMemberId = table.Column(type: "text", nullable: false), + PatronStatus = table.Column(type: "text", nullable: true), + EntitledTierIds = table.Column(type: "text[]", nullable: false), + CurrentTier = table.Column(type: "text", nullable: true), + UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false), + Hidden = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PatreonMemberships", x => x.Id); + table.ForeignKey( + name: "FK_PatreonMemberships_PatreonCampaigns_CampaignId", + column: x => x.CampaignId, + principalTable: "PatreonCampaigns", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_PatreonWebhookLogs_CampaignId", + table: "PatreonWebhookLogs", + column: "CampaignId"); + + migrationBuilder.CreateIndex( + name: "IX_PatreonCampaigns_IsFirstParty", + table: "PatreonCampaigns", + column: "IsFirstParty", + unique: true, + filter: "\"IsFirstParty\""); + + migrationBuilder.CreateIndex( + name: "IX_PatreonCampaigns_Key", + table: "PatreonCampaigns", + column: "Key", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PatreonCampaigns_OwnerUserId", + table: "PatreonCampaigns", + column: "OwnerUserId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PatreonCampaigns_PatreonCampaignId", + table: "PatreonCampaigns", + column: "PatreonCampaignId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PatreonCampaigns_ServerTokenHash", + table: "PatreonCampaigns", + column: "ServerTokenHash", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PatreonMemberships_CampaignId_PatreonUserId", + table: "PatreonMemberships", + columns: new[] { "CampaignId", "PatreonUserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PatreonMemberships_PatreonUserId", + table: "PatreonMemberships", + column: "PatreonUserId"); + + migrationBuilder.AddForeignKey( + name: "FK_PatreonWebhookLogs_PatreonCampaigns_CampaignId", + table: "PatreonWebhookLogs", + column: "CampaignId", + principalTable: "PatreonCampaigns", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_PatreonWebhookLogs_PatreonCampaigns_CampaignId", + table: "PatreonWebhookLogs"); + + migrationBuilder.DropTable( + name: "PatreonMemberships"); + + migrationBuilder.DropTable( + name: "PatreonCampaigns"); + + migrationBuilder.DropIndex( + name: "IX_PatreonWebhookLogs_CampaignId", + table: "PatreonWebhookLogs"); + + migrationBuilder.DropColumn( + name: "CampaignId", + table: "PatreonWebhookLogs"); + + migrationBuilder.AddColumn( + name: "CurrentTier", + table: "Patrons", + type: "text", + nullable: true); + } + } +} diff --git a/SS14.Auth.Shared/Data/Migrations/ApplicationDbContextModelSnapshot.cs b/SS14.Auth.Shared/Data/Migrations/ApplicationDbContextModelSnapshot.cs index 811b97a7..ac5246c4 100644 --- a/SS14.Auth.Shared/Data/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/SS14.Auth.Shared/Data/Migrations/ApplicationDbContextModelSnapshot.cs @@ -1,5 +1,6 @@ // using System; +using System.Collections.Generic; using System.Net; using System.Text.Json; using Microsoft.EntityFrameworkCore; @@ -1207,6 +1208,134 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("PastAccountNames"); }); + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonCampaign", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AccessToken") + .HasColumnType("text"); + + b.Property("DisabledTierIds") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsFirstParty") + .HasColumnType("boolean"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastFullSyncAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastWebhookAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerUserId") + .HasColumnType("uuid"); + + b.Property("PatreonCampaignId") + .IsRequired() + .HasColumnType("text"); + + b.Property("RefreshToken") + .HasColumnType("text"); + + b.Property("ServerTokenHash") + .HasColumnType("text"); + + b.Property>("TierMap") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property>("TierNames") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("WebhookSecret") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("IsFirstParty") + .IsUnique() + .HasFilter("\"IsFirstParty\""); + + b.HasIndex("Key") + .IsUnique(); + + b.HasIndex("OwnerUserId") + .IsUnique(); + + b.HasIndex("PatreonCampaignId") + .IsUnique(); + + b.HasIndex("ServerTokenHash") + .IsUnique(); + + b.ToTable("PatreonCampaigns"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonMembership", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CampaignId") + .HasColumnType("integer"); + + b.Property("CurrentTier") + .HasColumnType("text"); + + b.Property("EntitledTierIds") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("Hidden") + .HasColumnType("boolean"); + + b.Property("PatreonMemberId") + .IsRequired() + .HasColumnType("text"); + + b.Property("PatreonUserId") + .IsRequired() + .HasColumnType("text"); + + b.Property("PatronStatus") + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("PatreonUserId"); + + b.HasIndex("CampaignId", "PatreonUserId") + .IsUnique(); + + b.ToTable("PatreonMemberships"); + }); + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonWebhookLog", b => { b.Property("Id") @@ -1215,6 +1344,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + b.Property("CampaignId") + .HasColumnType("integer"); + b.Property("Content") .HasColumnType("jsonb"); @@ -1226,6 +1358,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); + b.HasIndex("CampaignId"); + b.ToTable("PatreonWebhookLogs"); }); @@ -1237,9 +1371,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - b.Property("CurrentTier") - .HasColumnType("text"); - b.Property("PatreonId") .IsRequired() .HasColumnType("text"); @@ -1699,6 +1830,33 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("SpaceUser"); }); + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonCampaign", b => + { + b.HasOne("SS14.Auth.Shared.Data.SpaceUser", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonMembership", b => + { + b.HasOne("SS14.Auth.Shared.Data.PatreonCampaign", "Campaign") + .WithMany("Memberships") + .HasForeignKey("CampaignId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Campaign"); + }); + + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonWebhookLog", b => + { + b.HasOne("SS14.Auth.Shared.Data.PatreonCampaign", null) + .WithMany() + .HasForeignKey("CampaignId") + .OnDelete(DeleteBehavior.SetNull); + }); + modelBuilder.Entity("SS14.Auth.Shared.Data.Patron", b => { b.HasOne("SS14.Auth.Shared.Data.SpaceUser", "SpaceUser") @@ -1780,6 +1938,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Users"); }); + modelBuilder.Entity("SS14.Auth.Shared.Data.PatreonCampaign", b => + { + b.Navigation("Memberships"); + }); + modelBuilder.Entity("SS14.Auth.Shared.Data.SpaceUser", b => { b.Navigation("AccountLogs"); diff --git a/SS14.Auth.Shared/Data/PatreonCampaign.cs b/SS14.Auth.Shared/Data/PatreonCampaign.cs new file mode 100644 index 00000000..e0387a8f --- /dev/null +++ b/SS14.Auth.Shared/Data/PatreonCampaign.cs @@ -0,0 +1,74 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace SS14.Auth.Shared.Data; + +public sealed class PatreonCampaign +{ + public int Id { get; set; } + + /// + /// Short unique name used in URLs referencing this campaign + /// + [Required] public string Key { get; set; } = default!; + + [Required] public string PatreonCampaignId { get; set; } = default!; + + [Required] public string Name { get; set; } = default!; + + /// + /// Maps Patreon tier IDs to reward names + /// + [Column(TypeName = "jsonb")] + public Dictionary TierMap { get; set; } = new(); + + /// + /// Maps reward names to display names + /// + [Column(TypeName = "jsonb")] + public Dictionary TierNames { get; set; } = new(); + + /// + /// Patreon tier IDs that are turned off + /// + public string[] DisabledTierIds { get; set; } = []; + + // The following secrets are encrypted, see PatreonSecretProtector + public string? WebhookSecret { get; set; } + public string? AccessToken { get; set; } + public string? RefreshToken { get; set; } + public DateTimeOffset? TokenExpiresAt { get; set; } + + /// + /// Hash of the token the campaign's servers use to query memberships + /// + public string? ServerTokenHash { get; set; } + + /// + /// If set, this campaign provides the patron tier returned by the query API and shown on the account page. + /// At most one campaign can be first party. This replicates the previous system + /// + public bool IsFirstParty { get; set; } + + /// + /// The user who connected the campaign and manages it. Null for campaigns added by admins + /// + public Guid? OwnerUserId { get; set; } + + /// + /// Campaigns connected by their creator stay disabled until the first import has finished. + /// Admins can also disable a campaign should the need arise + /// + public bool Enabled { get; set; } + public DateTimeOffset? LastFullSyncAt { get; set; } + + /// + /// When Patreon last sent a valid webhook for this campaign. Helps spot a broken webhook + /// + public DateTimeOffset? LastWebhookAt { get; set; } + + public List Memberships { get; set; } = default!; +} diff --git a/SS14.Auth.Shared/Data/PatreonDataManager.cs b/SS14.Auth.Shared/Data/PatreonDataManager.cs index 9495e4b8..e0125781 100644 --- a/SS14.Auth.Shared/Data/PatreonDataManager.cs +++ b/SS14.Auth.Shared/Data/PatreonDataManager.cs @@ -1,5 +1,9 @@ -using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; +using SS14.Auth.Shared.Patreon; namespace SS14.Auth.Shared.Data; @@ -14,6 +18,42 @@ public PatreonDataManager(ApplicationDbContext db) public async Task GetPatreonTierAsync(SpaceUser user) { - return (await _db.Patrons.SingleOrDefaultAsync(p => p.SpaceUserId == user.Id))?.CurrentTier; + return await ( + from patron in _db.Patrons + where patron.SpaceUserId == user.Id + join membership in _db.PatreonMemberships on patron.PatreonId equals membership.PatreonUserId + where membership.Campaign.IsFirstParty && membership.Campaign.Enabled + select membership.CurrentTier) + .FirstOrDefaultAsync(); } -} \ No newline at end of file + + public async Task GetCampaignByServerTokenAsync(string token) + { + if (string.IsNullOrEmpty(token)) + return null; + + var hash = PatreonServerToken.Hash(token); + return await _db.PatreonCampaigns.SingleOrDefaultAsync(c => c.Enabled && c.ServerTokenHash == hash); + } + + /// + /// Gets the memberships of the given users in a campaign, leaving out users who hide it from the campaign's + /// servers. Users without a (visible) membership are not in the result. + /// + public async Task> GetCampaignStatusesAsync( + PatreonCampaign campaign, + IReadOnlyCollection userIds) + { + var rows = await ( + from patron in _db.Patrons + where userIds.Contains(patron.SpaceUserId) + join membership in _db.PatreonMemberships on patron.PatreonId equals membership.PatreonUserId + where membership.CampaignId == campaign.Id && !membership.Hidden + select new { patron.SpaceUserId, membership.PatronStatus, membership.CurrentTier }) + .ToListAsync(); + + return rows.ToDictionary(r => r.SpaceUserId, r => new PatreonCampaignStatus(r.PatronStatus, r.CurrentTier)); + } +} + +public sealed record PatreonCampaignStatus(string PatronStatus, string Tier); diff --git a/SS14.Auth.Shared/Data/PatreonMembership.cs b/SS14.Auth.Shared/Data/PatreonMembership.cs new file mode 100644 index 00000000..794eaa58 --- /dev/null +++ b/SS14.Auth.Shared/Data/PatreonMembership.cs @@ -0,0 +1,42 @@ +#nullable enable +using System; +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace SS14.Auth.Shared.Data; + +public sealed class PatreonMembership +{ + public long Id { get; set; } + + public int CampaignId { get; set; } + + /// + /// Matches . + /// + [Required] public string PatreonUserId { get; set; } = default!; + + [Required] public string PatreonMemberId { get; set; } = default!; + + /// + /// active_patron, declined_patron, former_patron or null + /// + public string? PatronStatus { get; set; } + + public string[] EntitledTierIds { get; set; } = []; + + /// + /// Reward name from the campaign's tier map for the entitled tiers, if any. + /// + public string? CurrentTier { get; set; } + + public DateTimeOffset UpdatedAt { get; set; } + + /// + /// If set, the player chose not to share this membership with the campaign's servers + /// + public bool Hidden { get; set; } + + [JsonIgnore] + public PatreonCampaign Campaign { get; set; } = null!; +} diff --git a/SS14.Auth.Shared/Data/PatreonWebhookLogs.cs b/SS14.Auth.Shared/Data/PatreonWebhookLogs.cs index 0a2903a1..d1bf3d1f 100644 --- a/SS14.Auth.Shared/Data/PatreonWebhookLogs.cs +++ b/SS14.Auth.Shared/Data/PatreonWebhookLogs.cs @@ -9,5 +9,10 @@ public class PatreonWebhookLog public string Trigger { get; set; } public DateTimeOffset Time { get; set; } + /// + /// The campaign this was received for. Null for the first-party webhook. + /// + public int? CampaignId { get; set; } + [Column(TypeName = "jsonb")] public string Content { get; set; } } \ No newline at end of file diff --git a/SS14.Auth.Shared/Data/Patron.cs b/SS14.Auth.Shared/Data/Patron.cs index ea6c9b49..9e76f340 100644 --- a/SS14.Auth.Shared/Data/Patron.cs +++ b/SS14.Auth.Shared/Data/Patron.cs @@ -13,6 +13,4 @@ public class Patron [JsonIgnore] public SpaceUser SpaceUser { get; set; } - - public string CurrentTier { get; set; } } diff --git a/SS14.Auth.Shared/Patreon/PatreonApiClient.cs b/SS14.Auth.Shared/Patreon/PatreonApiClient.cs new file mode 100644 index 00000000..82924171 --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonApiClient.cs @@ -0,0 +1,161 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Options; +using SS14.Auth.Shared.Config; + +namespace SS14.Auth.Shared.Patreon; + +public sealed record PatreonTokens(string AccessToken, string RefreshToken, DateTimeOffset ExpiresAt); + +public sealed class PatreonApiClient +{ + private const int MaxAttempts = 5; + private const int PageSize = 500; + + private static readonly string[] WebhookTriggers = + [ + "members:create", + "members:update", + "members:delete", + "members:pledge:create", + "members:pledge:update", + "members:pledge:delete" + ]; + + private readonly HttpClient _http; + private readonly IOptions _cfg; + + public PatreonApiClient(HttpClient http, IOptions cfg) + { + _http = http; + _cfg = cfg; + } + + public async Task GetMembersPageAsync( + string accessToken, + string campaignId, + string? cursor, + CancellationToken cancel = default) + { + var url = $"api/oauth2/v2/campaigns/{Uri.EscapeDataString(campaignId)}/members" + + "?include=user,currently_entitled_tiers" + + "&fields%5Bmember%5D=patron_status" + + $"&page%5Bsize%5D={PageSize}"; + + if (cursor != null) + url += $"&page%5Bcursor%5D={Uri.EscapeDataString(cursor)}"; + + using var response = await SendAsync(() => + { + var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Authorization = new("Bearer", accessToken); + return request; + }, cancel); + + await using var stream = await response.Content.ReadAsStreamAsync(cancel); + using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancel); + return PatreonMemberParser.ParsePage(doc.RootElement); + } + + public async Task> GetCampaignsAsync(string accessToken, CancellationToken cancel = default) + { + using var response = await SendAsync(() => + { + var request = new HttpRequestMessage( + HttpMethod.Get, + "api/oauth2/v2/campaigns?include=tiers,creator" + + "&fields%5Bcampaign%5D=vanity&fields%5Btier%5D=title&fields%5Buser%5D=full_name"); + request.Headers.Authorization = new("Bearer", accessToken); + return request; + }, cancel); + + await using var stream = await response.Content.ReadAsStreamAsync(cancel); + using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancel); + return PatreonCampaignParser.ParseCampaigns(doc.RootElement); + } + + public async Task CreateWebhookAsync( + string accessToken, + string campaignId, + string uri, + CancellationToken cancel = default) + { + var body = JsonSerializer.Serialize(new + { + data = new + { + type = "webhook", + attributes = new + { + triggers = WebhookTriggers, + uri + }, + relationships = new + { + campaign = new { data = new { type = "campaign", id = campaignId } } + } + } + }); + + using var response = await SendAsync(() => + { + var request = new HttpRequestMessage(HttpMethod.Post, "api/oauth2/v2/webhooks") + { + Content = new StringContent(body, Encoding.UTF8, "application/json") + }; + request.Headers.Authorization = new("Bearer", accessToken); + return request; + }, cancel); + + await using var stream = await response.Content.ReadAsStreamAsync(cancel); + using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancel); + return doc.RootElement.GetProperty("data").GetProperty("attributes").GetProperty("secret").GetString()!; + } + + public async Task RefreshTokenAsync(string refreshToken, CancellationToken cancel = default) + { + using var response = await SendAsync(() => new HttpRequestMessage(HttpMethod.Post, "api/oauth2/token") + { + Content = new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "refresh_token", + ["refresh_token"] = refreshToken, + ["client_id"] = _cfg.Value.ClientId, + ["client_secret"] = _cfg.Value.ClientSecret + }) + }, cancel); + + await using var stream = await response.Content.ReadAsStreamAsync(cancel); + using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancel); + var root = doc.RootElement; + + return new PatreonTokens( + root.GetProperty("access_token").GetString()!, + root.GetProperty("refresh_token").GetString()!, + DateTimeOffset.UtcNow.AddSeconds(root.GetProperty("expires_in").GetInt32())); + } + + private async Task SendAsync(Func makeRequest, CancellationToken cancel) + { + for (var attempt = 1;; attempt++) + { + var response = await _http.SendAsync(makeRequest(), cancel); + if (response.StatusCode != HttpStatusCode.TooManyRequests || attempt == MaxAttempts) + { + response.EnsureSuccessStatusCode(); + return response; + } + + var delay = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(1 << attempt); + response.Dispose(); + await Task.Delay(delay, cancel); + } + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonCampaignParser.cs b/SS14.Auth.Shared/Patreon/PatreonCampaignParser.cs new file mode 100644 index 00000000..77c436c3 --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonCampaignParser.cs @@ -0,0 +1,99 @@ +#nullable enable +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; + +namespace SS14.Auth.Shared.Patreon; + +/// +/// A campaign as returned by the Patreon API. maps tier IDs to titles. +/// +public sealed record PatreonCampaignInfo(string Id, string Name, Dictionary Tiers); + +public static class PatreonCampaignParser +{ + public static List ParseCampaigns(JsonElement root) + { + var tierTitles = new Dictionary(); + var creatorNames = new Dictionary(); + if (root.TryGetProperty("included", out var included) && included.ValueKind == JsonValueKind.Array) + { + foreach (var item in included.EnumerateArray()) + { + if (!item.TryGetProperty("type", out var type) + || !item.TryGetProperty("id", out var id) || id.GetString() is not { } idStr + || !item.TryGetProperty("attributes", out var attributes)) + { + continue; + } + + if (type.GetString() == "tier" && GetString(attributes, "title") is { } title) + tierTitles[idStr] = title; + else if (type.GetString() == "user" && GetString(attributes, "full_name") is { } fullName) + creatorNames[idStr] = fullName; + } + } + + var campaigns = new List(); + if (!root.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Array) + return campaigns; + + foreach (var campaign in data.EnumerateArray()) + { + if (!campaign.TryGetProperty("id", out var idProp) || idProp.GetString() is not { } campaignId) + continue; + + string? name = null; // This can be null in the response for whatever reason + JsonElement relationships = default; + var hasRelationships = campaign.TryGetProperty("relationships", out relationships); + if (hasRelationships + && relationships.TryGetProperty("creator", out var creatorProp) + && creatorProp.TryGetProperty("data", out var creatorData) + && creatorData.ValueKind == JsonValueKind.Object + && creatorData.TryGetProperty("id", out var creatorId) + && creatorId.GetString() is { } creatorIdStr) + { + creatorNames.TryGetValue(creatorIdStr, out name); + } + + if (string.IsNullOrWhiteSpace(name) && campaign.TryGetProperty("attributes", out var attributes)) + name = GetString(attributes, "vanity"); + + var tiers = new Dictionary(); + if (hasRelationships + && relationships.TryGetProperty("tiers", out var tiersProp) + && tiersProp.TryGetProperty("data", out var tiersData) + && tiersData.ValueKind == JsonValueKind.Array) + { + foreach (var tier in tiersData.EnumerateArray()) + { + if (tier.TryGetProperty("id", out var tierId) + && tierId.GetString() is { } tierIdStr + && tierTitles.TryGetValue(tierIdStr, out var tierTitle)) + { + tiers[tierIdStr] = tierTitle; + } + } + } + + campaigns.Add(new PatreonCampaignInfo( + campaignId, + string.IsNullOrWhiteSpace(name) ? FallbackName(campaignId) : name, + tiers)); + } + + return campaigns; + } + + public static string FallbackName(string campaignId) + { + return $"Campaign {campaignId}"; + } + + private static string? GetString(JsonElement element, string property) + { + return element.TryGetProperty(property, out var prop) && prop.ValueKind == JsonValueKind.String + ? prop.GetString() + : null; + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonImporter.cs b/SS14.Auth.Shared/Patreon/PatreonImporter.cs new file mode 100644 index 00000000..8dc67ffa --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonImporter.cs @@ -0,0 +1,102 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using SS14.Auth.Shared.Data; + +namespace SS14.Auth.Shared.Patreon; + +public sealed class PatreonImporter +{ + private static readonly TimeSpan TokenRefreshMargin = TimeSpan.FromMinutes(5); + + private readonly ApplicationDbContext _db; + private readonly PatreonApiClient _api; + private readonly PatreonSecretProtector _secretProtector; + private readonly PatreonMembershipManager _membershipManager; + + public PatreonImporter( + ApplicationDbContext db, + PatreonApiClient api, + PatreonSecretProtector secretProtector, + PatreonMembershipManager membershipManager) + { + _db = db; + _api = api; + _secretProtector = secretProtector; + _membershipManager = membershipManager; + } + + public async Task ImportAsync(PatreonCampaign campaign, CancellationToken cancel = default) + { + var accessToken = await GetAccessTokenAsync(campaign, cancel); + + var members = new List(); + string? cursor = null; + do + { + var page = await _api.GetMembersPageAsync(accessToken, campaign.PatreonCampaignId, cursor, cancel); + members.AddRange(page.Members); + cursor = page.NextCursor; + } while (cursor != null); + + await _membershipManager.ReplaceAllAsync(campaign, members); + + campaign.LastFullSyncAt = DateTimeOffset.UtcNow; + await _db.SaveChangesAsync(cancel); + + return members.Count; + } + + /// + /// Adds tiers the creator created on Patreon since we last looked to the tier map. + /// + public async Task RefreshTiersAsync(PatreonCampaign campaign, CancellationToken cancel = default) + { + var accessToken = await GetAccessTokenAsync(campaign, cancel); + + var campaigns = await _api.GetCampaignsAsync(accessToken, cancel); + var info = campaigns.Find(c => c.Id == campaign.PatreonCampaignId); + if (info == null) + return 0; + + // If we failed to get any sort of name prior, this should hopefully get one now + if (campaign.Name == PatreonCampaignParser.FallbackName(campaign.PatreonCampaignId)) + campaign.Name = info.Name; + + var (tierMap, tierNames, added) = PatreonTierMapping.WithNewTiers( + campaign.TierMap, + campaign.TierNames, + info.Tiers); + + if (added > 0) + { + campaign.TierMap = tierMap; + campaign.TierNames = tierNames; + await _membershipManager.RemapTiersAsync(campaign); + } + + await _db.SaveChangesAsync(cancel); + + return added; + } + + private async Task GetAccessTokenAsync(PatreonCampaign campaign, CancellationToken cancel) + { + if (campaign.AccessToken == null) + throw new InvalidOperationException("Campaign has no access token."); + + var expiring = campaign.TokenExpiresAt is { } expiry && expiry - DateTimeOffset.UtcNow < TokenRefreshMargin; + if (expiring && campaign.RefreshToken != null) + { + var tokens = await _api.RefreshTokenAsync(_secretProtector.Unprotect(campaign.RefreshToken), cancel); + campaign.AccessToken = _secretProtector.Protect(tokens.AccessToken); + campaign.RefreshToken = _secretProtector.Protect(tokens.RefreshToken); + campaign.TokenExpiresAt = tokens.ExpiresAt; + await _db.SaveChangesAsync(cancel); + } + + return _secretProtector.Unprotect(campaign.AccessToken); + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonMemberParser.cs b/SS14.Auth.Shared/Patreon/PatreonMemberParser.cs new file mode 100644 index 00000000..d489287a --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonMemberParser.cs @@ -0,0 +1,105 @@ +#nullable enable +using System.Collections.Generic; +using System.Text.Json; + +namespace SS14.Auth.Shared.Patreon; + +public sealed record PatreonMemberData( + string MemberId, + string UserId, + string? PatronStatus, + string[] TierIds); + +/// +/// One page of a campaign's member list. +/// is null on the last page +/// +public sealed record PatreonMemberPage(IReadOnlyList Members, string? NextCursor); + +public static class PatreonMemberParser +{ + public static PatreonMemberData? ParseWebhook(JsonElement root) + { + if (!root.TryGetProperty("data", out var data)) + return null; + + return ParseMember(data); + } + + public static PatreonMemberPage ParsePage(JsonElement root) + { + var members = new List(); + if (root.TryGetProperty("data", out var data) && data.ValueKind == JsonValueKind.Array) + { + foreach (var item in data.EnumerateArray()) + { + if (ParseMember(item) is { } member) + members.Add(member); + } + } + + string? next = null; + if (root.TryGetProperty("meta", out var meta) + && meta.TryGetProperty("pagination", out var pagination) + && pagination.TryGetProperty("cursors", out var cursors) + && cursors.TryGetProperty("next", out var nextProp) + && nextProp.ValueKind == JsonValueKind.String) + { + next = nextProp.GetString(); + } + + return new PatreonMemberPage(members, next); + } + + /// + /// Parses a member resource, as found in webhooks and campaign member lists. + /// Returns null if the member has no user to link it to + /// + public static PatreonMemberData? ParseMember(JsonElement member) + { + if (member.ValueKind != JsonValueKind.Object || !member.TryGetProperty("id", out var idProp)) + return null; + + if (!member.TryGetProperty("relationships", out var relationships)) + return null; + + var userId = GetSingleId(relationships, "user"); + if (userId == null) + return null; + + string? status = null; + if (member.TryGetProperty("attributes", out var attributes) + && attributes.TryGetProperty("patron_status", out var statusProp) + && statusProp.ValueKind == JsonValueKind.String) + { + status = statusProp.GetString(); + } + + var tiers = new List(); + if (relationships.TryGetProperty("currently_entitled_tiers", out var tiersProp) + && tiersProp.TryGetProperty("data", out var tiersData) + && tiersData.ValueKind == JsonValueKind.Array) + { + foreach (var tier in tiersData.EnumerateArray()) + { + if (tier.TryGetProperty("id", out var tierId) && tierId.GetString() is { } tierIdStr) + tiers.Add(tierIdStr); + } + } + + return new PatreonMemberData(idProp.GetString()!, userId, status, tiers.ToArray()); + } + + private static string? GetSingleId(JsonElement relationships, string name) + { + if (!relationships.TryGetProperty(name, out var rel) + || !rel.TryGetProperty("data", out var data) + || data.ValueKind != JsonValueKind.Object + || !data.TryGetProperty("id", out var id)) + { + return null; + } + + return id.GetString(); + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonMembershipManager.cs b/SS14.Auth.Shared/Patreon/PatreonMembershipManager.cs new file mode 100644 index 00000000..a9c0cf49 --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonMembershipManager.cs @@ -0,0 +1,152 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using SS14.Auth.Shared.Data; + +namespace SS14.Auth.Shared.Patreon; + +public sealed class PatreonMembershipManager +{ + private readonly ApplicationDbContext _db; + + public PatreonMembershipManager(ApplicationDbContext db) + { + _db = db; + } + + public Task UpsertAsync(PatreonCampaign campaign, PatreonMemberData data) + { + return WithRetryOnConflictAsync(async () => + { + var membership = await _db.PatreonMemberships + .SingleOrDefaultAsync(m => m.CampaignId == campaign.Id && m.PatreonUserId == data.UserId); + + if (membership == null) + { + membership = new PatreonMembership + { + CampaignId = campaign.Id, + PatreonUserId = data.UserId + }; + _db.PatreonMemberships.Add(membership); + } + + Apply(membership, campaign, data); + + await _db.SaveChangesAsync(); + }); + } + + /// + /// Makes the campaign's memberships match the given list exactly, removing the ones not in it. + /// + public Task ReplaceAllAsync(PatreonCampaign campaign, IReadOnlyCollection members) + { + return WithRetryOnConflictAsync(async () => + { + var existing = await _db.PatreonMemberships + .Where(m => m.CampaignId == campaign.Id) + .ToDictionaryAsync(m => m.PatreonUserId); + + var seen = new HashSet(); + foreach (var data in members) + { + seen.Add(data.UserId); + + if (!existing.TryGetValue(data.UserId, out var membership)) + { + membership = new PatreonMembership + { + CampaignId = campaign.Id, + PatreonUserId = data.UserId + }; + _db.PatreonMemberships.Add(membership); + existing.Add(data.UserId, membership); + } + + Apply(membership, campaign, data); + } + + _db.PatreonMemberships.RemoveRange(existing.Where(e => !seen.Contains(e.Key)).Select(e => e.Value)); + + await _db.SaveChangesAsync(); + }); + } + + public static bool IsUniqueViolation(DbUpdateException exception) + { + return exception.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }; + } + + /// + /// Runs a write, and once more if it lost a race with another writer inserting the same membership. + /// If a webhook request comes in while running a large sync, this would trigger + /// + private async Task WithRetryOnConflictAsync(Func write) + { + try + { + await write(); + } + catch (DbUpdateException e) when (IsUniqueViolation(e)) + { + foreach (var entry in _db.ChangeTracker.Entries().ToList()) + { + entry.State = EntityState.Detached; + } + + await write(); + } + } + + /// + /// Recomputes the stored tier of the campaign's memberships, after its tier map changed + /// + public async Task RemapTiersAsync(PatreonCampaign campaign) + { + var memberships = await _db.PatreonMemberships + .Where(m => m.CampaignId == campaign.Id) + .ToListAsync(); + + foreach (var membership in memberships) + { + membership.CurrentTier = MapTier(campaign.TierMap, membership.EntitledTierIds, campaign.DisabledTierIds); + } + + await _db.SaveChangesAsync(); + } + + public async Task RemoveAsync(PatreonCampaign campaign, string patreonUserId) + { + var memberships = await _db.PatreonMemberships + .Where(m => m.CampaignId == campaign.Id && m.PatreonUserId == patreonUserId) + .ToListAsync(); + + _db.PatreonMemberships.RemoveRange(memberships); + await _db.SaveChangesAsync(); + } + + public static string? MapTier( + IReadOnlyDictionary tierMap, + IEnumerable tierIds, + IReadOnlyCollection? disabledTierIds = null) + { + return tierIds + .Where(t => tierMap.ContainsKey(t) && disabledTierIds?.Contains(t) != true) + .Select(t => tierMap[t]) + .FirstOrDefault(); + } + + private static void Apply(PatreonMembership membership, PatreonCampaign campaign, PatreonMemberData data) + { + membership.PatreonMemberId = data.MemberId; + membership.PatronStatus = data.PatronStatus; + membership.EntitledTierIds = data.TierIds; + membership.CurrentTier = MapTier(campaign.TierMap, data.TierIds, campaign.DisabledTierIds); + membership.UpdatedAt = DateTimeOffset.UtcNow; + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonSecretProtector.cs b/SS14.Auth.Shared/Patreon/PatreonSecretProtector.cs new file mode 100644 index 00000000..425a1c39 --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonSecretProtector.cs @@ -0,0 +1,23 @@ +using Microsoft.AspNetCore.DataProtection; + +namespace SS14.Auth.Shared.Patreon; + +public sealed class PatreonSecretProtector +{ + private readonly IDataProtector _protector; + + public PatreonSecretProtector(IDataProtectionProvider provider) + { + _protector = provider.CreateProtector("SS14.Patreon.CampaignSecrets"); + } + + public string Protect(string plaintext) + { + return _protector.Protect(plaintext); + } + + public string Unprotect(string protectedText) + { + return _protector.Unprotect(protectedText); + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonServerToken.cs b/SS14.Auth.Shared/Patreon/PatreonServerToken.cs new file mode 100644 index 00000000..83794fde --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonServerToken.cs @@ -0,0 +1,24 @@ +using System; +using System.Security.Cryptography; +using System.Text; + +namespace SS14.Auth.Shared.Patreon; + +/// +/// Tokens for a campaign's game servers to query its memberships. Only the hash is stored. +/// +public static class PatreonServerToken +{ + public static string Generate() + { + return Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) + .Replace('+', '-') + .Replace('/', '_') + .TrimEnd('='); + } + + public static string Hash(string token) + { + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonTierMapping.cs b/SS14.Auth.Shared/Patreon/PatreonTierMapping.cs new file mode 100644 index 00000000..d8f5b3d3 --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonTierMapping.cs @@ -0,0 +1,54 @@ +#nullable enable +using System.Collections.Generic; + +namespace SS14.Auth.Shared.Patreon; + +/// +/// Edits to a campaign's tier map. These return new dictionaries, because EF doesn't notice changes made to the +/// dictionaries of a jsonb column in place. +/// +public static class PatreonTierMapping +{ + /// + /// Sets the reward name of a tier. The tier keeps showing under its old display name, unless the new reward + /// already has one. + /// + public static (Dictionary TierMap, Dictionary TierNames) WithReward( + IReadOnlyDictionary tierMap, + IReadOnlyDictionary tierNames, + string tierId, + string reward) + { + var newMap = new Dictionary(tierMap); + var newNames = new Dictionary(tierNames); + + var oldReward = newMap.GetValueOrDefault(tierId); + var displayName = oldReward == null ? reward : newNames.GetValueOrDefault(oldReward, oldReward); + + newMap[tierId] = reward; + newNames.TryAdd(reward, displayName); + + return (newMap, newNames); + } + + public static (Dictionary TierMap, Dictionary TierNames, int Added) WithNewTiers( + IReadOnlyDictionary tierMap, + IReadOnlyDictionary tierNames, + IReadOnlyDictionary tiers) + { + var newMap = new Dictionary(tierMap); + var newNames = new Dictionary(tierNames); + + var added = 0; + foreach (var (id, title) in tiers) + { + if (!newMap.TryAdd(id, title)) + continue; + + newNames.TryAdd(title, title); + added += 1; + } + + return (newMap, newNames, added); + } +} diff --git a/SS14.Auth.Shared/Patreon/PatreonWebhookSignature.cs b/SS14.Auth.Shared/Patreon/PatreonWebhookSignature.cs new file mode 100644 index 00000000..8143f623 --- /dev/null +++ b/SS14.Auth.Shared/Patreon/PatreonWebhookSignature.cs @@ -0,0 +1,28 @@ +#nullable enable +using System; +using System.Security.Cryptography; +using System.Text; + +namespace SS14.Auth.Shared.Patreon; + +public static class PatreonWebhookSignature +{ + public static bool Verify(ReadOnlySpan body, string secret, string? signature) + { + if (string.IsNullOrEmpty(signature) || signature.Length % 2 != 0) + return false; + + byte[] sigBytes; + try + { + sigBytes = Utility.FromHex(signature); + } + catch (FormatException) + { + return false; + } + + var hash = HMACMD5.HashData(Encoding.UTF8.GetBytes(secret), body); + return Utility.SecretEqual(sigBytes, hash); + } +} diff --git a/SS14.Auth.Shared/StartupHelpers.cs b/SS14.Auth.Shared/StartupHelpers.cs index b8594bc9..36673b3d 100644 --- a/SS14.Auth.Shared/StartupHelpers.cs +++ b/SS14.Auth.Shared/StartupHelpers.cs @@ -15,6 +15,7 @@ using SS14.Auth.Shared.Data; using SS14.Auth.Shared.Emails; using SS14.Auth.Shared.MutexDb; +using SS14.Auth.Shared.Patreon; using SS14.Auth.Shared.Sessions; namespace SS14.Auth.Shared; @@ -79,6 +80,13 @@ public static void AddShared(IServiceCollection services, IConfiguration config) services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); + services.AddHttpClient(client => + { + client.BaseAddress = new Uri("https://www.patreon.com/"); + }); services.AddTransient(_ => RandomNumberGenerator.Create()); diff --git a/SS14.Auth/Controllers/PatreonHookController.cs b/SS14.Auth/Controllers/PatreonHookController.cs index 1091fe9d..bd36e180 100644 --- a/SS14.Auth/Controllers/PatreonHookController.cs +++ b/SS14.Auth/Controllers/PatreonHookController.cs @@ -1,14 +1,15 @@ using System; using System.IO; -using System.Security.Cryptography; using System.Text; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using SS14.Auth.Shared; using SS14.Auth.Shared.Config; using SS14.Auth.Shared.Data; +using SS14.Auth.Shared.Patreon; namespace SS14.Auth.Controllers; @@ -19,60 +20,93 @@ public class PatreonHookController : ControllerBase private readonly IOptions _patreonCfg; private readonly ILogger _logger; private readonly ApplicationDbContext _db; + private readonly PatreonMembershipManager _membershipManager; + private readonly PatreonSecretProtector _secretProtector; public PatreonHookController( - IOptions patreonCfg, + IOptions patreonCfg, ILogger logger, - ApplicationDbContext db) + ApplicationDbContext db, + PatreonMembershipManager membershipManager, + PatreonSecretProtector secretProtector) { _patreonCfg = patreonCfg; _logger = logger; _db = db; + _membershipManager = membershipManager; + _secretProtector = secretProtector; } - [HttpPost] - public async Task Hook( - [FromHeader(Name = "X-Patreon-Signature")] string signature, - [FromHeader(Name = "X-Patreon-Event")] string trigger) + [HttpPost("{campaignKey}")] + public async Task CampaignHook( + string campaignKey, + [FromHeader(Name = "X-Patreon-Signature")] string? signature, + [FromHeader(Name = "X-Patreon-Event")] string? trigger) { - _logger.LogDebug("Handling Patreon event of type {Event} signature {Signature}", trigger, signature); - - var ms = new MemoryStream(); - await Request.Body.CopyToAsync(ms); - ms.Position = 0; + // Not filtered on Enabled so events aren't lost while the first import is still pending. + var campaign = await _db.PatreonCampaigns.SingleOrDefaultAsync(c => c.Key == campaignKey); + if (campaign?.WebhookSecret == null) + return NotFound(); - var sigBytes = Utility.FromHex(signature); - var hmac = new HMACMD5(Encoding.UTF8.GetBytes(_patreonCfg.Value.WebhookSecret)); - // ReSharper disable once MethodHasAsyncOverload - hmac.ComputeHash(ms); - ms.Position = 0; + using var ms = new MemoryStream(); + await Request.Body.CopyToAsync(ms); + var body = ms.ToArray(); - if (!Utility.SecretEqual(sigBytes, hmac.Hash)) + var secret = _secretProtector.Unprotect(campaign.WebhookSecret); + if (!PatreonWebhookSignature.Verify(body, secret, signature)) { - _logger.LogDebug("Signature failed to validate, ignoring"); + _logger.LogDebug("Signature failed to validate for campaign {Campaign}, ignoring", campaign.Key); return Unauthorized(); } - _logger.LogDebug("Patreon webhook passed signature check!"); + campaign.LastWebhookAt = DateTimeOffset.UtcNow; + await _db.SaveChangesAsync(); if (_patreonCfg.Value.LogWebhooks) { - _logger.LogTrace("Storing in database"); - using var reader = new StreamReader(ms); - // ReSharper disable once MethodHasAsyncOverload - var str = reader.ReadToEnd(); - - // ReSharper disable once MethodHasAsyncOverload _db.PatreonWebhookLogs.Add(new PatreonWebhookLog { - Content = str, + Content = Encoding.UTF8.GetString(body), Time = DateTimeOffset.UtcNow, - Trigger = trigger + Trigger = trigger ?? "", + CampaignId = campaign.Id }); await _db.SaveChangesAsync(); } - + + JsonDocument doc; + try + { + doc = JsonDocument.Parse(body); + } + catch (JsonException) + { + return BadRequest(); + } + + using (doc) + { + var member = PatreonMemberParser.ParseWebhook(doc.RootElement); + if (member == null) + return Ok(); + + switch (trigger) + { + case "members:create": + case "members:update": + case "members:pledge:create": + case "members:pledge:update": + case "members:pledge:delete": + await _membershipManager.UpsertAsync(campaign, member); + break; + + case "members:delete": + await _membershipManager.RemoveAsync(campaign, member.UserId); + break; + } + } + return Ok(); } } \ No newline at end of file diff --git a/SS14.Auth/Controllers/QueryApiController.cs b/SS14.Auth/Controllers/QueryApiController.cs index ac4e1962..fb0d597b 100644 --- a/SS14.Auth/Controllers/QueryApiController.cs +++ b/SS14.Auth/Controllers/QueryApiController.cs @@ -81,13 +81,28 @@ public async Task QueryByUserId(Guid userId) return await DoResponse(user); } + /// + /// Servers can send this header to also get the user's membership in their community's Patreon campaign. + /// + internal const string CampaignTokenHeader = "SS14-Campaign-Token"; + internal static async Task BuildUserResponse( PatreonDataManager patreonDataManager, - SpaceUser user) + SpaceUser user, + string? campaignToken) { var patronTier = await patreonDataManager.GetPatreonTierAsync(user); - return new QueryUserResponse(user.UserName!, user.Id, patronTier, user.CreatedTime); + // A missing or invalid token is not an error, just no the community data is returned. + CommunityPatronResponse? communityPatron = null; + if (await patreonDataManager.GetCampaignByServerTokenAsync(campaignToken!) is { } campaign) + { + var statuses = await patreonDataManager.GetCampaignStatusesAsync(campaign, [user.Id]); + if (statuses.TryGetValue(user.Id, out var status)) + communityPatron = new CommunityPatronResponse(status.PatronStatus, status.Tier); + } + + return new QueryUserResponse(user.UserName!, user.Id, patronTier, user.CreatedTime, communityPatron); } private async Task DoResponse(SpaceUser? user) @@ -95,6 +110,6 @@ private async Task DoResponse(SpaceUser? user) if (user == null) return NotFound(); - return Ok(await BuildUserResponse(_patreonDataManager, user)); + return Ok(await BuildUserResponse(_patreonDataManager, user, Request.Headers[CampaignTokenHeader])); } } diff --git a/SS14.Auth/Controllers/SessionApiController.cs b/SS14.Auth/Controllers/SessionApiController.cs index b140ff30..5bf1bdac 100644 --- a/SS14.Auth/Controllers/SessionApiController.cs +++ b/SS14.Auth/Controllers/SessionApiController.cs @@ -91,7 +91,9 @@ public async Task HasJoined(Guid userId, string hash) } var userResponse = await QueryApiController.BuildUserResponse( - _patreonDataManager, authHash.SpaceUser); + _patreonDataManager, + authHash.SpaceUser, + Request.Headers[QueryApiController.CampaignTokenHeader]); var hwidString = authHash.Hwid?.Value is { } hwid ? Convert.ToBase64String(hwid) : null; diff --git a/SS14.Auth/Responses/QueryUserResponse.cs b/SS14.Auth/Responses/QueryUserResponse.cs index a1c35ed8..1ec055cb 100644 --- a/SS14.Auth/Responses/QueryUserResponse.cs +++ b/SS14.Auth/Responses/QueryUserResponse.cs @@ -1,4 +1,5 @@ using System; +using System.Text.Json.Serialization; namespace SS14.Auth.Responses; @@ -6,6 +7,10 @@ public sealed record QueryUserResponse( string UserName, Guid UserId, string? PatronTier, - DateTimeOffset CreatedTime) + DateTimeOffset CreatedTime, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + CommunityPatronResponse? CommunityPatron = null) { -} \ No newline at end of file +} + +public sealed record CommunityPatronResponse(string? PatronStatus, string? Tier); diff --git a/SS14.Web.Tests/Patreon/TestPatreonApiClient.cs b/SS14.Web.Tests/Patreon/TestPatreonApiClient.cs new file mode 100644 index 00000000..00bbec0c --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonApiClient.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Options; +using NUnit.Framework; +using SS14.Auth.Shared.Config; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonApiClient))] +public sealed class TestPatreonApiClient +{ + private const string EmptyPage = """{ "data": [] }"""; + + private static PatreonApiClient MakeClient(FakeHandler handler) + { + var http = new HttpClient(handler) { BaseAddress = new Uri("https://patreon.test/") }; + var cfg = Options.Create(new PatreonConfiguration { ClientId = "id", ClientSecret = "secret" }); + return new PatreonApiClient(http, cfg); + } + + [Test] + public async Task TestGetMembersPageFirstPage() + { + var handler = new FakeHandler(() => Json(EmptyPage)); + var client = MakeClient(handler); + + var page = await client.GetMembersPageAsync("token", "c1", null); + + var request = handler.Requests[0]; + Assert.Multiple(() => + { + Assert.That(page.Members, Is.Empty); + Assert.That(request.RequestUri!.AbsolutePath, Is.EqualTo("/api/oauth2/v2/campaigns/c1/members")); + Assert.That(request.RequestUri.Query, Does.Not.Contain("cursor")); + Assert.That(request.Headers.Authorization!.ToString(), Is.EqualTo("Bearer token")); + }); + } + + [Test] + public async Task TestGetMembersPageSendsCursor() + { + var handler = new FakeHandler(() => Json(EmptyPage)); + var client = MakeClient(handler); + + await client.GetMembersPageAsync("token", "c1", "a/b"); + + Assert.That(handler.Requests[0].RequestUri!.Query, Does.Contain("page%5Bcursor%5D=a%2Fb")); + } + + [Test] + public async Task TestRetriesOnTooManyRequests() + { + var handler = new FakeHandler(RateLimited, RateLimited, () => Json(EmptyPage)); + var client = MakeClient(handler); + + await client.GetMembersPageAsync("token", "c1", null); + + Assert.That(handler.Requests, Has.Count.EqualTo(3)); + } + + [Test] + public void TestGivesUpAfterMaxAttempts() + { + var handler = new FakeHandler(RateLimited); + var client = MakeClient(handler); + + Assert.That( + async () => await client.GetMembersPageAsync("token", "c1", null), + Throws.InstanceOf()); + Assert.That(handler.Requests, Has.Count.EqualTo(5)); + } + + [Test] + public void TestDoesNotRetryOtherErrors() + { + var handler = new FakeHandler(() => new HttpResponseMessage(HttpStatusCode.Unauthorized)); + var client = MakeClient(handler); + + Assert.That( + async () => await client.GetMembersPageAsync("token", "c1", null), + Throws.InstanceOf()); + Assert.That(handler.Requests, Has.Count.EqualTo(1)); + } + + [Test] + public async Task TestRefreshToken() + { + var handler = new FakeHandler(() => Json(""" + { "access_token": "new-access", "refresh_token": "new-refresh", "expires_in": 3600 } + """)); + var client = MakeClient(handler); + + var tokens = await client.RefreshTokenAsync("old-refresh"); + + Assert.Multiple(() => + { + Assert.That(tokens.AccessToken, Is.EqualTo("new-access")); + Assert.That(tokens.RefreshToken, Is.EqualTo("new-refresh")); + Assert.That(tokens.ExpiresAt, Is.EqualTo(DateTimeOffset.UtcNow.AddHours(1)).Within(TimeSpan.FromMinutes(1))); + Assert.That(handler.Bodies[0], Does.Contain("refresh_token=old-refresh")); + }); + } + + [Test] + public async Task TestCreateWebhookReturnsSecret() + { + var handler = new FakeHandler(() => Json(""" + { "data": { "attributes": { "secret": "hook-secret" } } } + """)); + var client = MakeClient(handler); + + var secret = await client.CreateWebhookAsync("token", "c1", "https://example.test/hook"); + + Assert.Multiple(() => + { + Assert.That(secret, Is.EqualTo("hook-secret")); + Assert.That(handler.Bodies[0], Does.Contain("https://example.test/hook")); + Assert.That(handler.Bodies[0], Does.Contain("\"id\":\"c1\"")); + }); + } + + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(json) + }; + } + + private static HttpResponseMessage RateLimited() + { + var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero); + return response; + } + + private sealed class FakeHandler : HttpMessageHandler + { + private readonly Func[] _responses; + + public List Requests { get; } = new(); + public List Bodies { get; } = new(); + + public FakeHandler(params Func[] responses) + { + _responses = responses; + } + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + Requests.Add(request); + Bodies.Add(request.Content == null ? "" : await request.Content.ReadAsStringAsync(cancellationToken)); + + return _responses[Math.Min(Requests.Count - 1, _responses.Length - 1)](); + } + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonCampaignParser.cs b/SS14.Web.Tests/Patreon/TestPatreonCampaignParser.cs new file mode 100644 index 00000000..f27a1728 --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonCampaignParser.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using System.Text.Json; +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonCampaignParser))] +public sealed class TestPatreonCampaignParser +{ + private static JsonElement Parse(string json) + { + return JsonDocument.Parse(json).RootElement; + } + + [Test] + public void TestParseCampaigns() + { + var campaigns = PatreonCampaignParser.ParseCampaigns(Parse(""" + { + "data": [ + { + "id": "c1", + "attributes": { "vanity": "vanity" }, + "relationships": { + "creator": { "data": { "id": "u1", "type": "user" } }, + "tiers": { "data": [ { "id": "t1" }, { "id": "unknown" } ] } + } + } + ], + "included": [ + { "type": "tier", "id": "t1", "attributes": { "title": "Janitor" } }, + { "type": "tier", "id": "t2", "attributes": { "title": "Unlisted" } }, + { "type": "user", "id": "u1", "attributes": { "full_name": "Joe Genero" } } + ] + } + """)); + + Assert.That(campaigns, Has.Count.EqualTo(1)); + Assert.Multiple(() => + { + Assert.That(campaigns[0].Id, Is.EqualTo("c1")); + Assert.That(campaigns[0].Name, Is.EqualTo("Joe Genero")); + Assert.That(campaigns[0].Tiers, Is.EqualTo(new Dictionary { ["t1"] = "Janitor" })); + }); + } + + [Test] + public void TestNameFallsBackToVanity() + { + var campaigns = PatreonCampaignParser.ParseCampaigns(Parse(""" + { "data": [ { "id": "c1", "attributes": { "vanity": "vanity" } } ] } + """)); + + Assert.That(campaigns[0].Name, Is.EqualTo("vanity")); + } + + [Test] + public void TestNameFallsBackToId() + { + var campaigns = PatreonCampaignParser.ParseCampaigns(Parse(""" + { "data": [ { "id": "c1", "attributes": { "vanity": null } } ] } + """)); + + Assert.Multiple(() => + { + Assert.That(campaigns[0].Name, Is.EqualTo(PatreonCampaignParser.FallbackName("c1"))); + Assert.That(campaigns[0].Tiers, Is.Empty); + }); + } + + [Test] + public void TestEmptyAndMalformed() + { + Assert.Multiple(() => + { + Assert.That(PatreonCampaignParser.ParseCampaigns(Parse("{}")), Is.Empty); + Assert.That(PatreonCampaignParser.ParseCampaigns(Parse("""{ "data": [ {} ] }""")), Is.Empty); + }); + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonMemberParser.cs b/SS14.Web.Tests/Patreon/TestPatreonMemberParser.cs new file mode 100644 index 00000000..5e85a6a8 --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonMemberParser.cs @@ -0,0 +1,119 @@ +using System.Text.Json; +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonMemberParser))] +public sealed class TestPatreonMemberParser +{ + private const string MemberJson = """ + { + "id": "m1", + "type": "member", + "attributes": { "patron_status": "active_patron" }, + "relationships": { + "user": { "data": { "id": "u1", "type": "user" } }, + "currently_entitled_tiers": { "data": [ { "id": "t1", "type": "tier" }, { "id": "t2", "type": "tier" } ] } + } + } + """; + + private static JsonElement Parse(string json) + { + return JsonDocument.Parse(json).RootElement; + } + + [Test] + public void TestParseMember() + { + var member = PatreonMemberParser.ParseMember(Parse(MemberJson)); + + Assert.That(member, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(member!.MemberId, Is.EqualTo("m1")); + Assert.That(member.UserId, Is.EqualTo("u1")); + Assert.That(member.PatronStatus, Is.EqualTo("active_patron")); + Assert.That(member.TierIds, Is.EqualTo(new[] { "t1", "t2" })); + }); + } + + [Test] + public void TestParseMemberWithoutOptionalFields() + { + var member = PatreonMemberParser.ParseMember(Parse(""" + { "id": "m1", "relationships": { "user": { "data": { "id": "u1" } } } } + """)); + + Assert.That(member, Is.Not.Null); + Assert.Multiple(() => + { + Assert.That(member!.PatronStatus, Is.Null); + Assert.That(member.TierIds, Is.Empty); + }); + } + + [Test] + public void TestParseMemberWithoutUser() + { + Assert.Multiple(() => + { + Assert.That(PatreonMemberParser.ParseMember(Parse(""" + { "id": "m1", "relationships": { "user": { "data": null } } } + """)), Is.Null); + Assert.That(PatreonMemberParser.ParseMember(Parse("""{ "id": "m1" }""")), Is.Null); + Assert.That(PatreonMemberParser.ParseMember(Parse("""{ "relationships": {} }""")), Is.Null); + Assert.That(PatreonMemberParser.ParseMember(Parse("[]")), Is.Null); + }); + } + + [Test] + public void TestParseWebhook() + { + var member = PatreonMemberParser.ParseWebhook(Parse("{ \"data\": " + MemberJson + " }")); + + Assert.Multiple(() => + { + Assert.That(member?.MemberId, Is.EqualTo("m1")); + Assert.That(PatreonMemberParser.ParseWebhook(Parse("{}")), Is.Null); + }); + } + + [Test] + public void TestParsePage() + { + var page = PatreonMemberParser.ParsePage(Parse(""" + { + "data": [ + { + "id": "m1", + "relationships": { "user": { "data": { "id": "u1" } } } + }, + { "id": "orphan", "relationships": {} } + ], + "meta": { "pagination": { "cursors": { "next": "abc" } } } + } + """)); + + Assert.Multiple(() => + { + Assert.That(page.Members, Has.Count.EqualTo(1)); + Assert.That(page.NextCursor, Is.EqualTo("abc")); + }); + } + + [Test] + public void TestParsePageLastPage() + { + var page = PatreonMemberParser.ParsePage(Parse(""" + { "data": [], "meta": { "pagination": { "cursors": { "next": null } } } } + """)); + + Assert.Multiple(() => + { + Assert.That(page.Members, Is.Empty); + Assert.That(page.NextCursor, Is.Null); + }); + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonMembershipManager.cs b/SS14.Web.Tests/Patreon/TestPatreonMembershipManager.cs new file mode 100644 index 00000000..c04ce7e9 --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonMembershipManager.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonMembershipManager))] +public sealed class TestPatreonMembershipManager +{ + private static readonly Dictionary TierMap = new() + { + ["1"] = "Assistant", + ["2"] = "Captain" + }; + + [Test] + public void TestMapTier() + { + Assert.Multiple(() => + { + Assert.That(PatreonMembershipManager.MapTier(TierMap, ["2"]), Is.EqualTo("Captain")); + Assert.That(PatreonMembershipManager.MapTier(TierMap, ["unknown"]), Is.Null); + Assert.That(PatreonMembershipManager.MapTier(TierMap, []), Is.Null); + }); + } + + [Test] + public void TestMapTierSkipsDisabledTiers() + { + Assert.Multiple(() => + { + Assert.That(PatreonMembershipManager.MapTier(TierMap, ["2"], ["2"]), Is.Null); + Assert.That(PatreonMembershipManager.MapTier(TierMap, ["2", "1"], ["2"]), Is.EqualTo("Assistant")); + Assert.That(PatreonMembershipManager.MapTier(TierMap, ["2"], ["1"]), Is.EqualTo("Captain")); + }); + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonSecretProtector.cs b/SS14.Web.Tests/Patreon/TestPatreonSecretProtector.cs new file mode 100644 index 00000000..13a98569 --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonSecretProtector.cs @@ -0,0 +1,23 @@ +using Microsoft.AspNetCore.DataProtection; +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonSecretProtector))] +public sealed class TestPatreonSecretProtector +{ + [Test] + public void TestRoundTrip() + { + var protector = new PatreonSecretProtector(new EphemeralDataProtectionProvider()); + + var protectedText = protector.Protect("secret"); + + Assert.Multiple(() => + { + Assert.That(protectedText, Is.Not.EqualTo("secret")); + Assert.That(protector.Unprotect(protectedText), Is.EqualTo("secret")); + }); + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonServerToken.cs b/SS14.Web.Tests/Patreon/TestPatreonServerToken.cs new file mode 100644 index 00000000..b4bb7372 --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonServerToken.cs @@ -0,0 +1,34 @@ +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonServerToken))] +public sealed class TestPatreonServerToken +{ + [Test] + public void TestGenerateIsUrlSafeAndUnique() + { + var a = PatreonServerToken.Generate(); + var b = PatreonServerToken.Generate(); + + Assert.Multiple(() => + { + Assert.That(a, Is.Not.EqualTo(b)); + Assert.That(a, Does.Match("^[A-Za-z0-9_-]+$")); + }); + } + + [Test] + public void TestHash() + { + var hash = PatreonServerToken.Hash("token"); + + Assert.Multiple(() => + { + Assert.That(hash, Has.Length.EqualTo(64)); + Assert.That(PatreonServerToken.Hash("token"), Is.EqualTo(hash)); + Assert.That(PatreonServerToken.Hash("Token"), Is.Not.EqualTo(hash)); + }); + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonTierMapping.cs b/SS14.Web.Tests/Patreon/TestPatreonTierMapping.cs new file mode 100644 index 00000000..3c75c6f3 --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonTierMapping.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonTierMapping))] +public sealed class TestPatreonTierMapping +{ + [Test] + public void TestWithRewardNewTier() + { + var (map, names) = PatreonTierMapping.WithReward( + new Dictionary(), + new Dictionary(), + "1", + "Captain"); + + Assert.Multiple(() => + { + Assert.That(map, Is.EqualTo(new Dictionary { ["1"] = "Captain" })); + Assert.That(names, Is.EqualTo(new Dictionary { ["Captain"] = "Captain" })); + }); + } + + [Test] + public void TestWithRewardKeepsOldDisplayName() + { + var map = new Dictionary { ["1"] = "Assistant" }; + var names = new Dictionary { ["Assistant"] = "Greytide" }; + + var (newMap, newNames) = PatreonTierMapping.WithReward(map, names, "1", "Captain"); + + Assert.Multiple(() => + { + Assert.That(newMap["1"], Is.EqualTo("Captain")); + Assert.That(newNames["Captain"], Is.EqualTo("Greytide")); + }); + } + + [Test] + public void TestWithRewardKeepsExistingDisplayName() + { + var map = new Dictionary { ["1"] = "Assistant" }; + var names = new Dictionary { ["Assistant"] = "Assistant", ["Captain"] = "Comdom" }; + + var (_, newNames) = PatreonTierMapping.WithReward(map, names, "1", "Captain"); + + Assert.That(newNames["Captain"], Is.EqualTo("Comdom")); + } + + [Test] + public void TestWithRewardDoesNotMutateInput() + { + var map = new Dictionary { ["1"] = "Assistant" }; + var names = new Dictionary(); + + var (newMap, newNames) = PatreonTierMapping.WithReward(map, names, "1", "Captain"); + + Assert.Multiple(() => + { + Assert.That(newMap, Is.Not.SameAs(map)); + Assert.That(newNames, Is.Not.SameAs(names)); + Assert.That(map["1"], Is.EqualTo("Assistant")); + Assert.That(names, Is.Empty); + }); + } + + [Test] + public void TestWithNewTiers() + { + var map = new Dictionary { ["1"] = "Assistant" }; + var names = new Dictionary { ["Assistant"] = "Greytide" }; + var tiers = new Dictionary { ["1"] = "Renamed", ["2"] = "Captain" }; + + var (newMap, newNames, added) = PatreonTierMapping.WithNewTiers(map, names, tiers); + + Assert.Multiple(() => + { + Assert.That(added, Is.EqualTo(1)); + Assert.That(newMap["1"], Is.EqualTo("Assistant")); + Assert.That(newMap["2"], Is.EqualTo("Captain")); + Assert.That(newNames["Assistant"], Is.EqualTo("Greytide")); + Assert.That(newNames["Captain"], Is.EqualTo("Captain")); + Assert.That(map, Has.Count.EqualTo(1)); + }); + } +} diff --git a/SS14.Web.Tests/Patreon/TestPatreonWebhookSignature.cs b/SS14.Web.Tests/Patreon/TestPatreonWebhookSignature.cs new file mode 100644 index 00000000..1c64f70e --- /dev/null +++ b/SS14.Web.Tests/Patreon/TestPatreonWebhookSignature.cs @@ -0,0 +1,52 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using NUnit.Framework; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Tests.Patreon; + +[TestFixture, TestOf(typeof(PatreonWebhookSignature))] +public sealed class TestPatreonWebhookSignature +{ + private const string Secret = "4"; + private static readonly byte[] Body = """{"data": {}}"""u8.ToArray(); + + private static string Sign(byte[] body, string secret) + { + return Convert.ToHexString(HMACMD5.HashData(Encoding.UTF8.GetBytes(secret), body)).ToLowerInvariant(); + } + + [Test] + public void TestValid() + { + Assert.That(PatreonWebhookSignature.Verify(Body, Secret, Sign(Body, Secret)), Is.True); + } + + [Test] + public void TestWrongSecret() + { + Assert.That(PatreonWebhookSignature.Verify(Body, Secret, Sign(Body, "67")), Is.False); + } + + [Test] + public void TestTamperedBody() + { + var signature = Sign(Body, Secret); + var tampered = """{"data": {"x": 1}}"""u8.ToArray(); + + Assert.That(PatreonWebhookSignature.Verify(tampered, Secret, signature), Is.False); + } + + [Test] + public void TestMalformedSignature() + { + Assert.Multiple(() => + { + Assert.That(PatreonWebhookSignature.Verify(Body, Secret, null), Is.False); + Assert.That(PatreonWebhookSignature.Verify(Body, Secret, ""), Is.False); + Assert.That(PatreonWebhookSignature.Verify(Body, Secret, "abc"), Is.False); + Assert.That(PatreonWebhookSignature.Verify(Body, Secret, "zzzz"), Is.False); + }); + } +} diff --git a/SS14.Web.Tests/TestPatreonConnection.cs b/SS14.Web.Tests/TestPatreonConnection.cs deleted file mode 100644 index 57bcd923..00000000 --- a/SS14.Web.Tests/TestPatreonConnection.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Text.Json; -using NUnit.Framework; - -namespace SS14.Web.Tests; - -public class TestPatreonConnection -{ - [Test] - public void TestParseTiers() - { - const string json = @" -{ - ""data"": { - ""attributes"": {}, - ""id"": ""1"", - ""relationships"": { - ""memberships"": { - ""data"": [ - { - ""id"": ""6f12afba-4432-4e53-b2e7-721486e66bf3"", - ""type"": ""member"" - } - ] - } - }, - ""type"": ""user"" - }, - ""included"": [ - { - ""attributes"": {}, - ""id"": ""6f12afba-4432-4e53-b2e7-721486e66bf3"", - ""relationships"": { - ""currently_entitled_tiers"": { - ""data"": [ - { - ""id"": ""2"", - ""type"": ""tier"" - } - ] - } - }, - ""type"": ""member"" - }, - { - ""attributes"": {}, - ""id"": ""2"", - ""type"": ""tier"" - } - ] -}"; - using var doc = JsonDocument.Parse(json); - var tiers = PatreonConnectionHandler.ParseTiers(doc.RootElement); - - Assert.That(tiers, Is.EquivalentTo(new[] {"2"})); - } -} \ No newline at end of file diff --git a/SS14.Web/Areas/Admin/Pages/Index.cshtml b/SS14.Web/Areas/Admin/Pages/Index.cshtml index 79dc445f..646a317e 100644 --- a/SS14.Web/Areas/Admin/Pages/Index.cshtml +++ b/SS14.Web/Areas/Admin/Pages/Index.cshtml @@ -19,6 +19,7 @@ { Users OAuth Clients + Patreon } @if ((await AuthorizationService.AuthorizeAsync(User, AuthConstants.PolicyServerHubAdmin)).Succeeded) diff --git a/SS14.Web/Areas/Admin/Pages/Patreon/Campaign.cshtml b/SS14.Web/Areas/Admin/Pages/Patreon/Campaign.cshtml new file mode 100644 index 00000000..60191a37 --- /dev/null +++ b/SS14.Web/Areas/Admin/Pages/Patreon/Campaign.cshtml @@ -0,0 +1,133 @@ +@page "{id:int?}" +@model SS14.Web.Areas.Admin.Pages.Patreon.Campaign + +@{ + ViewData["Title"] = $"Patreon Campaign: {Model.Title}"; +} + + + + + +
Options
+
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+
+ + +
+
+
+ +
+
+
+ + +
+
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ + +
+ +@if (Model.DbCampaign?.Id is { } id and not 0) +{ +
Status
+ +
+
Webhook URL
+
/hook/patreon/@Model.DbCampaign.Key
+
Webhook secret
+
@(Model.DbCampaign.WebhookSecret == null ? "Not set" : "Set")
+
Access token
+
@(Model.DbCampaign.AccessToken == null ? "Not set" : "Set")
+
Owner
+
+ @if (Model.DbCampaign.OwnerUserId is { } ownerId) + { + @ownerId + } + else + { + Added by an admin + } +
+
Server token
+
@(Model.DbCampaign.ServerTokenHash == null ? "Not set" : "Set")
+
Members
+
@Model.MemberCount
+
Last import
+
@(Model.DbCampaign.LastFullSyncAt?.ToUniversalTime().ToString("u") ?? "Never")
+
Last webhook received
+
@(Model.DbCampaign.LastWebhookAt?.ToUniversalTime().ToString("u") ?? "Never")
+
+ +
Actions
+ +
+ +
+
+ +
+
+ +
+} diff --git a/SS14.Web/Areas/Admin/Pages/Patreon/Campaign.cshtml.cs b/SS14.Web/Areas/Admin/Pages/Patreon/Campaign.cshtml.cs new file mode 100644 index 00000000..70aff2ef --- /dev/null +++ b/SS14.Web/Areas/Admin/Pages/Patreon/Campaign.cshtml.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using SS14.Auth.Shared.Data; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Areas.Admin.Pages.Patreon; + +public class Campaign : PageModel +{ + private static readonly Regex KeyRegex = new("^[a-z0-9-]+$"); + + private readonly ApplicationDbContext _dbContext; + private readonly PatreonSecretProtector _secretProtector; + private readonly PatreonImporter _importer; + private readonly PatreonMembershipManager _membershipManager; + private readonly ILogger _logger; + + public Campaign( + ApplicationDbContext dbContext, + PatreonSecretProtector secretProtector, + PatreonImporter importer, + PatreonMembershipManager membershipManager, + ILogger logger) + { + _dbContext = dbContext; + _secretProtector = secretProtector; + _importer = importer; + _membershipManager = membershipManager; + _logger = logger; + } + + [BindProperty] public InputModel Input { get; set; } + + [TempData] public string StatusMessage { get; set; } + + public PatreonCampaign DbCampaign { get; set; } + public int MemberCount { get; set; } + + public string Title => DbCampaign?.Name ?? "New campaign"; + + public sealed class InputModel + { + [Display(Name = "Key (lowercase letters, numbers and dashes)")] + public string Key { get; set; } + + public string Name { get; set; } + + [Display(Name = "Patreon campaign ID")] + public string PatreonCampaignId { get; set; } + + [Display(Name = "First party")] + public bool IsFirstParty { get; set; } + + public bool Enabled { get; set; } + + [Display(Name = "Tier map (one per line, tier ID=reward)")] + public string TierMap { get; set; } + + [Display(Name = "Tier names (one per line, reward=display name)")] + public string TierNames { get; set; } + + [Display(Name = "Disabled tier IDs (one per line)")] + public string DisabledTierIds { get; set; } + + [Display(Name = "Webhook secret (leave empty to keep)")] + public string WebhookSecret { get; set; } + + [Display(Name = "Access token (leave empty to keep)")] + public string AccessToken { get; set; } + + [Display(Name = "Refresh token (leave empty to keep)")] + public string RefreshToken { get; set; } + } + + public async Task OnGetAsync(int? id) + { + if (id == null) + { + Input = new InputModel { Enabled = true }; + return Page(); + } + + if (!await LoadAsync(id.Value)) + return NotFound("Campaign not found"); + + Input = new InputModel + { + Key = DbCampaign.Key, + Name = DbCampaign.Name, + PatreonCampaignId = DbCampaign.PatreonCampaignId, + IsFirstParty = DbCampaign.IsFirstParty, + Enabled = DbCampaign.Enabled, + TierMap = FormatPairs(DbCampaign.TierMap), + TierNames = FormatPairs(DbCampaign.TierNames), + DisabledTierIds = string.Join("\n", DbCampaign.DisabledTierIds) + }; + + return Page(); + } + + public async Task OnPostSaveAsync(int? id) + { + if (id == null) + { + DbCampaign = new PatreonCampaign(); + } + else if (!await LoadAsync(id.Value)) + { + return NotFound("Campaign not found"); + } + + if (!KeyRegex.IsMatch(Input.Key ?? "")) + ModelState.AddModelError("Input.Key", "Invalid key."); + + if (string.IsNullOrWhiteSpace(Input.Name)) + ModelState.AddModelError("Input.Name", "Name is required."); + + if (string.IsNullOrWhiteSpace(Input.PatreonCampaignId)) + ModelState.AddModelError("Input.PatreonCampaignId", "Campaign ID is required."); + + if (!TryParsePairs(Input.TierMap, out var tierMap)) + ModelState.AddModelError("Input.TierMap", "Invalid tier map."); + + if (!TryParsePairs(Input.TierNames, out var tierNames)) + ModelState.AddModelError("Input.TierNames", "Invalid tier names."); + + var otherCampaigns = _dbContext.PatreonCampaigns.Where(c => c.Id != DbCampaign.Id); + + if (await otherCampaigns.AnyAsync(c => c.Key == Input.Key)) + ModelState.AddModelError("Input.Key", "Key is already in use."); + + if (await otherCampaigns.AnyAsync(c => c.PatreonCampaignId == Input.PatreonCampaignId)) + ModelState.AddModelError("Input.PatreonCampaignId", "Campaign is already added."); + + if (Input.IsFirstParty && await otherCampaigns.AnyAsync(c => c.IsFirstParty)) + ModelState.AddModelError("Input.IsFirstParty", "Another campaign is already first party."); + + if (!ModelState.IsValid) + { + MemberCount = await _dbContext.PatreonMemberships.CountAsync(m => m.CampaignId == DbCampaign.Id); + return Page(); + } + + DbCampaign.Key = Input.Key; + DbCampaign.Name = Input.Name; + DbCampaign.PatreonCampaignId = Input.PatreonCampaignId; + DbCampaign.IsFirstParty = Input.IsFirstParty; + DbCampaign.Enabled = Input.Enabled; + DbCampaign.TierMap = tierMap; + DbCampaign.TierNames = tierNames; + DbCampaign.DisabledTierIds = (Input.DisabledTierIds ?? "") + .Replace("\r", "") + .Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Distinct() + .ToArray(); + + if (!string.IsNullOrEmpty(Input.WebhookSecret)) + DbCampaign.WebhookSecret = _secretProtector.Protect(Input.WebhookSecret); + + if (!string.IsNullOrEmpty(Input.AccessToken)) + { + DbCampaign.AccessToken = _secretProtector.Protect(Input.AccessToken); + // Expiry is unknown for pasted tokens, so they are never refreshed automatically. + DbCampaign.TokenExpiresAt = null; + } + + if (!string.IsNullOrEmpty(Input.RefreshToken)) + DbCampaign.RefreshToken = _secretProtector.Protect(Input.RefreshToken); + + if (id == null) + _dbContext.PatreonCampaigns.Add(DbCampaign); + + await _dbContext.SaveChangesAsync(); + + // Memberships store their mapped tier, so they need updating when the map changed. + await _membershipManager.RemapTiersAsync(DbCampaign); + + StatusMessage = "Changes saved"; + + return RedirectToPage(new { id = DbCampaign.Id }); + } + + public async Task OnPostImportAsync(int id) + { + if (!await LoadAsync(id)) + return NotFound("Campaign not found"); + + try + { + var count = await _importer.ImportAsync(DbCampaign); + StatusMessage = $"Imported {count} members"; + } + catch (Exception e) + { + _logger.LogError(e, "Importing members of Patreon campaign {Campaign} failed", DbCampaign.Key); + StatusMessage = $"Error: import failed ({e.Message})"; + } + + return RedirectToPage(new { id }); + } + + public async Task OnPostGenerateTokenAsync(int id) + { + if (!await LoadAsync(id)) + return NotFound("Campaign not found"); + + var token = PatreonServerToken.Generate(); + DbCampaign.ServerTokenHash = PatreonServerToken.Hash(token); + await _dbContext.SaveChangesAsync(); + + StatusMessage = $"Server token generated, it will not be shown again. Value: {token}"; + + return RedirectToPage(new { id }); + } + + public async Task OnPostDeleteAsync(int id) + { + if (!await LoadAsync(id)) + return NotFound("Campaign not found"); + + _dbContext.PatreonCampaigns.Remove(DbCampaign); + await _dbContext.SaveChangesAsync(); + + TempData["StatusMessage"] = "Campaign deleted"; + + return RedirectToPage("./Index"); + } + + private async Task LoadAsync(int id) + { + DbCampaign = await _dbContext.PatreonCampaigns.SingleOrDefaultAsync(c => c.Id == id); + if (DbCampaign == null) + return false; + + MemberCount = await _dbContext.PatreonMemberships.CountAsync(m => m.CampaignId == id); + return true; + } + + private static string FormatPairs(Dictionary pairs) + { + return string.Join("\n", pairs.Select(p => $"{p.Key}={p.Value}")); + } + + private static bool TryParsePairs(string text, out Dictionary pairs) + { + pairs = new Dictionary(); + + foreach (var line in (text ?? "").Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries)) + { + var split = line.Split('=', 2); + if (split.Length != 2 || split[0].Trim() == "" || split[1].Trim() == "") + return false; + + pairs[split[0].Trim()] = split[1].Trim(); + } + + return true; + } +} diff --git a/SS14.Web/Areas/Admin/Pages/Patreon/Index.cshtml b/SS14.Web/Areas/Admin/Pages/Patreon/Index.cshtml new file mode 100644 index 00000000..9099f628 --- /dev/null +++ b/SS14.Web/Areas/Admin/Pages/Patreon/Index.cshtml @@ -0,0 +1,57 @@ +@page +@model SS14.Web.Areas.Admin.Pages.Patreon.Index + +@{ + ViewData["Title"] = "Patreon Campaigns"; +} + + +@if (TempData.ContainsKey("StatusMessage")) +{ + +} + +New Campaign + + + + + + + + + + + + + + @foreach (var (campaign, members) in Model.Campaigns) + { + + + + + + + + + } + +
KeyNameMembersLast importLast webhook
@campaign.Key + @campaign.Name + @if (campaign.IsFirstParty) + { + First party + } + @if (!campaign.Enabled) + { + Disabled + } + @members@(campaign.LastFullSyncAt?.ToUniversalTime().ToString("u") ?? "Never")@(campaign.LastWebhookAt?.ToUniversalTime().ToString("u") ?? "Never") + View +
diff --git a/SS14.Web/Areas/Admin/Pages/Patreon/Index.cshtml.cs b/SS14.Web/Areas/Admin/Pages/Patreon/Index.cshtml.cs new file mode 100644 index 00000000..dd07db2d --- /dev/null +++ b/SS14.Web/Areas/Admin/Pages/Patreon/Index.cshtml.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using SS14.Auth.Shared.Data; + +namespace SS14.Web.Areas.Admin.Pages.Patreon; + +public class Index : PageModel +{ + private readonly ApplicationDbContext _dbContext; + + public List Campaigns { get; set; } + + public Index(ApplicationDbContext dbContext) + { + _dbContext = dbContext; + } + + public sealed record CampaignRow(PatreonCampaign Campaign, int Members); + + public async Task OnGetAsync() + { + var campaigns = await _dbContext.PatreonCampaigns + .OrderBy(c => c.Name) + .Select(c => new CampaignRow(c, c.Memberships.Count)) + .ToListAsync(); + + Campaigns = campaigns; + } +} diff --git a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs index 71145176..daae02ce 100644 --- a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs +++ b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs @@ -17,6 +17,7 @@ public static class ManageNavPages public const string PersonalData = "PersonalData"; public const string TwoFactorAuthentication = "TwoFactorAuthentication"; public const string ManagePatreon = "ManagePatreon"; + public const string ManagePatreonCampaigns = "ManagePatreonCampaigns"; public const string Developer = "Developer"; public static string IndexNavClass(ViewContext viewContext) @@ -44,6 +45,7 @@ public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication); public static string PatreonNavClass(ViewContext viewContext) => PageNavClass(viewContext, ManagePatreon); + public static string PatreonCampaignsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ManagePatreonCampaigns); public static string DeveloperNavClass(ViewContext viewContext) => PageNavClass(viewContext, Developer); private static string PageNavClass(ViewContext viewContext, string page) diff --git a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml index cd604d2b..20e462a3 100644 --- a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml +++ b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml @@ -7,6 +7,7 @@ }

@ViewData["Title"]

+
@@ -26,7 +27,35 @@ }

- + } + + } else @@ -35,6 +64,14 @@ If you are one of our patrons, you can link your Patreon account with your Space Station 14 account here to receive recognition on servers.

+

+ Linking also lets servers of other communities whose Patreon you support see your membership in + their campaign. You can hide it from individual communities after linking. +

+

+ Patreon will ask you to share your Patreon identity info. We only keep your Patreon user ID, which + is used to match you to your memberships. We do not store your name or email address from Patreon. +

} diff --git a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml.cs b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml.cs index 43ec0e6d..f261ce64 100644 --- a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml.cs +++ b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreon.cshtml.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; @@ -23,6 +25,18 @@ public class ManagePatreon : PageModel public bool PatreonLinked { get; private set; } public string PatreonTier { get; private set; } + [BindProperty] public List Sharing { get; set; } = new(); + + [TempData] public string StatusMessage { get; set; } + + public sealed class SharingInput + { + public int CampaignId { get; set; } + public string CampaignName { get; set; } + public bool Share { get; set; } + public string Tier { get; set; } + } + public ManagePatreon( SpaceUserManager userManager, ILogger logger, @@ -49,18 +63,77 @@ public async Task OnGet() PatreonLinked = patron != null; - if (patron?.CurrentTier is { } t) + if (patron != null) { - if (_cfg.Value.TierNames.TryGetValue(t, out var name)) + var membership = await _db.PatreonMemberships + .Where(m => m.Campaign.IsFirstParty && m.Campaign.Enabled && m.PatreonUserId == patron.PatreonId) + .Select(m => new { m.CurrentTier, m.Campaign.TierNames }) + .SingleOrDefaultAsync(); + + if (membership?.CurrentTier is { } t) { - PatreonTier = name; + PatreonTier = membership.TierNames.GetValueOrDefault(t, t); } - else + + var communities = await _db.PatreonMemberships + .Where(m => !m.Campaign.IsFirstParty && m.PatreonUserId == patron.PatreonId) + .OrderBy(m => m.Campaign.Name) + .Select(m => new + { + m.CampaignId, + CampaignName = m.Campaign.Name, + m.Hidden, + m.CurrentTier, + m.Campaign.TierNames + }) + .ToListAsync(); + + Sharing = communities + .Select(m => new SharingInput + { + CampaignId = m.CampaignId, + CampaignName = m.CampaignName, + Share = !m.Hidden, + Tier = m.CurrentTier == null ? null : m.TierNames.GetValueOrDefault(m.CurrentTier, m.CurrentTier) + }) + .ToList(); + } + + return Page(); + } + + public async Task OnPostSharingAsync() + { + var user = await _userManager.GetUserAsync(User); + if (user == null) + { + return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); + } + + var patron = await _db.Patrons.SingleOrDefaultAsync(p => p.SpaceUserId == user.Id); + if (patron == null) + { + return RedirectToPage(); + } + + // Only touch the user's own memberships, the campaign IDs come from the form + var memberships = await _db.PatreonMemberships + .Where(m => !m.Campaign.IsFirstParty && m.PatreonUserId == patron.PatreonId) + .ToListAsync(); + + foreach (var membership in memberships) + { + var input = Sharing.FirstOrDefault(s => s.CampaignId == membership.CampaignId); + if (input != null) { - PatreonTier = t; + membership.Hidden = !input.Share; } } - return Page(); + + await _db.SaveChangesAsync(); + + StatusMessage = "Sharing preferences saved."; + return RedirectToPage(); } public async Task OnPostUnlinkPatreonAsync() @@ -101,4 +174,4 @@ public async Task OnPostLinkPatreonAsync() RedirectUri = redirect }, "Patreon"); } -} \ No newline at end of file +} diff --git a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreonCampaigns.cshtml b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreonCampaigns.cshtml new file mode 100644 index 00000000..05e857f1 --- /dev/null +++ b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreonCampaigns.cshtml @@ -0,0 +1,135 @@ +@page +@model ManagePatreonCampaigns + +@{ + ViewData["Title"] = "Patreon campaigns"; + ViewData["ActivePage"] = ManageNavPages.ManagePatreonCampaigns; +} + +

@ViewData["Title"]

+ +@if (Model.ResultMessage != null) +{ + +} + +
+
+

+ If you run a community with its own Patreon campaign, you can connect it here so your servers + can recognize your patrons. You authorize us to read your campaign's members and to set up a webhook + for membership changes, and you can revoke that on Patreon at any time. Players who linked their Patreon + account can hide their membership from your servers. +

+ +
What we ask Patreon for, and why
+

When you connect, Patreon shows you a list of permissions. Here is what each one is used for:

+
    +
  • + View your Patreon identity info (Patreon always includes this). + We don't use or store it. It is only needed to complete the sign-in. +
  • +
  • + View your campaign: so we can read your campaign's name and tiers, and to identify it. +
  • +
  • + View your campaign's members: so we can import your current patrons, and know who + your patrons are when they play on your servers. We store each patron's Patreon user ID, patron status + and tier. We do not ask for or store patrons' names or email addresses. +
  • +
  • + Manage your campaign's webhooks: so we can set up one webhook that tells us when + someone joins, changes or ends their pledge, keeping the data current. +
  • +
+

+ Your servers get a token from us to ask whether a player is a patron of your campaign. They only ever see + your campaign's data, never other campaigns a player supports, and players can choose to hide their + membership from you. You can revoke our access at any time in your Patreon account's connected apps, + or by disconnecting the campaign here. +

+ + @if (Model.Campaigns.Count == 0) + { +
+ +
+ } + else + { +

Each account can have one campaign connected. Disconnect it to connect a different one.

+ } + + @foreach (var (campaign, members) in Model.Campaigns) + { +
@campaign.Name
+
+
Status
+
@(campaign.Enabled ? "Active" : "Pending, members have not been imported yet")
+
Members
+
@members
+
Last import
+
@(campaign.LastFullSyncAt?.ToUniversalTime().ToString("u") ?? "Never")
+
Last webhook received
+
@(campaign.LastWebhookAt?.ToUniversalTime().ToString("u") ?? "Never")
+
Server token
+
@(campaign.ServerTokenHash == null ? "Not generated" : "Generated")
+
+ +
Tiers
+

+ The reward name is what your servers receive for a patron of that tier. It starts out as the tier's + title, change it if your servers expect something else. Patrons on a disabled tier are treated as + having no tier. +

+
+ + + + + + + + + + @{ var i = 0; } + @foreach (var (tierId, reward) in campaign.TierMap.OrderBy(t => t.Value)) + { + + + + + + i++; + } + +
TierReward nameEnabled
@campaign.TierNames.GetValueOrDefault(reward, reward) + + + + +
+ + +
+ +
Actions
+
+
+ +
+
+ +
+
+ +
+
+ } +
+
diff --git a/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreonCampaigns.cshtml.cs b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreonCampaigns.cshtml.cs new file mode 100644 index 00000000..a6e2b6c6 --- /dev/null +++ b/SS14.Web/Areas/Identity/Pages/Account/Manage/ManagePatreonCampaigns.cshtml.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using SS14.Auth.Shared.Data; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web.Areas.Identity.Pages.Account.Manage; + +public class ManagePatreonCampaigns : PageModel +{ + private const int MaxRewardLength = 64; + + private static readonly Dictionary ResultMessages = new() + { + [PatreonCampaignConnectHandler.ResultConnected] = "Your campaign is connected and its members were imported.", + [PatreonCampaignConnectHandler.ResultNoCampaign] = "That Patreon account has no campaign.", + [PatreonCampaignConnectHandler.ResultTaken] = "That campaign is already connected to another account.", + [PatreonCampaignConnectHandler.ResultLimit] = + "Your account already has a campaign connected. Disconnect it first to connect a different one.", + [PatreonCampaignConnectHandler.ResultApiError] = "Patreon returned an error, please try again later.", + [PatreonCampaignConnectHandler.ResultImportFailed] = + "Your campaign was connected but importing its members failed. You can retry below.", + [PatreonCampaignConnectHandler.ResultNotConfigured] = "Connecting campaigns is not available right now." + }; + + private readonly SpaceUserManager _userManager; + private readonly ApplicationDbContext _db; + private readonly PatreonImporter _importer; + private readonly PatreonMembershipManager _membershipManager; + private readonly ILogger _logger; + + public ManagePatreonCampaigns( + SpaceUserManager userManager, + ApplicationDbContext db, + PatreonImporter importer, + PatreonMembershipManager membershipManager, + ILogger logger) + { + _userManager = userManager; + _db = db; + _importer = importer; + _membershipManager = membershipManager; + _logger = logger; + } + + [BindProperty(SupportsGet = true)] public string Result { get; set; } + + [BindProperty] public List Tiers { get; set; } = new(); + + public sealed class TierInput + { + public string TierId { get; set; } + public string Reward { get; set; } + public bool Enabled { get; set; } + } + + [TempData] public string StatusMessage { get; set; } + + public List Campaigns { get; private set; } = new(); + + public sealed record CampaignRow(PatreonCampaign Campaign, int Members); + + public string ResultMessage => Result != null && ResultMessages.TryGetValue(Result, out var m) ? m : null; + + public async Task OnGetAsync() + { + var user = await _userManager.GetUserAsync(User); + if (user == null) + { + return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); + } + + Campaigns = await _db.PatreonCampaigns + .Where(c => c.OwnerUserId == user.Id) + .OrderBy(c => c.Name) + .Select(c => new CampaignRow(c, c.Memberships.Count)) + .ToListAsync(); + + return Page(); + } + + public async Task OnPostConnectAsync() + { + var user = await _userManager.GetUserAsync(User); + if (user == null) + { + return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); + } + + if (await _db.PatreonCampaigns.AnyAsync(c => c.OwnerUserId == user.Id)) + { + return RedirectToPage(new { result = PatreonCampaignConnectHandler.ResultLimit }); + } + + return Challenge(new AuthenticationProperties + { + Items = + { + ["SS14UserId"] = user.Id.ToString(), + }, + RedirectUri = Url.Page("./ManagePatreonCampaigns") + }, "PatreonCreator"); + } + + public async Task OnPostRetryImportAsync(int id) + { + var campaign = await GetOwnedCampaignAsync(id); + if (campaign == null) + return NotFound(); + + try + { + var count = await _importer.ImportAsync(campaign); + campaign.Enabled = true; + await _db.SaveChangesAsync(); + StatusMessage = $"Imported {count} members."; + } + catch (Exception e) + { + _logger.LogWarning(e, "Retrying import of Patreon campaign {Campaign} failed", campaign.Key); + StatusMessage = "Error: importing members failed."; + } + + return RedirectToPage(); + } + + public async Task OnPostSaveTiersAsync(int id) + { + var campaign = await GetOwnedCampaignAsync(id); + if (campaign == null) + return NotFound(); + + var tierMap = campaign.TierMap; + var tierNames = campaign.TierNames; + var disabledTierIds = new HashSet(campaign.DisabledTierIds); + foreach (var input in Tiers) + { + // The tier IDs come from the form, only accept ones the campaign has. + if (input.TierId == null || !tierMap.ContainsKey(input.TierId)) + continue; + + if (input.Enabled) + disabledTierIds.Remove(input.TierId); + else + disabledTierIds.Add(input.TierId); + + var reward = input.Reward?.Trim(); + if (string.IsNullOrEmpty(reward) || reward.Length > MaxRewardLength) + { + StatusMessage = $"Error: reward names must be 1 to {MaxRewardLength} characters."; + return RedirectToPage(); + } + + (tierMap, tierNames) = PatreonTierMapping.WithReward(tierMap, tierNames, input.TierId, reward); + } + + campaign.TierMap = tierMap; + campaign.TierNames = tierNames; + campaign.DisabledTierIds = disabledTierIds.ToArray(); + await _membershipManager.RemapTiersAsync(campaign); + + StatusMessage = "Tiers saved."; + + return RedirectToPage(); + } + + public async Task OnPostRefreshTiersAsync(int id) + { + var campaign = await GetOwnedCampaignAsync(id); + if (campaign == null) + return NotFound(); + + try + { + var added = await _importer.RefreshTiersAsync(campaign); + StatusMessage = added == 0 ? "No new tiers found." : $"Added {added} new tiers."; + } + catch (Exception e) + { + _logger.LogWarning(e, "Refreshing tiers of Patreon campaign {Campaign} failed", campaign.Key); + StatusMessage = "Error: refreshing tiers failed."; + } + + return RedirectToPage(); + } + + public async Task OnPostRegenerateTokenAsync(int id) + { + var campaign = await GetOwnedCampaignAsync(id); + if (campaign == null) + return NotFound(); + + var token = PatreonServerToken.Generate(); + campaign.ServerTokenHash = PatreonServerToken.Hash(token); + await _db.SaveChangesAsync(); + + StatusMessage = $"New server token, it will not be shown again: {token}"; + + return RedirectToPage(); + } + + public async Task OnPostDisconnectAsync(int id) + { + var campaign = await GetOwnedCampaignAsync(id); + if (campaign == null) + return NotFound(); + + _db.PatreonCampaigns.Remove(campaign); + await _db.SaveChangesAsync(); + + StatusMessage = "Campaign disconnected. You can also remove the webhook on Patreon."; + + return RedirectToPage(); + } + + private async Task GetOwnedCampaignAsync(int id) + { + var user = await _userManager.GetUserAsync(User); + if (user == null) + return null; + + return await _db.PatreonCampaigns.SingleOrDefaultAsync(c => c.Id == id && c.OwnerUserId == user.Id); + } +} diff --git a/SS14.Web/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml b/SS14.Web/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml index ff44670e..2a26c89d 100644 --- a/SS14.Web/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml +++ b/SS14.Web/Areas/Identity/Pages/Account/Manage/_ManageNav.cshtml @@ -15,5 +15,6 @@ + diff --git a/SS14.Web/PatreonCampaignConnectHandler.cs b/SS14.Web/PatreonCampaignConnectHandler.cs new file mode 100644 index 00000000..6c06fd88 --- /dev/null +++ b/SS14.Web/PatreonCampaignConnectHandler.cs @@ -0,0 +1,179 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SS14.Auth.Shared.Config; +using SS14.Auth.Shared.Data; +using SS14.Auth.Shared.Patreon; + +namespace SS14.Web; + +public sealed class PatreonCampaignConnectHandler +{ + public const string ResultConnected = "connected"; + public const string ResultNoCampaign = "no-campaign"; + public const string ResultTaken = "taken"; + public const string ResultLimit = "limit"; + public const string ResultApiError = "api-error"; + public const string ResultImportFailed = "import-failed"; + public const string ResultNotConfigured = "not-configured"; + + private readonly SpaceUserManager _userManager; + private readonly ApplicationDbContext _db; + private readonly PatreonApiClient _api; + private readonly PatreonImporter _importer; + private readonly PatreonSecretProtector _secretProtector; + private readonly IOptions _patreonCfg; + private readonly ILogger _logger; + + public PatreonCampaignConnectHandler( + SpaceUserManager userManager, + ApplicationDbContext db, + PatreonApiClient api, + PatreonImporter importer, + PatreonSecretProtector secretProtector, + IOptions patreonCfg, + ILogger logger) + { + _userManager = userManager; + _db = db; + _api = api; + _importer = importer; + _secretProtector = secretProtector; + _patreonCfg = patreonCfg; + _logger = logger; + } + + public async Task HookReceivedTicket(TicketReceivedContext context) + { + var guid = context.Properties.Items["SS14UserId"]!; + var user = await _userManager.FindByIdAsync(guid); + + if (user == null) + { + throw new InvalidOperationException("Unable to find user??"); + } + + var result = await ConnectAsync(context.Properties, user); + + if (context.ReturnUri != null) + { + context.HttpContext.Response.Redirect(QueryHelpers.AddQueryString(context.ReturnUri, "result", result)); + } + + context.HandleResponse(); + } + + private async Task ConnectAsync(AuthenticationProperties properties, SpaceUser user) + { + var webhookBaseUrl = _patreonCfg.Value.WebhookBaseUrl; + var accessToken = properties.GetTokenValue("access_token"); + var refreshToken = properties.GetTokenValue("refresh_token"); + if (string.IsNullOrEmpty(webhookBaseUrl) || accessToken == null || refreshToken == null) + return ResultNotConfigured; + + PatreonCampaignInfo info; + try + { + var campaigns = await _api.GetCampaignsAsync(accessToken); + info = campaigns.FirstOrDefault(); + } + catch (HttpRequestException e) + { + _logger.LogWarning(e, "Listing campaigns of connecting creator failed"); + return ResultApiError; + } + + if (info == null) + return ResultNoCampaign; + + var campaign = await _db.PatreonCampaigns.SingleOrDefaultAsync(c => c.PatreonCampaignId == info.Id); + if (campaign != null && campaign.OwnerUserId != user.Id) + return ResultTaken; + + var isNew = campaign == null; + if (isNew && await _db.PatreonCampaigns.AnyAsync(c => c.OwnerUserId == user.Id)) + return ResultLimit; + + campaign ??= new PatreonCampaign + { + Key = await MakeUniqueKeyAsync(info.Name), + PatreonCampaignId = info.Id, + Name = info.Name, + TierMap = info.Tiers.ToDictionary(t => t.Key, t => t.Value), + TierNames = info.Tiers.Values.Distinct().ToDictionary(t => t, t => t), + OwnerUserId = user.Id, + Enabled = false + }; + + if (campaign.WebhookSecret == null) + { + try + { + var uri = $"{webhookBaseUrl.TrimEnd('/')}/hook/patreon/{campaign.Key}"; + var secret = await _api.CreateWebhookAsync(accessToken, info.Id, uri); + campaign.WebhookSecret = _secretProtector.Protect(secret); + } + catch (HttpRequestException e) + { + _logger.LogWarning(e, "Creating webhook for campaign {Campaign} failed", info.Id); + return ResultApiError; + } + } + + campaign.AccessToken = _secretProtector.Protect(accessToken); + campaign.RefreshToken = _secretProtector.Protect(refreshToken); + campaign.TokenExpiresAt = properties.GetTokenValue("expires_at") is { } expires + ? DateTimeOffset.Parse(expires, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind) + : null; + + if (isNew) + _db.PatreonCampaigns.Add(campaign); + + await _db.SaveChangesAsync(); + + try + { + await _importer.ImportAsync(campaign); + } + catch (Exception e) + { + _logger.LogWarning(e, "Importing members of campaign {Campaign} failed", campaign.Key); + return ResultImportFailed; + } + + campaign.Enabled = true; + await _db.SaveChangesAsync(); + + return ResultConnected; + } + + private async Task MakeUniqueKeyAsync(string name) + { + var baseKey = MakeKey(name); + var key = baseKey; + for (var i = 2; await _db.PatreonCampaigns.AnyAsync(c => c.Key == key); i++) + { + key = $"{baseKey}-{i}"; + } + + return key; + } + + internal static string MakeKey(string name) + { + var key = Regex.Replace(name.ToLowerInvariant(), "[^a-z0-9]+", "-").Trim('-'); + if (key.Length > 40) + key = key[..40].TrimEnd('-'); + + return key == "" ? "campaign" : key; + } +} diff --git a/SS14.Web/PatreonConnectionHandler.cs b/SS14.Web/PatreonConnectionHandler.cs index 33f521c4..a5b70fc0 100644 --- a/SS14.Web/PatreonConnectionHandler.cs +++ b/SS14.Web/PatreonConnectionHandler.cs @@ -1,63 +1,30 @@ using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Security.Claims; -using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using SS14.Auth.Shared.Config; using SS14.Auth.Shared.Data; namespace SS14.Web; public sealed class PatreonConnectionHandler { - private const string ClaimPatreonReward = "PatreonReward"; - private readonly SpaceUserManager _userManager; private readonly ApplicationDbContext _db; - private readonly IOptions _patreonCfg; private readonly AccountLogManager _accountLogManager; public PatreonConnectionHandler( SpaceUserManager userManager, ApplicationDbContext db, - IOptions patreonCfg, AccountLogManager accountLogManager) { _userManager = userManager; _db = db; - _patreonCfg = patreonCfg; _accountLogManager = accountLogManager; } - public Task HookCreatingTicket(OAuthCreatingTicketContext context) - { - // Add current tier to the principal, rest is handle in Received. - - var identity = (ClaimsIdentity) context.Principal!.Identity; - - // AFAICT you shouldn't be able to have multiple tiers with our current patreon setup so... - var tier = ParseTiers(context.User) - .Where(t => _patreonCfg.Value.TierMap.ContainsKey(t)) - .Select(t => _patreonCfg.Value.TierMap[t]) - .FirstOrDefault(); - - if (tier != null) - { - identity!.AddClaim(new Claim(ClaimPatreonReward, tier)); - } - - Console.WriteLine(context.AccessToken); - - return Task.CompletedTask; - } - public async Task HookReceivedTicket(TicketReceivedContext context) { var guid = context.Properties.Items["SS14UserId"]!; @@ -86,11 +53,8 @@ public async Task HookReceivedTicket(TicketReceivedContext context) _db.Patrons.Remove(existingPatron); } - var tier = context.Principal.Claims.FirstOrDefault(p => p.Type == ClaimPatreonReward)?.Value; - var newPatron = new Patron { - CurrentTier = tier, PatreonId = patreonId, SpaceUserId = user.Id }; @@ -113,33 +77,4 @@ await _accountLogManager.LogAndSave( context.HandleResponse(); } - - [SuppressMessage("ReSharper", "HeapView.BoxingAllocation")] - internal static IEnumerable ParseTiers(JsonElement elemRoot) - { - if (!elemRoot.TryGetProperty("included", out var included)) - return Enumerable.Empty(); - - var includedMemberships = included - .EnumerateArray() - .Where(c => c.GetProperty("type").GetString() == "member"); - - return elemRoot - .GetProperty("data") - .GetProperty("relationships") - .GetProperty("memberships") - .GetProperty("data") - .EnumerateArray() - .Join( - includedMemberships, - m => m.GetProperty("id").GetString(), - m => m.GetProperty("id").GetString(), - (_, member) => member) - .SelectMany(m => - m.GetProperty("relationships") - .GetProperty("currently_entitled_tiers") - .GetProperty("data") - .EnumerateArray()) - .Select(m => m.GetProperty("id").GetString()); - } } \ No newline at end of file diff --git a/SS14.Web/Startup.cs b/SS14.Web/Startup.cs index c7805369..f14ee646 100644 --- a/SS14.Web/Startup.cs +++ b/SS14.Web/Startup.cs @@ -79,6 +79,7 @@ public void ConfigureServices(IServiceCollection services) options.Conventions.AuthorizeAreaFolder("Admin", "/", AuthConstants.PolicyAnyHubAdmin); options.Conventions.AuthorizeAreaFolder("Admin", "/Clients", AuthConstants.PolicySysAdmin); options.Conventions.AuthorizeAreaFolder("Admin", "/Users", AuthConstants.PolicySysAdmin); + options.Conventions.AuthorizeAreaFolder("Admin", "/Patreon", AuthConstants.PolicySysAdmin); options.Conventions.AuthorizeAreaFolder("Admin", "/Servers", AuthConstants.PolicyServerHubAdmin); }); @@ -93,6 +94,7 @@ public void ConfigureServices(IServiceCollection services) services.AddRazorPages(); services.AddScoped(); + services.AddScoped(); var patreonSection = Configuration.GetSection("Patreon"); var patreonCfg = patreonSection.Get(); @@ -108,19 +110,30 @@ public void ConfigureServices(IServiceCollection services) { // Patreon docs lied you don't need this to see memberships to your own campaign. // options.Scope.Add("identity.memberships"); - options.Includes.Add("memberships.currently_entitled_tiers"); options.ClientId = patreonCfg.ClientId; options.ClientSecret = patreonCfg.ClientSecret; - options.Events.OnCreatingTicket += context => + options.Events.OnTicketReceived += context => { var handler = context.HttpContext.RequestServices.GetService(); - return handler!.HookCreatingTicket(context); + return handler!.HookReceivedTicket(context); }; + }) + // Campaign creators connecting their campaign. Needs the callback registered in the Patreon client. + .AddPatreon("PatreonCreator", null!, options => + { + options.Scope.Add("campaigns"); + options.Scope.Add("campaigns.members"); + options.Scope.Add("w:campaigns.webhook"); + options.ClientId = patreonCfg.ClientId; + options.ClientSecret = patreonCfg.ClientSecret; + options.CallbackPath = "/signin-patreon-creator"; + options.SaveTokens = true; options.Events.OnTicketReceived += context => { - var handler = context.HttpContext.RequestServices.GetService(); + var handler = context.HttpContext.RequestServices + .GetService(); return handler!.HookReceivedTicket(context); }; });