formatting

This commit is contained in:
Aaron Po
2026-06-20 15:09:40 -04:00
parent 254431928f
commit cd99c1fbc3
131 changed files with 1306 additions and 1447 deletions

View File

@@ -8,33 +8,27 @@
</PropertyGroup>
<ItemGroup>
<PackageReference
Include="Microsoft.AspNetCore.OpenApi"
Version="9.0.11"
/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
<PackageReference
Include="FluentValidation.AspNetCore"
Version="11.3.0"
/>
<PackageReference Include="MediatR" Version="12.4.1"/>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="MediatR" Version="12.4.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="Infrastructure\"/>
<Folder Include="Infrastructure\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj"/>
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj"/>
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj"/>
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Jwt\Infrastructure.Jwt.csproj"/>
<ProjectReference Include="..\..\Features\Features.Breweries\Features.Breweries.csproj"/>
<ProjectReference Include="..\..\Features\Features.UserManagement\Features.UserManagement.csproj"/>
<ProjectReference Include="..\..\Features\Features.Auth\Features.Auth.csproj"/>
<ProjectReference Include="..\..\Features\Features.Emails\Features.Emails.csproj"/>
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj"/>
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj"/>
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Jwt\Infrastructure.Jwt.csproj" />
<ProjectReference Include="..\..\Features\Features.Breweries\Features.Breweries.csproj" />
<ProjectReference Include="..\..\Features\Features.UserManagement\Features.UserManagement.csproj" />
<ProjectReference Include="..\..\Features\Features.Auth\Features.Auth.csproj" />
<ProjectReference Include="..\..\Features\Features.Emails\Features.Emails.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
</ItemGroup>
<ItemGroup>

View File

@@ -44,29 +44,19 @@ public class JwtAuthenticationHandler(
{
// Use the same access-token secret source as TokenService to avoid mismatched validation.
string? secret = Environment.GetEnvironmentVariable("ACCESS_TOKEN_SECRET");
if (string.IsNullOrWhiteSpace(secret)) secret = configuration["Jwt:SecretKey"];
if (string.IsNullOrWhiteSpace(secret))
secret = configuration["Jwt:SecretKey"];
if (string.IsNullOrWhiteSpace(secret)) return AuthenticateResult.Fail("JWT secret is not configured");
if (string.IsNullOrWhiteSpace(secret))
return AuthenticateResult.Fail("JWT secret is not configured");
// Check if Authorization header exists
if (
!Request.Headers.TryGetValue(
"Authorization",
out StringValues authHeaderValue
)
)
if (!Request.Headers.TryGetValue("Authorization", out StringValues authHeaderValue))
return AuthenticateResult.Fail("Authorization header is missing");
string authHeader = authHeaderValue.ToString();
if (
!authHeader.StartsWith(
"Bearer ",
StringComparison.OrdinalIgnoreCase
)
)
return AuthenticateResult.Fail(
"Invalid authorization header format"
);
if (!authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return AuthenticateResult.Fail("Invalid authorization header format");
string token = authHeader.Substring("Bearer ".Length).Trim();
@@ -81,9 +71,7 @@ public class JwtAuthenticationHandler(
}
catch (Exception ex)
{
return AuthenticateResult.Fail(
$"Token validation failed: {ex.Message}"
);
return AuthenticateResult.Fail($"Token validation failed: {ex.Message}");
}
}
@@ -97,7 +85,10 @@ public class JwtAuthenticationHandler(
Response.ContentType = "application/json";
Response.StatusCode = 401;
ResponseBody response = new() { Message = "Unauthorized: Invalid or missing authentication token" };
ResponseBody response = new()
{
Message = "Unauthorized: Invalid or missing authentication token",
};
await Response.WriteAsJsonAsync(response);
}
}
@@ -106,6 +97,4 @@ public class JwtAuthenticationHandler(
/// Options for the <c>JWT</c> authentication scheme handled by <see cref="JwtAuthenticationHandler" />.
/// </summary>
/// <remarks>No additional options are defined beyond those provided by <see cref="AuthenticationSchemeOptions" />.</remarks>
public class JwtAuthenticationOptions : AuthenticationSchemeOptions
{
}
public class JwtAuthenticationOptions : AuthenticationSchemeOptions { }

View File

@@ -24,4 +24,4 @@ public class NotFoundController : ControllerBase
{
return NotFound(new { message = "Route not found." });
}
}
}

