Skip to content

Commit 90c4249

Browse files
refactor: authors in database instead of Auth0 metadata
It's fairly complicated to read and maintain author information in the Auth0 user's metadata, so instead we'll just store the user's ID in mongo and read author information from there. This also allows multiple users to work under multiple authors.
1 parent 749dade commit 90c4249

File tree

11 files changed

+39
-244
lines changed

11 files changed

+39
-244
lines changed

src/BHS.Infrastructure/BHS.Infrastructure.csproj

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
</PropertyGroup>
99

1010
<ItemGroup>
11-
<PackageReference Include="Auth0.ManagementApi" Version="7.29.0" />
12-
<PackageReference Include="Auth0Net.DependencyInjection" Version="4.0.0" />
1311
<PackageReference Include="Humanizer" Version="2.14.1" />
1412
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
1513
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="8.0.0" />
@@ -24,7 +22,7 @@
2422

2523
<ItemGroup>
2624
<InternalsVisibleTo Include="$(AssemblyName).Tests" />
27-
<InternalsVisibleTo Include="BHS.Utilities.MongoMigration" />
25+
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
2826
</ItemGroup>
2927

3028
</Project>

src/BHS.Infrastructure/IoC/BhsServiceCollectionExtensions.cs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using Auth0Net.DependencyInjection;
2-
using Auth0Net.DependencyInjection.Cache;
3-
using BHS.Domain.Authors;
1+
using BHS.Domain.Authors;
42
using BHS.Domain.Banners;
53
using BHS.Domain.Blog;
64
using BHS.Domain.ContactUs;
@@ -9,7 +7,6 @@
97
using BHS.Domain.Notifications;
108
using BHS.Domain.Photos;
119
using BHS.Infrastructure.Adapters;
12-
using BHS.Infrastructure.Repositories.Auth0;
1310
using BHS.Infrastructure.Repositories.Mongo;
1411
using Microsoft.Extensions.Configuration;
1512
using Microsoft.Extensions.DependencyInjection;
@@ -38,13 +35,6 @@ public static IServiceCollection AddBhsServices(this IServiceCollection services
3835
services.AddSingleton(TimeProvider.System);
3936

4037
services.AddMongoRepositories();
41-
services.AddTransient<IAuthorRepository, AuthorRepository>();
42-
43-
services.AddAuth0AuthenticationClient(config => { });
44-
services.AddOptions<Auth0Configuration>()
45-
.BindConfiguration("Auth0ManagementApiOptions");
46-
services.AddAuth0ManagementClient()
47-
.AddManagementAccessToken();
4838

4939
return services;
5040
}
@@ -69,6 +59,7 @@ private static IServiceCollection AddMongoRepositories(this IServiceCollection s
6959
return new MongoClient(clientSettings);
7060
});
7161

62+
services.AddSingleton<IAuthorRepository, AuthorRepository>();
7263
services.AddSingleton<IPostRepository, PostRepository>();
7364
services.AddSingleton<IPostPreviewRepository, PostPreviewRepository>();
7465
services.AddSingleton<ICategoryRepository, CategoryRepository>();

src/BHS.Infrastructure/Repositories/Auth0/AuthorRepository.cs

Lines changed: 0 additions & 98 deletions
This file was deleted.

src/BHS.Infrastructure/Repositories/Auth0/FailedAuthorRequestException.cs

Lines changed: 0 additions & 8 deletions
This file was deleted.

src/BHS.Infrastructure/Repositories/Auth0/InvalidAuthorRequestException.cs

Lines changed: 0 additions & 6 deletions
This file was deleted.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using BHS.Contracts;
2+
using BHS.Domain.Authors;
3+
using MongoDB.Driver;
4+
5+
namespace BHS.Infrastructure.Repositories.Mongo;
6+
7+
internal sealed record AuthorDto(
8+
string Id,
9+
string[] AuthUserId,
10+
string DisplayName);
11+
12+
public class AuthorRepository(
13+
IMongoClient mongoClient) : IAuthorRepository
14+
{
15+
private readonly IMongoCollection<AuthorDto> _authorsCollection = mongoClient
16+
.GetBhsCollection<AuthorDto>("authors");
17+
18+
public async Task<IReadOnlyCollection<Author>> GetByAuthUserId(string authUserId, CancellationToken cancellationToken = default)
19+
{
20+
return await _authorsCollection
21+
.Aggregate()
22+
.Match(x => x.AuthUserId.Contains(authUserId))
23+
.Project(x => new Author(x.Id, x.DisplayName))
24+
.ToListAsync(cancellationToken);
25+
}
26+
}

