Skip to content

Commit

Permalink
Move code into the delegating handler
Browse files Browse the repository at this point in the history
  • Loading branch information
davidfowl committed Jul 14, 2023
1 parent 88d236b commit 7c18bec
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions TodoApi.Tests/TodoApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ public async Task CreateUserAsync(string username, string? password = null)

public HttpClient CreateClient(string id, bool isAdmin = false)
{
return CreateDefaultClient(new AuthHandler(async req =>
{
var token = await CreateTokenAsync(id, isAdmin);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}));
return CreateDefaultClient(new AuthHandler(Services, id, isAdmin));
}

protected override IHost CreateHost(IHostBuilder builder)
Expand Down Expand Up @@ -65,28 +61,25 @@ protected override IHost CreateHost(IHostBuilder builder)
return base.CreateHost(builder);
}

private async Task<string> CreateTokenAsync(string id, bool isAdmin = false)
{
await using var scope = Services.CreateAsyncScope();

// Read the user JWTs configuration for testing so unit tests can generate
// JWT tokens.
var tokenService = scope.ServiceProvider.GetRequiredService<TokenService>();

return await tokenService.GenerateTokenAsync(id, isAdmin);
}

protected override void Dispose(bool disposing)
{
_sqliteConnection?.Dispose();
base.Dispose(disposing);
}

private sealed class AuthHandler(Func<HttpRequestMessage, Task> onRequest) : DelegatingHandler
private sealed class AuthHandler(IServiceProvider services, string id, bool isAdmin) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
await onRequest(request);
await using var scope = services.CreateAsyncScope();

// Generate tokens
var tokenService = scope.ServiceProvider.GetRequiredService<TokenService>();

var token = await tokenService.GenerateTokenAsync(id, isAdmin);

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

return await base.SendAsync(request, cancellationToken);
}
}
Expand Down

0 comments on commit 7c18bec

Please sign in to comment.