View File

@@ -31,8 +31,8 @@ public class ProtectedController : ControllerBase
new ResponseBody<object>
{
Message = "Protected endpoint accessed successfully",
Payload = new { userId, username }
Payload = new { userId, username },
}
);
}
}
}

View File

@@ -14,8 +14,7 @@ namespace API.Core;
/// consistent JSON error responses with appropriate HTTP status codes.
/// </summary>
/// <param name="logger">Logger used to record unhandled exceptions before they are translated into a response.</param>
public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
: IExceptionFilter
public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExceptionFilter
{
/// <summary>
/// Logs the exception and sets <see cref="ExceptionContext.Result" /> to an appropriate error response,
@@ -84,10 +83,7 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
case ValidationException fluentValidationException:
Dictionary<string, string[]> errors = fluentValidationException
.Errors.GroupBy(e => e.PropertyName)
.ToDictionary(
g => g.Key,
g => g.Select(e => e.ErrorMessage).ToArray()
);
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray());
context.Result = new BadRequestObjectResult(
new { message = "Validation failed", errors }
@@ -96,41 +92,33 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
break;
case ConflictException ex:
context.Result = new ObjectResult(
new ResponseBody { Message = ex.Message }
)
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
{
StatusCode = 409
StatusCode = 409,
};
context.ExceptionHandled = true;
break;
case NotFoundException ex:
context.Result = new ObjectResult(
new ResponseBody { Message = ex.Message }
)
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
{
StatusCode = 404
StatusCode = 404,
};
context.ExceptionHandled = true;
break;
case UnauthorizedException ex:
context.Result = new ObjectResult(
new ResponseBody { Message = ex.Message }
)
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
{
StatusCode = 401
StatusCode = 401,
};
context.ExceptionHandled = true;
break;
case ForbiddenException ex:
context.Result = new ObjectResult(
new ResponseBody { Message = ex.Message }
)
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
{
StatusCode = 403
StatusCode = 403,
};
context.ExceptionHandled = true;
break;
@@ -140,33 +128,28 @@ public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
new ResponseBody { Message = "A database error occurred." }
)
{
StatusCode = 503
StatusCode = 503,
};
context.ExceptionHandled = true;
break;
case Domain.Exceptions.ValidationException ex:
context.Result = new ObjectResult(
new ResponseBody { Message = ex.Message }
)
context.Result = new ObjectResult(new ResponseBody { Message = ex.Message })
{
StatusCode = 400
StatusCode = 400,
};
context.ExceptionHandled = true;
break;
default:
context.Result = new ObjectResult(
new ResponseBody
{
Message = "An unexpected error occurred"
}
new ResponseBody { Message = "An unexpected error occurred" }
)
{
StatusCode = 500
StatusCode = 500,
};
context.ExceptionHandled = true;
break;
}
}
}
}

View File

@@ -17,7 +17,11 @@ using Shared.Application.Behaviors;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Global Exception Filter
builder.Services.AddControllers(options => { options.Filters.Add<GlobalExceptionFilter>(); })
builder
.Services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
})
.AddApplicationPart(typeof(BreweryController).Assembly)
.AddApplicationPart(typeof(UserController).Assembly)
.AddApplicationPart(typeof(AuthController).Assembly);
@@ -51,14 +55,12 @@ builder.Services.AddHealthChecks();
// Configure logging for container output
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
if (!builder.Environment.IsProduction()) builder.Logging.AddDebug();
if (!builder.Environment.IsProduction())
builder.Logging.AddDebug();
// Configure Dependency Injection -------------------------------------------------------------------------------------
builder.Services.AddSingleton<
ISqlConnectionFactory,
DefaultSqlConnectionFactory
>();
builder.Services.AddSingleton<ISqlConnectionFactory, DefaultSqlConnectionFactory>();
builder.Services.AddFeaturesBreweries();
builder.Services.AddFeaturesUserManagement();
@@ -75,10 +77,7 @@ builder.Services.AddScoped<GlobalExceptionFilter>();
// Configure JWT Authentication
builder
.Services.AddAuthentication("JWT")
.AddScheme<JwtAuthenticationOptions, JwtAuthenticationHandler>(
"JWT",
options => { }
);
.AddScheme<JwtAuthenticationOptions, JwtAuthenticationHandler>("JWT", options => { });
builder.Services.AddAuthorization();
@@ -106,4 +105,4 @@ lifetime.ApplicationStopping.Register(() =>
app.Logger.LogInformation("Application is shutting down gracefully...");
});
app.Run();
app.Run();