src/BHS.Web/Controllers/ErrorController.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using BHS.Domain.Banners;
22
using BHS.Domain.ContactUs;
33
using BHS.Domain.Photos;
4-
using BHS.Infrastructure.Repositories.Auth0;
54
using Microsoft.AspNetCore.Diagnostics;
65
using Microsoft.AspNetCore.Mvc;
76
using MongoDB.Driver;
@@ -35,13 +34,10 @@ private static int GetStatusCode(Exception? exception) =>
3534
{
3635
InvalidContactRequestException => StatusCodes.Status400BadRequest,
3736
InvalidPhotoIdException => StatusCodes.Status400BadRequest,
38-
InvalidAuthorRequestException => StatusCodes.Status400BadRequest,
3937
InvalidBannerIdException => StatusCodes.Status400BadRequest,
4038

4139
MongoWriteException ex when ex.WriteError.Category == ServerErrorCategory.DuplicateKey => StatusCodes.Status409Conflict,
4240

43-
FailedAuthorRequestException => StatusCodes.Status500InternalServerError,
44-
4541
NotImplementedException => StatusCodes.Status501NotImplemented,
4642

4743
_ => StatusCodes.Status500InternalServerError,

tests/BHS.Api.IntegrationTests/BhsWebApplicationFactory.cs

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using Auth0.ManagementApi;
2-
using EphemeralMongo;
1+
using EphemeralMongo;
32
using Microsoft.AspNetCore.Authorization.Policy;
43
using Microsoft.AspNetCore.Hosting;
54
using Microsoft.AspNetCore.Mvc.Testing;
@@ -9,7 +8,6 @@
98
using Microsoft.Extensions.Diagnostics.HealthChecks;
109
using Microsoft.Extensions.Hosting;
1110
using MongoDB.Driver;
12-
using NSubstitute;
1311

1412
namespace BHS.Api.IntegrationTests;
1513

@@ -19,8 +17,6 @@ public sealed class BhsWebApplicationFactory<TProgram> : WebApplicationFactory<T
1917
private readonly MongoUrl _mongoUrl;
2018
private bool _disposedValue;
2119

22-
public IManagementConnection MockManagementConnection { get; } = Substitute.For<IManagementConnection>();
23-
2420
public BhsWebApplicationFactory()
2521
{
2622
_mongoRunner = MongoRunner.Run(new MongoRunnerOptions
@@ -52,10 +48,6 @@ protected override IHost CreateHost(IHostBuilder builder)
5248
// Replace any occurrence of the MongoDB connection string.
5349
{ "ConnectionStrings:bhsMongo", _mongoUrl.ToString() },
5450
{ "Serilog:WriteTo:0:Args:databaseUrl", _mongoUrl.ToString() },
55-
56-
{ "Auth0ManagementApiOptions:Domain", "test.com" },
57-
{ "Auth0ManagementApiOptions:ClientId", "foo" },
58-
{ "Auth0ManagementApiOptions:ClientSecret", "bar" },
5951
});
6052
});
6153

@@ -65,10 +57,6 @@ protected override IHost CreateHost(IHostBuilder builder)
6557
services.RemoveAll<IPolicyEvaluator>();
6658
services.AddSingleton<IPolicyEvaluator, NoAuthEvaluator>();
6759

68-
// Mock Auth0 management api.
69-
services.RemoveAll<IManagementConnection>();
70-
services.AddSingleton(provider => MockManagementConnection);
71-
7260
// SendGrid healthcheck is more appropriate for smoke tests, not integration tests.
7361
services.PostConfigure<HealthCheckServiceOptions>(opt =>
7462
{

tests/BHS.Api.IntegrationTests/EndpointTests.cs

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
1-
using Auth0.Core.Exceptions;
2-
using Auth0.ManagementApi;
3-
using Auth0.ManagementApi.Models;
4-
using BHS.Contracts;
1+
using BHS.Contracts;
52
using BHS.Contracts.Banners;
63
using BHS.Contracts.Blog;
74
using BHS.Contracts.Leadership;
85
using BHS.Contracts.Photos;
96
using BHS.Web;
107
using MongoDB.Bson;
11-
using NSubstitute;
12-
using NSubstitute.ExceptionExtensions;
138
using System.Net;
149
using System.Net.Http.Json;
1510
using System.Net.Mime;
@@ -22,7 +17,6 @@ namespace BHS.Api.IntegrationTests;
2217
public class EndpointTests(BhsWebApplicationFactory<Program> factory) : IClassFixture<BhsWebApplicationFactory<Program>>
2318
{
2419
private readonly HttpClient _httpClient = factory.CreateClient();
25-
private readonly IManagementConnection _mockManagementConnection = factory.MockManagementConnection;
2620

2721
[Fact]
2822
public async Task HealthCheck_Ok()
@@ -45,15 +39,16 @@ public async Task Swagger_Ok()
4539
}
4640

4741
[Fact]
48-
public async Task Author_GetByAuthUserId_InvalidFormat_400()
42+
public async Task Author_GetByAuthUserId_Empty()
4943
{
50-
_mockManagementConnection
51-
.GetAsync<User>(Arg.Any<Uri>(), Arg.Any<Dictionary<string, string>>(), null, Arg.Any<CancellationToken>())
52-
.Throws(new ErrorApiException(HttpStatusCode.BadRequest));
53-
5444
using var response = await _httpClient.GetAsync("/api/authors?authUserId=12345", TestContext.Current.CancellationToken);
5545

56-
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
46+
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
47+
Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
48+
49+
var authors = await response.Content.ReadFromJsonAsync<IEnumerable<Author>>(TestContext.Current.CancellationToken);
50+
Assert.NotNull(authors);
51+
Assert.Empty(authors);
5752
}
5853

5954
[Fact]

tests/BHS.Infrastructure.Tests/Repositories/AuthorRepositoryTests.cs

Lines changed: 0 additions & 81 deletions
This file was deleted.

0 commit comments

Comments
 (0)