Skip to content

Commit

Permalink
2.8.0
Browse files Browse the repository at this point in the history
  • Loading branch information
vbilopav committed May 2, 2024
1 parent 0c335f1 commit 4f22e63
Show file tree
Hide file tree
Showing 18 changed files with 323 additions and 30 deletions.
10 changes: 10 additions & 0 deletions NpgsqlRest/MiddlewareExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
NpgsqlRest.IRoutineSourceParameterFormatter formatter
);
using NpgsqlRest.Auth;
using System.Reflection.PortableExecutable;

namespace NpgsqlRest;

Expand Down Expand Up @@ -460,6 +461,15 @@ public static IApplicationBuilder UseNpgsqlRest(this IApplicationBuilder builder
string? headers = null;
if (endpoint.RequestHeadersMode != RequestHeadersMode.Ignore)
{
if (options.CustomRequestHeaders.Count > 0)
{
foreach (var header in options.CustomRequestHeaders)
{
//context.Request?.Headers?.Append(header);
context.Request?.Headers?.Add(header);
}
}
headers = "{";
var i = 0;
foreach (var header in context.Request.Headers)

Check warning on line 475 in NpgsqlRest/MiddlewareExtension.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 475 in NpgsqlRest/MiddlewareExtension.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 475 in NpgsqlRest/MiddlewareExtension.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
Expand Down
8 changes: 4 additions & 4 deletions NpgsqlRest/NpgsqlRest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReadmeFile>README.MD</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(AssemblyName).xml</DocumentationFile>
<Version>2.7.1</Version>
<AssemblyVersion>2.7.1</AssemblyVersion>
<FileVersion>2.7.1</FileVersion>
<PackageVersion>2.7.1</PackageVersion>
<Version>2.8.0</Version>
<AssemblyVersion>2.8.0</AssemblyVersion>
<FileVersion>2.8.0</FileVersion>
<PackageVersion>2.8.0</PackageVersion>
</PropertyGroup>

<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
Expand Down
12 changes: 10 additions & 2 deletions NpgsqlRest/NpgsqlRestOptions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Npgsql;
using Microsoft.Extensions.Primitives;
using Npgsql;
using NpgsqlRest.Defaults;

namespace NpgsqlRest;
Expand Down Expand Up @@ -47,7 +48,8 @@ public class NpgsqlRestOptions(
NpgsqlRestAuthenticationOptions? authenticationOptions = null,
bool returnNpgsqlExceptionMessage = true,
Dictionary<string, int>? postgreSqlErrorCodeToHttpStatusCodeMapping = null,
Action<NpgsqlConnection, Routine, RoutineEndpoint, HttpContext>? beforeConnectionOpen = null)
Action<NpgsqlConnection, Routine, RoutineEndpoint, HttpContext>? beforeConnectionOpen = null,
Dictionary<string, StringValues>? customRequestHeaders = null)
{

/// <summary>
Expand Down Expand Up @@ -282,5 +284,11 @@ public NpgsqlRestOptions() : this(null)
/// </summary>
public Action<NpgsqlConnection, Routine, RoutineEndpoint, HttpContext>? BeforeConnectionOpen { get; set; } = beforeConnectionOpen;

/// <summary>
/// Custom request headers dictionary that will be added to NpgsqlRest requests.
/// Note: these values are added to the request headers dictionary before they are sent as a context or parameter to the PostgreSQL routine and as such not visible to the browser debugger.
/// </summary>
public Dictionary<string, StringValues> CustomRequestHeaders { get; set; } = customRequestHeaders ?? [];

internal List<IRoutineSource> RoutineSources { get; set; } = [new RoutineSource()];
}
37 changes: 37 additions & 0 deletions NpgsqlRestClient/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,25 @@ public static void Configure(WebApplication app, Action started)
{
app.UseSerilogRequestLogging();
}
var cfgCfg = Cfg.GetSection("Config");
var configEndpoint = GetConfigStr("ExposeAsEndpoint", cfgCfg);
if (configEndpoint is not null)
{
app.Use(async (context, next) =>
{
if (
string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase) &&
string.Equals(context.Request.Path, configEndpoint, StringComparison.OrdinalIgnoreCase))
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Json;
await context.Response.WriteAsync(Serialize());
await context.Response.CompleteAsync();
return;
}
await next(context);
});
}
}

public static void ConfigureStaticFiles(WebApplication app)
Expand Down Expand Up @@ -206,6 +225,24 @@ public static List<IEndpointCreateHandler> CreateCodeGenHandlers(string connecti
ts.HeaderLines = headerLines.ToList();
}

var skipRoutineNames = GetConfigEnumerable("SkipRoutineNames", tsClientCfg);
if (skipRoutineNames is not null)
{
ts.SkipRoutineNames = skipRoutineNames.ToArray();
}

var skipFunctionNames = GetConfigEnumerable("SkipFunctionNames", tsClientCfg);
if (skipFunctionNames is not null)
{
ts.SkipFunctionNames = skipFunctionNames.ToArray();
}

var skipPaths = GetConfigEnumerable("SkipPaths", tsClientCfg);
if (skipPaths is not null)
{
ts.SkipPaths = skipPaths.ToArray();
}

handlers.Add(new TsClient(ts));
}

Expand Down
11 changes: 11 additions & 0 deletions NpgsqlRestClient/Builder.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Npgsql;
using Serilog;
Expand Down Expand Up @@ -263,4 +264,14 @@ public static void BuildCors()

return connectionString;
}