View File

@@ -8,40 +8,37 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0"/>
<PackageReference Include="xunit" Version="2.9.2"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"/>
<PackageReference Include="FluentAssertions" Version="6.9.0"/>
<PackageReference Include="dbup" Version="5.0.41"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="FluentAssertions" Version="6.9.0" />
<PackageReference Include="dbup" Version="5.0.41" />
<!-- Reqnroll core, xUnit adapter and code-behind generator -->
<PackageReference Include="Reqnroll" Version="3.3.3"/>
<PackageReference Include="Reqnroll.xUnit" Version="3.3.3"/>
<PackageReference Include="Reqnroll" Version="3.3.3" />
<PackageReference Include="Reqnroll.xUnit" Version="3.3.3" />
<PackageReference
Include="Reqnroll.Tools.MsBuild.Generation"
Version="3.3.3"
PrivateAssets="all"
Include="Reqnroll.Tools.MsBuild.Generation"
Version="3.3.3"
PrivateAssets="all"
/>
<!-- ASP.NET Core integration testing -->
<PackageReference
Include="Microsoft.AspNetCore.Mvc.Testing"
Version="9.0.1"
/>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.1" />
</ItemGroup>
<ItemGroup>
<!-- Ensure feature files are included in the project -->
<None Include="Features\**\*.feature"/>
<None Include="Features\**\*.feature" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\API.Core\API.Core.csproj"/>
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Email\Infrastructure.Email.csproj"/>
<ProjectReference Include="..\..\Features\Features.Emails\Features.Emails.csproj"/>
<ProjectReference Include="..\API.Core\API.Core.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Email\Infrastructure.Email.csproj" />
<ProjectReference Include="..\..\Features\Features.Emails\Features.Emails.csproj" />
</ItemGroup>
</Project>

View File

@@ -8,11 +8,7 @@ public class MockEmailDispatcher : IEmailDispatcher
public List<ResendConfirmationEmail> SentResendConfirmationEmails { get; } = new();
public Task SendRegistrationEmailAsync(
string firstName,
string email,
string confirmationToken
)
public Task SendRegistrationEmailAsync(string firstName, string email, string confirmationToken)
{
SentRegistrationEmails.Add(
new RegistrationEmail
@@ -20,7 +16,7 @@ public class MockEmailDispatcher : IEmailDispatcher
FirstName = firstName,
Email = email,
ConfirmationToken = confirmationToken,
SentAt = DateTime.UtcNow
SentAt = DateTime.UtcNow,
}
);
@@ -39,7 +35,7 @@ public class MockEmailDispatcher : IEmailDispatcher
FirstName = firstName,
Email = email,
ConfirmationToken = confirmationToken,
SentAt = DateTime.UtcNow
SentAt = DateTime.UtcNow,
}
);
@@ -67,4 +63,4 @@ public class MockEmailDispatcher : IEmailDispatcher
public string ConfirmationToken { get; init; } = string.Empty;
public DateTime SentAt { get; init; }
}
}
}

View File

@@ -10,12 +10,7 @@ public class MockEmailProvider : IEmailProvider
{
public List<SentEmail> SentEmails { get; } = new();
public Task SendAsync(
string to,
string subject,
string body,
bool isHtml = true
)
public Task SendAsync(string to, string subject, string body, bool isHtml = true)
{
SentEmails.Add(
new SentEmail
@@ -24,19 +19,14 @@ public class MockEmailProvider : IEmailProvider
Subject = subject,
Body = body,
IsHtml = isHtml,
SentAt = DateTime.UtcNow
SentAt = DateTime.UtcNow,
}
);
return Task.CompletedTask;
}
public Task SendAsync(
IEnumerable<string> to,
string subject,
string body,
bool isHtml = true
)
public Task SendAsync(IEnumerable<string> to, string subject, string body, bool isHtml = true)
{
SentEmails.Add(
new SentEmail
@@ -45,7 +35,7 @@ public class MockEmailProvider : IEmailProvider
Subject = subject,
Body = body,
IsHtml = isHtml,
SentAt = DateTime.UtcNow
SentAt = DateTime.UtcNow,
}
);
@@ -65,4 +55,4 @@ public class MockEmailProvider : IEmailProvider
public bool IsHtml { get; init; }
public DateTime SentAt { get; init; }
}
}
}

