Skip to content

Commit

Permalink
Format and minor refactoring of WebAppMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
tjementum committed Nov 17, 2023
1 parent 8b595b6 commit a9b7629
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 43 deletions.
5 changes: 0 additions & 5 deletions application/account-management/Api/Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@
</Content>
</ItemGroup>

<!-- <Target Name="InstallDependencies" BeforeTargets="Build" Condition="$(Configuration)=='Debug'">
<Exec Command="dotnet tool restore"/>
<Exec Command="bun install" WorkingDirectory="$(ProjectDir)/../WebApp/"/>
</Target> -->

<Target Name="CreateSwaggerJson" AfterTargets="Build">
<Exec Command="SWAGGER_GENERATOR=true dotnet swagger tofile --output $(OutputPath)swagger.json $(OutputPath)$(AssemblyName).dll v1" WorkingDirectory="$(ProjectDir)"/>
<Exec Command="bunx openapi-typescript@latest $(OutputPath)swagger.json -o ../WebApp/src/lib/api/api.generated.d.ts" WorkingDirectory="$(ProjectDir)"/>
Expand Down
2 changes: 1 addition & 1 deletion application/account-management/Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

// Add common configuration for all APIs like Swagger, HSTS, DeveloperExceptionPage, and run EF database migrations.
app.AddApiCoreConfiguration<AccountManagementDbContext>();
app.UseWebAppMiddleware("WebApp");
app.UseWebAppMiddleware();

app.MapTenantEndpoints();
app.MapUserEndpoints();
Expand Down
53 changes: 16 additions & 37 deletions application/shared-kernel/ApiCore/Middleware/WebAppMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,12 @@ public class WebAppMiddleware
private readonly Dictionary<string, string> _runtimeEnvironment;
private string? _htmlTemplate;

public WebAppMiddleware(
RequestDelegate next,
Dictionary<string, string> runtimeEnvironment,
string htmlTemplatePath
)
public WebAppMiddleware(RequestDelegate next, Dictionary<string, string> runtimeEnvironment,
string htmlTemplatePath)
{
_next = next;
_runtimeEnvironment = runtimeEnvironment;
_htmlTemplatePath = htmlTemplatePath;
_next = next;

VerifyRuntimeEnvironment(runtimeEnvironment);

Expand All @@ -47,14 +44,9 @@ private void VerifyRuntimeEnvironment(Dictionary<string, string> environmentVari
{
foreach (var key in environmentVariables.Keys)
{
if (key.StartsWith(PublicKeyPrefix) || _publicAllowedKeys.Contains(key))
{
continue;
}
if (key.StartsWith(PublicKeyPrefix) || _publicAllowedKeys.Contains(key)) continue;

throw new SecurityException(
$"Environment variable '{key}' is not allowed to be public."
);
throw new SecurityException($"Environment variable '{key}' is not allowed to be public.");
}
}

Expand Down Expand Up @@ -95,8 +87,7 @@ private StringValues GetContentSecurityPolicy()

return string.Join(
" ",
contentSecurityPolicies.Select(
policy => $"{policy.Key} {string.Join(" ", policy.Value)};"
contentSecurityPolicies.Select(policy => $"{policy.Key} {string.Join(" ", policy.Value)};"
)
);
}
Expand All @@ -117,19 +108,11 @@ public async Task InvokeAsync(HttpContext context)

public static class WebAppMiddlewareExtensions
{
private const string WebAppDistRootName = "dist";

[UsedImplicitly]
public static IApplicationBuilder UseWebAppMiddleware(
this IApplicationBuilder builder,
string webAppProjectName,
Dictionary<string, string>? publicEnvironmentVariables = null
)
public static IApplicationBuilder UseWebAppMiddleware(this IApplicationBuilder builder,
string webAppProjectName = "WebApp", Dictionary<string, string>? publicEnvironmentVariables = null)
{
if (Environment.GetEnvironmentVariable("SWAGGER_GENERATOR") == "true")
{
return builder;
}
if (Environment.GetEnvironmentVariable("SWAGGER_GENERATOR") == "true") return builder;

var publicUrl = GetEnvironmentVariableOrThrow(WebAppMiddleware.PublicUrlKey);
var cdnUrl = GetEnvironmentVariableOrThrow(WebAppMiddleware.CdnUrlKey);
Expand All @@ -150,7 +133,7 @@ public static IApplicationBuilder UseWebAppMiddleware(
}
}

var buildRootPath = GetWebAppDistRoot(webAppProjectName);
var buildRootPath = GetWebAppDistRoot(webAppProjectName, "dist");
var templateFilePath = Path.Combine(buildRootPath, "index.html");

if (!File.Exists(templateFilePath))
Expand All @@ -159,31 +142,27 @@ public static IApplicationBuilder UseWebAppMiddleware(
}

return builder
.UseStaticFiles(
new StaticFileOptions {FileProvider = new PhysicalFileProvider(buildRootPath)}
)
.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(buildRootPath) })
.UseMiddleware<WebAppMiddleware>(runtimeEnvironmentVariables, templateFilePath);
}

private static string GetEnvironmentVariableOrThrow(string variableName)
{
return Environment.GetEnvironmentVariable(variableName)
?? throw new InvalidOperationException(
$"Required environment variable '{variableName}' is not set."
);
?? throw new InvalidOperationException($"Required environment variable '{variableName}' is not set.");
}

private static string GetWebAppDistRoot(string webAppProjectName)
private static string GetWebAppDistRoot(string webAppProjectName, string webAppDistRootName)
{
var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;

var directoryInfo = new DirectoryInfo(assemblyPath);
while (directoryInfo != null && !directoryInfo.GetDirectories(webAppProjectName).Any() &&
!Path.Exists(Path.Join(directoryInfo.FullName, webAppProjectName, WebAppDistRootName)))
while (directoryInfo is not null && !directoryInfo.GetDirectories(webAppProjectName).Any() &&
!Path.Exists(Path.Join(directoryInfo.FullName, webAppProjectName, webAppDistRootName)))
{
directoryInfo = directoryInfo.Parent;
}

return Path.Join(directoryInfo!.FullName, webAppProjectName, WebAppDistRootName);
return Path.Join(directoryInfo!.FullName, webAppProjectName, webAppDistRootName);
}
}

0 comments on commit a9b7629

Please sign in to comment.