public static Dictionary<string, StringValues> GetCustomHeaders()
{
var result = new Dictionary<string, StringValues>();
foreach(var section in NpgsqlRestCfg.GetSection("CustomRequestHeaders").GetChildren())
{
result.Add(section.Key, section.Value);
}
return result;
}
}
88 changes: 86 additions & 2 deletions NpgsqlRestClient/Config.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
namespace NpgsqlRestClient;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace NpgsqlRestClient;

public static class Config
{
Expand All @@ -9,7 +12,34 @@ public static class Config

public static void Build(string[] args)
{
var configBuilder = new ConfigurationBuilder().AddEnvironmentVariables();
IConfigurationBuilder configBuilder;
var tempBuilder = new ConfigurationBuilder();
IConfigurationRoot tempCfg;

if (args.Length > 0)
{
foreach (var (fileName, optional) in Arguments.EnumerateConfigFiles(args))
{
tempBuilder.AddJsonFile(Path.GetFullPath(fileName, CurrentDir), optional: optional);
}
tempCfg = tempBuilder.Build();
}
else
{
tempCfg = tempBuilder
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile("appsettings.Development.json", optional: true)
.Build();
}
var cfgCfg = tempCfg.GetSection("Config");
if (cfgCfg != null && GetConfigBool("AddEnvironmentVariables", cfgCfg))
{
configBuilder = new ConfigurationBuilder().AddEnvironmentVariables();
}
else
{
configBuilder = new ConfigurationBuilder();
}

if (args.Length > 0)
{
Expand Down Expand Up @@ -147,4 +177,58 @@ public static bool GetConfigBool(string key, IConfiguration? subsection = null,
}
return result;
}

public static string Serialize()
{
var json = SerializeConfig(Cfg);
return json?.ToJsonString(new JsonSerializerOptions() { WriteIndented = true }) ?? "{}";
}

private static JsonNode? SerializeConfig(IConfiguration config)
{
JsonObject obj = new();

foreach (var child in config.GetChildren())
{
if (child.Path.EndsWith(":0"))
{
var arr = new JsonArray();

foreach (var arrayChild in config.GetChildren())
{
arr.Add(SerializeConfig(arrayChild));
}

return arr;
}
else
{
obj.Add(child.Key, SerializeConfig(child));
}
}

if (obj.Count() == 0 && config is IConfigurationSection section)
{
if (bool.TryParse(section.Value, out bool boolean))
{
return JsonValue.Create(boolean);
}
else if (decimal.TryParse(section.Value, out decimal real))
{
return JsonValue.Create(real);
}
else if (long.TryParse(section.Value, out long integer))
{
return JsonValue.Create(integer);
}
if (section.Path.StartsWith("ConnectionStrings:"))
{
return JsonValue.Create(string.Join(';',
section?.Value?.Split(';')?.Where(p => p.StartsWith("password", StringComparison.OrdinalIgnoreCase) is false) ?? []));
}
return JsonValue.Create(section.Value);
}

return obj;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public static void Build(IConfigurationSection authConfig)
}
}

public static class ExternalAuthBuilder
public static class ExternalAuth
{
public static void Configure(WebApplication app, NpgsqlRestOptions options)
{
Expand All @@ -100,8 +100,7 @@ public static void Configure(WebApplication app, NpgsqlRestOptions options)

app.Use(async (context, next) =>
{
var config = ExternalAuthConfig.ClientConfigs[context.Request.Path];
if (config is null)
if (ExternalAuthConfig.ClientConfigs.TryGetValue(context.Request.Path, out var config) is false)
{
await next(context);
return;
Expand Down
2 changes: 1 addition & 1 deletion NpgsqlRestClient/NpgsqlRestClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<InvariantGlobalization>true</InvariantGlobalization>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<PublishAot>true</PublishAot>
<Version>1.1.0</Version>
<Version>1.2.0</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
6 changes: 4 additions & 2 deletions NpgsqlRestClient/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,12 @@
},

EndpointCreateHandlers = CreateCodeGenHandlers(connectionString),
SourcesCreated = SourcesCreated
SourcesCreated = SourcesCreated,

CustomRequestHeaders = GetCustomHeaders()
};

ExternalAuthBuilder.Configure(app, options);
ExternalAuth.Configure(app, options);

app.UseNpgsqlRest(options);
app.Run();
30 changes: 29 additions & 1 deletion NpgsqlRestClient/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@
//
"EnvironmentName": "Production",

"Config": {
//
// Expose current configuration to the endpoint for debugging and inspection. Note, the password in the connection string is not exposed.
//
"ExposeAsEndpoint": "/config",
//
// Add the environment variables to configuration first.
//
"AddEnvironmentVariables": false
},

"ConnectionStrings": {
//
// See https://www.npgsql.org/doc/connection-string-parameters.html
Expand Down Expand Up @@ -355,6 +366,11 @@
"PostgreSqlErrorCodeToHttpStatusCodeMapping": {
"57014": 205
},
//
// https://vb-consulting.github.io/npgsqlrest/options/#customrequestheaders
//
"CustomRequestHeaders": {
},

//
// Authentication options for NpgsqlRest endpoints
Expand Down Expand Up @@ -500,7 +516,19 @@
//
// Header lines on a each auto-generated source file. Default is ["// autogenerated at {0}", "", ""] where {0} is current timestamp.
//
"HeaderLines": null
"HeaderLines": null,
//
// Array of routine names to skip (without schema)
//
"SkipRoutineNames": [],
//
// Array of generated function names to skip
//
"SkipFunctionNames": [],
//
// Array of url paths to skip
//
"SkipPaths": []
},

//
Expand Down
Loading

0 comments on commit 4f22e63

Please sign in to comment.