View File

@@ -15,7 +15,8 @@ public class ApiGeneralSteps(ScenarioContext scenario)
private HttpClient GetClient()
{
if (scenario.TryGetValue<HttpClient>(ClientKey, out HttpClient? client)) return client;
if (scenario.TryGetValue<HttpClient>(ClientKey, out HttpClient? client))
return client;
TestApiFactory? factory = scenario.TryGetValue<TestApiFactory>(
FactoryKey,
@@ -47,11 +48,7 @@ public class ApiGeneralSteps(ScenarioContext scenario)
HttpRequestMessage requestMessage = new(new HttpMethod(method), url)
{
Content = new StringContent(
jsonBody,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -62,16 +59,10 @@ public class ApiGeneralSteps(ScenarioContext scenario)
}
[When("I send an HTTP request {string} to {string}")]
public async Task WhenISendAnHttpRequestStringToString(
string method,
string url
)
public async Task WhenISendAnHttpRequestStringToString(string method, string url)
{
HttpClient client = GetClient();
HttpRequestMessage requestMessage = new(
new HttpMethod(method),
url
);
HttpRequestMessage requestMessage = new(new HttpMethod(method), url);
HttpResponseMessage response = await client.SendAsync(requestMessage);
string responseBody = await response.Content.ReadAsStringAsync();
@@ -100,19 +91,13 @@ public class ApiGeneralSteps(ScenarioContext scenario)
}
[Then("the response JSON should have {string} equal {string}")]
public void ThenTheResponseJsonShouldHaveStringEqualString(
string field,
string expected
)
public void ThenTheResponseJsonShouldHaveStringEqualString(string field, string expected)
{
scenario
.TryGetValue<HttpResponseMessage>(ResponseKey, out HttpResponseMessage? response)
.Should()
.BeTrue();
scenario
.TryGetValue<string>(ResponseBodyKey, out string? responseBody)
.Should()
.BeTrue();
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement root = doc.RootElement;
@@ -125,25 +110,16 @@ public class ApiGeneralSteps(ScenarioContext scenario)
"Expected field '{0}' to be present either at the root or inside 'payload'",
field
);
payloadElem
.ValueKind.Should()
.Be(JsonValueKind.Object, "payload must be an object");
payloadElem.ValueKind.Should().Be(JsonValueKind.Object, "payload must be an object");
payloadElem
.TryGetProperty(field, out value)
.Should()
.BeTrue(
"Expected field '{0}' to be present inside 'payload'",
field
);
.BeTrue("Expected field '{0}' to be present inside 'payload'", field);
}
value
.ValueKind.Should()
.Be(
JsonValueKind.String,
"Expected field '{0}' to be a string",
field
);
.Be(JsonValueKind.String, "Expected field '{0}' to be a string", field);
value.GetString().Should().Be(expected);
}
@@ -157,10 +133,7 @@ public class ApiGeneralSteps(ScenarioContext scenario)
.TryGetValue<HttpResponseMessage>(ResponseKey, out HttpResponseMessage? response)
.Should()
.BeTrue();
scenario
.TryGetValue<string>(ResponseBodyKey, out string? responseBody)
.Should()
.BeTrue();
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement root = doc.RootElement;
@@ -173,25 +146,16 @@ public class ApiGeneralSteps(ScenarioContext scenario)
"Expected field '{0}' to be present either at the root or inside 'payload'",
field
);
payloadElem
.ValueKind.Should()
.Be(JsonValueKind.Object, "payload must be an object");
payloadElem.ValueKind.Should().Be(JsonValueKind.Object, "payload must be an object");
payloadElem
.TryGetProperty(field, out value)
.Should()
.BeTrue(
"Expected field '{0}' to be present inside 'payload'",
field
);
.BeTrue("Expected field '{0}' to be present inside 'payload'", field);
}
value
.ValueKind.Should()
.Be(
JsonValueKind.String,
"Expected field '{0}' to be a string",
field
);
.Be(JsonValueKind.String, "Expected field '{0}' to be a string", field);
string? actualValue = value.GetString();
actualValue
.Should()
@@ -203,4 +167,4 @@ public class ApiGeneralSteps(ScenarioContext scenario)
actualValue
);
}
}
}

View File

@@ -21,7 +21,8 @@ public class AuthSteps(ScenarioContext scenario)
private HttpClient GetClient()
{
if (scenario.TryGetValue<HttpClient>(ClientKey, out HttpClient? client)) return client;
if (scenario.TryGetValue<HttpClient>(ClientKey, out HttpClient? client))
return client;
TestApiFactory? factory = scenario.TryGetValue<TestApiFactory>(
FactoryKey,
@@ -39,9 +40,7 @@ public class AuthSteps(ScenarioContext scenario)
private static string GetRequiredEnvVar(string name)
{
return Environment.GetEnvironmentVariable(name)
?? throw new InvalidOperationException(
$"{name} environment variable is not set"
);
?? throw new InvalidOperationException($"{name} environment variable is not set");
}
private static string GenerateJwtToken(
@@ -57,21 +56,13 @@ public class AuthSteps(ScenarioContext scenario)
private static Guid ParseRegisteredUserId(JsonElement root)
{
return root
.GetProperty("payload")
.GetProperty("userAccountId")
.GetGuid();
return root.GetProperty("payload").GetProperty("userAccountId").GetGuid();
}
private static string ParseRegisteredUsername(JsonElement root)
{
return root
.GetProperty("payload")
.GetProperty("username")
.GetString()
?? throw new InvalidOperationException(
"username missing from registration payload"
);
return root.GetProperty("payload").GetProperty("username").GetString()
?? throw new InvalidOperationException("username missing from registration payload");
}
private static string ParseTokenFromPayload(
@@ -85,9 +76,7 @@ public class AuthSteps(ScenarioContext scenario)
|| payload.TryGetProperty(pascalCaseName, out tokenElem)
)
return tokenElem.GetString()
?? throw new InvalidOperationException(
$"{camelCaseName} is null"
);
?? throw new InvalidOperationException($"{camelCaseName} is null");
throw new InvalidOperationException(
$"Could not find token field '{camelCaseName}' in payload"
@@ -113,22 +102,15 @@ public class AuthSteps(ScenarioContext scenario)
(string username, string password) = scenario.TryGetValue<(
string username,
string password
)>(TestUserKey, out (string username, string password) user)
)>(TestUserKey, out (string username, string password) user)
? user
: ("test.user", "password");
string body = JsonSerializer.Serialize(new { username, password });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/login"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/login")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -144,16 +126,9 @@ public class AuthSteps(ScenarioContext scenario)
HttpClient client = GetClient();
string body = JsonSerializer.Serialize(new { password = "test" });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/login"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/login")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -169,16 +144,9 @@ public class AuthSteps(ScenarioContext scenario)
HttpClient client = GetClient();
string body = JsonSerializer.Serialize(new { username = "test" });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/login"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/login")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -192,16 +160,9 @@ public class AuthSteps(ScenarioContext scenario)
public async Task WhenISubmitALoginRequestWithBothUsernameAndPasswordMissing()
{
HttpClient client = GetClient();
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/login"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/login")
{
Content = new StringContent(
"{}",
Encoding.UTF8,
"application/json"
)
Content = new StringContent("{}", Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -218,10 +179,7 @@ public class AuthSteps(ScenarioContext scenario)
.TryGetValue<HttpResponseMessage>(ResponseKey, out HttpResponseMessage? response)
.Should()
.BeTrue();
scenario
.TryGetValue<string>(ResponseBodyKey, out string? responseBody)
.Should()
.BeTrue();
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement root = doc.RootElement;
@@ -236,11 +194,7 @@ public class AuthSteps(ScenarioContext scenario)
payloadElem.TryGetProperty("accessToken", out tokenElem)
|| payloadElem.TryGetProperty("AccessToken", out tokenElem);
hasToken
.Should()
.BeTrue(
"Expected an access token either at the root or inside 'payload'"
);
hasToken.Should().BeTrue("Expected an access token either at the root or inside 'payload'");
string? token = tokenElem.GetString();
token.Should().NotBeNullOrEmpty();
@@ -251,16 +205,9 @@ public class AuthSteps(ScenarioContext scenario)
{
HttpClient client = GetClient();
// testing GET
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/auth/login"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/auth/login")
{
Content = new StringContent(
"{}",
Encoding.UTF8,
"application/json"
)
Content = new StringContent("{}", Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -282,7 +229,8 @@ public class AuthSteps(ScenarioContext scenario)
string email = row["Email"] ?? "";
string dateOfBirth = row["DateOfBirth"] ?? "";
if (dateOfBirth == "{underage_date}") dateOfBirth = DateTime.UtcNow.AddYears(-18).ToString("yyyy-MM-dd");
if (dateOfBirth == "{underage_date}")
dateOfBirth = DateTime.UtcNow.AddYears(-18).ToString("yyyy-MM-dd");
// Keep default registration fixture values unique across repeated runs.
if (email == "newuser@example.com")
@@ -290,7 +238,8 @@ public class AuthSteps(ScenarioContext scenario)
string suffix = Guid.NewGuid().ToString("N")[..8];
email = $"newuser-{suffix}@example.com";
if (username == "newuser") username = $"newuser-{suffix}";
if (username == "newuser")
username = $"newuser-{suffix}";
}
string? password = row["Password"];
@@ -302,21 +251,14 @@ public class AuthSteps(ScenarioContext scenario)
lastName,
email,
dateOfBirth,
password
password,
};
string body = JsonSerializer.Serialize(registrationData);
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/register"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/register")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -330,16 +272,9 @@ public class AuthSteps(ScenarioContext scenario)
public async Task WhenISubmitARegistrationRequestUsingAGetRequest()
{
HttpClient client = GetClient();
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/auth/register"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/auth/register")
{
Content = new StringContent(
"{}",
Encoding.UTF8,
"application/json"
)
Content = new StringContent("{}", Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -361,20 +296,13 @@ public class AuthSteps(ScenarioContext scenario)
lastName = "User",
email = $"newuser-{suffix}@example.com",
dateOfBirth = "1990-01-01",
password = "Password1!"
password = "Password1!",
};
string body = JsonSerializer.Serialize(registrationData);
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/register"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/register")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -395,16 +323,9 @@ public class AuthSteps(ScenarioContext scenario)
var loginData = new { username = "test.user", password = "password" };
string body = JsonSerializer.Serialize(loginData);
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/login"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/login")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -445,17 +366,10 @@ public class AuthSteps(ScenarioContext scenario)
{
Guid userId = scenario.TryGetValue<Guid>(RegisteredUserIdKey, out Guid id)
? id
: throw new InvalidOperationException(
"registered user ID not found in scenario"
);
string? username = scenario.TryGetValue<string>(
RegisteredUsernameKey,
out string? user
)
: throw new InvalidOperationException("registered user ID not found in scenario");
string? username = scenario.TryGetValue<string>(RegisteredUsernameKey, out string? user)
? user
: throw new InvalidOperationException(
"registered username not found in scenario"
);
: throw new InvalidOperationException("registered username not found in scenario");
string secret = GetRequiredEnvVar("ACCESS_TOKEN_SECRET");
scenario["accessToken"] = GenerateJwtToken(
@@ -471,17 +385,10 @@ public class AuthSteps(ScenarioContext scenario)
{
Guid userId = scenario.TryGetValue<Guid>(RegisteredUserIdKey, out Guid id)
? id
: throw new InvalidOperationException(
"registered user ID not found in scenario"
);
string? username = scenario.TryGetValue<string>(
RegisteredUsernameKey,
out string? user
)
: throw new InvalidOperationException("registered user ID not found in scenario");
string? username = scenario.TryGetValue<string>(RegisteredUsernameKey, out string? user)
? user
: throw new InvalidOperationException(
"registered username not found in scenario"
);
: throw new InvalidOperationException("registered username not found in scenario");
string secret = GetRequiredEnvVar("CONFIRMATION_TOKEN_SECRET");
scenario["confirmationToken"] = GenerateJwtToken(
@@ -497,17 +404,10 @@ public class AuthSteps(ScenarioContext scenario)
{
Guid userId = scenario.TryGetValue<Guid>(RegisteredUserIdKey, out Guid id)
? id
: throw new InvalidOperationException(
"registered user ID not found in scenario"
);
string? username = scenario.TryGetValue<string>(
RegisteredUsernameKey,
out string? user
)
: throw new InvalidOperationException("registered user ID not found in scenario");
string? username = scenario.TryGetValue<string>(RegisteredUsernameKey, out string? user)
? user
: throw new InvalidOperationException(
"registered username not found in scenario"
);
: throw new InvalidOperationException("registered username not found in scenario");
string secret = GetRequiredEnvVar("CONFIRMATION_TOKEN_SECRET");
scenario["confirmationToken"] = GenerateJwtToken(
@@ -523,20 +423,12 @@ public class AuthSteps(ScenarioContext scenario)
{
Guid userId = scenario.TryGetValue<Guid>(RegisteredUserIdKey, out Guid id)
? id
: throw new InvalidOperationException(
"registered user ID not found in scenario"
);
string? username = scenario.TryGetValue<string>(
RegisteredUsernameKey,
out string? user
)
: throw new InvalidOperationException("registered user ID not found in scenario");
string? username = scenario.TryGetValue<string>(RegisteredUsernameKey, out string? user)
? user
: throw new InvalidOperationException(
"registered username not found in scenario"
);
: throw new InvalidOperationException("registered username not found in scenario");
const string wrongSecret =
"wrong-confirmation-secret-that-is-very-long-1234567890";
const string wrongSecret = "wrong-confirmation-secret-that-is-very-long-1234567890";
scenario["confirmationToken"] = GenerateJwtToken(
userId,
username,
@@ -545,9 +437,7 @@ public class AuthSteps(ScenarioContext scenario)
);
}
[When(
"I submit a request to a protected endpoint with a valid access token"
)]
[When("I submit a request to a protected endpoint with a valid access token")]
public async Task WhenISubmitARequestToAProtectedEndpointWithAValidAccessToken()
{
HttpClient client = GetClient();
@@ -555,12 +445,9 @@ public class AuthSteps(ScenarioContext scenario)
? t
: "invalid-token";
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected")
{
Headers = { { "Authorization", $"Bearer {token}" } }
Headers = { { "Authorization", $"Bearer {token}" } },
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -569,18 +456,13 @@ public class AuthSteps(ScenarioContext scenario)
scenario[ResponseBodyKey] = responseBody;
}
[When(
"I submit a request to a protected endpoint with an invalid access token"
)]
[When("I submit a request to a protected endpoint with an invalid access token")]
public async Task WhenISubmitARequestToAProtectedEndpointWithAnInvalidAccessToken()
{
HttpClient client = GetClient();
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected")
{
Headers = { { "Authorization", "Bearer invalid-token-format" } }
Headers = { { "Authorization", "Bearer invalid-token-format" } },
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -673,16 +555,9 @@ public class AuthSteps(ScenarioContext scenario)
: "valid-refresh-token";
string body = JsonSerializer.Serialize(new { refreshToken = token });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/refresh"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/refresh")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -695,20 +570,11 @@ public class AuthSteps(ScenarioContext scenario)
public async Task WhenISubmitARefreshTokenRequestWithAnInvalidRefreshToken()
{
HttpClient client = GetClient();
string body = JsonSerializer.Serialize(
new { refreshToken = "invalid-refresh-token" }
);
string body = JsonSerializer.Serialize(new { refreshToken = "invalid-refresh-token" });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/refresh"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/refresh")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -722,20 +588,11 @@ public class AuthSteps(ScenarioContext scenario)
{
HttpClient client = GetClient();
// Use an expired token
string body = JsonSerializer.Serialize(
new { refreshToken = "expired-refresh-token" }
);
string body = JsonSerializer.Serialize(new { refreshToken = "expired-refresh-token" });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/refresh"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/refresh")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -750,16 +607,9 @@ public class AuthSteps(ScenarioContext scenario)
HttpClient client = GetClient();
string body = JsonSerializer.Serialize(new { });
HttpRequestMessage requestMessage = new(
HttpMethod.Post,
"/api/auth/refresh"
)
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/refresh")
{
Content = new StringContent(
body,
Encoding.UTF8,
"application/json"
)
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -772,16 +622,9 @@ public class AuthSteps(ScenarioContext scenario)
public async Task WhenISubmitARefreshTokenRequestUsingAGETRequest()
{
HttpClient client = GetClient();
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/auth/refresh"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/auth/refresh")
{
Content = new StringContent(
"{}",
Encoding.UTF8,
"application/json"
)
Content = new StringContent("{}", Encoding.UTF8, "application/json"),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -795,10 +638,7 @@ public class AuthSteps(ScenarioContext scenario)
public async Task WhenISubmitARequestToAProtectedEndpointWithoutAnAccessToken()
{
HttpClient client = GetClient();
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
);
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected");
HttpResponseMessage response = await client.SendAsync(requestMessage);
string responseBody = await response.Content.ReadAsStringAsync();
@@ -830,12 +670,9 @@ public class AuthSteps(ScenarioContext scenario)
? t
: "expired-token";
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected")
{
Headers = { { "Authorization", $"Bearer {token}" } }
Headers = { { "Authorization", $"Bearer {token}" } },
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -852,12 +689,9 @@ public class AuthSteps(ScenarioContext scenario)
? t
: "tampered-token";
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected")
{
Headers = { { "Authorization", $"Bearer {token}" } }
Headers = { { "Authorization", $"Bearer {token}" } },
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -876,12 +710,9 @@ public class AuthSteps(ScenarioContext scenario)
? t
: "refresh-token";
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected")
{
Headers = { { "Authorization", $"Bearer {token}" } }
Headers = { { "Authorization", $"Bearer {token}" } },
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -991,12 +822,9 @@ public class AuthSteps(ScenarioContext scenario)
? t
: "confirmation-token";
HttpRequestMessage requestMessage = new(
HttpMethod.Get,
"/api/protected"
)
HttpRequestMessage requestMessage = new(HttpMethod.Get, "/api/protected")
{
Headers = { { "Authorization", $"Bearer {token}" } }
Headers = { { "Authorization", $"Bearer {token}" } },
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
@@ -1049,54 +877,30 @@ public class AuthSteps(ScenarioContext scenario)
[Then("the response JSON should have a new access token")]
public void ThenTheResponseJsonShouldHaveANewAccessToken()
{
scenario
.TryGetValue<string>(ResponseBodyKey, out string? responseBody)
.Should()
.BeTrue();
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement payload = doc.RootElement.GetProperty("payload");
string accessToken = ParseTokenFromPayload(
payload,
"accessToken",
"AccessToken"
);
string accessToken = ParseTokenFromPayload(payload, "accessToken", "AccessToken");
accessToken.Should().NotBeNullOrWhiteSpace();
if (
scenario.TryGetValue<string>(
PreviousAccessTokenKey,
out string? previousAccessToken
)
)
if (scenario.TryGetValue<string>(PreviousAccessTokenKey, out string? previousAccessToken))
accessToken.Should().NotBe(previousAccessToken);
}
[Then("the response JSON should have a new refresh token")]
public void ThenTheResponseJsonShouldHaveANewRefreshToken()
{
scenario
.TryGetValue<string>(ResponseBodyKey, out string? responseBody)
.Should()
.BeTrue();
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement payload = doc.RootElement.GetProperty("payload");
string refreshToken = ParseTokenFromPayload(
payload,
"refreshToken",
"RefreshToken"
);
string refreshToken = ParseTokenFromPayload(payload, "refreshToken", "RefreshToken");
refreshToken.Should().NotBeNullOrWhiteSpace();
if (
scenario.TryGetValue<string>(
PreviousRefreshTokenKey,
out string? previousRefreshToken
)
)
if (scenario.TryGetValue<string>(PreviousRefreshTokenKey, out string? previousRefreshToken))
refreshToken.Should().NotBe(previousRefreshToken);
}
@@ -1186,4 +990,4 @@ public class AuthSteps(ScenarioContext scenario)
scenario[ResponseKey] = response;
scenario[ResponseBodyKey] = responseBody;
}
}
}

View File

@@ -20,7 +20,8 @@ public class TestApiFactory : WebApplicationFactory<Program>
d.ServiceType == typeof(IEmailProvider)
);
if (emailProviderDescriptor != null) services.Remove(emailProviderDescriptor);
if (emailProviderDescriptor != null)
services.Remove(emailProviderDescriptor);
services.AddScoped<IEmailProvider, MockEmailProvider>();
@@ -29,9 +30,10 @@ public class TestApiFactory : WebApplicationFactory<Program>
d.ServiceType == typeof(IEmailDispatcher)
);
if (emailDispatcherDescriptor != null) services.Remove(emailDispatcherDescriptor);
if (emailDispatcherDescriptor != null)
services.Remove(emailDispatcherDescriptor);
services.AddScoped<IEmailDispatcher, MockEmailDispatcher>();
});
}
}
}