Skip to content

Commit

Permalink
fix: Removed usage of HttpClient.DefaultRequestHeaders.
Browse files Browse the repository at this point in the history
  • Loading branch information
HavenDV committed Oct 1, 2024
1 parent 77e969e commit 7a64774
Show file tree
Hide file tree
Showing 1,773 changed files with 12,534 additions and 484 deletions.
14 changes: 14 additions & 0 deletions src/libs/AutoSDK/Models/Authorization.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Immutable;
using AutoSDK.Extensions;
using Microsoft.OpenApi.Models;

Expand All @@ -7,11 +8,14 @@ public readonly record struct Authorization(
string FriendlyName,
SecuritySchemeType Type,
ParameterLocation In,
EquatableArray<string> Parameters,
string Name,
string Scheme,
Settings Settings
)
{
public string MethodName => $"AuthorizeUsing{FriendlyName}";

public static Authorization FromOpenApiSecurityScheme(
OpenApiSecurityScheme scheme,
Settings settings)
Expand All @@ -27,15 +31,25 @@ public static Authorization FromOpenApiSecurityScheme(
(SecuritySchemeType.OAuth2, _, _) => "OAuth2",
_ => scheme.Scheme?.ToPropertyName() ?? string.Empty,
};
string[] parameters = (scheme.Type, scheme.Scheme, scheme.In) switch
{
(SecuritySchemeType.Http, "bearer", _) => ["apiKey"],
(SecuritySchemeType.Http, "basic", _) => ["username", "password"],
(SecuritySchemeType.ApiKey, _, ParameterLocation.Header) => ["apiKey"],
(SecuritySchemeType.ApiKey, _, ParameterLocation.Query) => ["apiKey"],
_ => [],
};

return new Authorization(
FriendlyName: friendlyName,
Type: scheme.Type,
In: (scheme.Type, scheme.Scheme) switch
{
(SecuritySchemeType.Http, "bearer") => ParameterLocation.Header,
(SecuritySchemeType.OAuth2, _) => ParameterLocation.Header,
_ => scheme.In,
},
Parameters: parameters.ToImmutableArray().AsEquatableArray(),
Name: scheme.Name ?? string.Empty,
Scheme: scheme.Scheme ?? string.Empty,
Settings: settings);
Expand Down
133 changes: 48 additions & 85 deletions src/libs/AutoSDK/Sources/Sources.Authorizations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,70 +9,32 @@ public static partial class Sources
public static string GenerateAuthorization(
Authorization authorization)
{
var body = (authorization.Type, authorization.Scheme, authorization.In) switch
if (authorization.Type is SecuritySchemeType.OAuth2 or SecuritySchemeType.OpenIdConnect)
{
(SecuritySchemeType.Http, "bearer", _) => $@"
/// <summary>
/// Authorize using bearer authentication.
/// </summary>
/// <param name=""apiKey""></param>
public void AuthorizeUsingBearer(
string apiKey)
{{
apiKey = apiKey ?? throw new global::System.ArgumentNullException(nameof(apiKey));
_httpClient.DefaultRequestHeaders.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: ""Bearer"",
parameter: apiKey);
}}",
(SecuritySchemeType.Http, "basic", _) => $@"
/// <summary>
/// Authorize using basic authentication.
/// </summary>
/// <param name=""username""></param>
/// <param name=""password""></param>
public void AuthorizeUsingBasic(
string username,
string password)
{{
username = username ?? throw new global::System.ArgumentNullException(nameof(username));
password = password ?? throw new global::System.ArgumentNullException(nameof(password));
_httpClient.DefaultRequestHeaders.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: ""Basic"",
parameter: global::System.Convert.ToBase64String(
global::System.Text.Encoding.UTF8.GetBytes($""{{username}}:{{password}}"")));
}}",
(SecuritySchemeType.ApiKey, _, ParameterLocation.Header) => $@"
/// <summary>
/// Authorize using ApiKey authentication.
/// </summary>
/// <param name=""apiKey""></param>
public void AuthorizeUsingApiKey(
string apiKey)
{{
apiKey = apiKey ?? throw new global::System.ArgumentNullException(nameof(apiKey));
_httpClient.DefaultRequestHeaders.Add(""{authorization.Name}"", apiKey);
}}",
(SecuritySchemeType.ApiKey, _, ParameterLocation.Query) or
(SecuritySchemeType.ApiKey, _, ParameterLocation.Path) => $@"
/// <summary>
/// Authorize using ApiKey authentication.
/// </summary>
/// <param name=""apiKey""></param>
public void AuthorizeUsingApiKey(
string apiKey)
{{
apiKey = apiKey ?? throw new global::System.ArgumentNullException(nameof(apiKey));
_authorization = new global::{authorization.Settings.Namespace}.EndPointAuthorization
{{
Name = ""{authorization.Name}"",
Value = apiKey,
}};
}}",
_ => " ",
return string.Empty;
}

var name = (authorization.Type, authorization.Scheme, authorization.In) switch
{
(SecuritySchemeType.Http, "bearer", _) => "Bearer",
(SecuritySchemeType.Http, "basic", _) => "Basic",
(SecuritySchemeType.ApiKey, _, _) => authorization.Name,
_ => string.Empty,
};
var value = (authorization.Type, authorization.Scheme, authorization.In) switch
{
(SecuritySchemeType.Http, "bearer", _) => "apiKey",
(SecuritySchemeType.Http, "basic", _) => @"global::System.Convert.ToBase64String(
global::System.Text.Encoding.UTF8.GetBytes($""{username}:{password}""))",
(SecuritySchemeType.ApiKey, _, _) => "apiKey",
_ => string.Empty,
};
var xmlDocs = (authorization.Type, authorization.Scheme, authorization.In) switch
{
(SecuritySchemeType.Http, "bearer", _) => "Authorize using bearer authentication.",
(SecuritySchemeType.Http, "basic", _) => "Authorize using basic authentication.",
(SecuritySchemeType.ApiKey, _, _) => "Authorize using ApiKey authentication.",
_ => string.Empty,
};

return $@"
Expand All @@ -82,31 +44,32 @@ namespace {authorization.Settings.Namespace}
{{
public sealed partial class {authorization.Settings.ClassName}
{{
{body}
/// <summary>
/// {xmlDocs}
/// </summary>
{authorization.Parameters.Select(x => $@"
/// <param name=""{x}""></param>").Inject()}
public void {authorization.MethodName}(
{authorization.Parameters.Select(x => $@"
string {x},").Inject().TrimEnd(',')})
{{
{authorization.Parameters.Select(x => $@"
{x} = {x} ?? throw new global::System.ArgumentNullException(nameof({x}));").Inject()}
_authorization = new global::{authorization.Settings.Namespace}.EndPointAuthorization
{{
Name = ""{name}"",
Value = {value},
}};
}}
}}
}}".RemoveBlankLinesWhereOnlyWhitespaces();
}

public static string GenerateMainAuthorizationConstructor(
Authorization authorization)
{
var methodName = (authorization.Type, authorization.Scheme, authorization.In) switch
{
(SecuritySchemeType.Http, "bearer", _) => "AuthorizeUsingBearer",
(SecuritySchemeType.Http, "basic", _) => "AuthorizeUsingBasic",
(SecuritySchemeType.ApiKey, _, ParameterLocation.Header) => "AuthorizeUsingApiKey",
(SecuritySchemeType.ApiKey, _, ParameterLocation.Query) => "AuthorizeUsingApiKey",
_ => string.Empty,
};
string[] parameters = (authorization.Type, authorization.Scheme, authorization.In) switch
{
(SecuritySchemeType.Http, "bearer", _) => ["apiKey"],
(SecuritySchemeType.Http, "basic", _) => ["username", "password"],
(SecuritySchemeType.ApiKey, _, ParameterLocation.Header) => ["apiKey"],
(SecuritySchemeType.ApiKey, _, ParameterLocation.Query) => ["apiKey"],
_ => [],
};
if (parameters.Length == 0)
if (authorization.Parameters.IsEmpty)
{
return string.Empty;
}
Expand All @@ -120,21 +83,21 @@ public sealed partial class {authorization.Settings.ClassName}
{{
/// <inheritdoc cref=""{authorization.Settings.ClassName}(global::System.Net.Http.HttpClient?, global::System.Uri?)""/>
public {authorization.Settings.ClassName}(
{string.Join("\n", parameters.Select(x => $@"
{string.Join("\n", authorization.Parameters.Select(x => $@"
string {x},"))}
global::System.Net.Http.HttpClient? httpClient = null,
global::System.Uri? baseUri = null) : this(httpClient, baseUri)
{{
Authorizing(_httpClient, {string.Join(", ", parameters.Select(x => $"ref {x}"))});
Authorizing(_httpClient, {string.Join(", ", authorization.Parameters.Select(x => $"ref {x}"))});
{methodName}({string.Join(", ", parameters.Select(x => $"{x}"))});
{authorization.MethodName}({string.Join(", ", authorization.Parameters.Select(x => $"{x}"))});
Authorized(_httpClient);
}}
partial void Authorizing(
global::System.Net.Http.HttpClient client,
{string.Join("\n", parameters.Select(x => $@"
{string.Join("\n", authorization.Parameters.Select(x => $@"
ref string {x},")).TrimEnd(',')});
partial void Authorized(
global::System.Net.Http.HttpClient client);
Expand Down
29 changes: 20 additions & 9 deletions src/libs/AutoSDK/Sources/Sources.Methods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,16 @@ public static string GenerateMethod(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: {GetHttpMethod(endPoint.Settings.TargetFramework, endPoint.HttpMethod)},
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
{(endPoint.Authorizations.Any(x => x is
{ Type: SecuritySchemeType.ApiKey, In: ParameterLocation.Header } or
{ Type: SecuritySchemeType.Http } or
{ Type: SecuritySchemeType.OAuth2 }) ? @"
if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}" : " ")}
{(endPoint.Parameters.Any(x => x is { Location: ParameterLocation.Header }) ? "" : " ")}
{endPoint.Parameters
.Where(x => x is { Location: ParameterLocation.Header, IsRequired: true })
Expand Down Expand Up @@ -290,25 +300,27 @@ public static string GeneratePathAndQuery(
var __pathBuilder = new PathBuilder(
path: {endPoint.Path},
baseUri: _httpClient.BaseAddress);";
if (endPoint.Authorizations.Any(x => x is { Type: SecuritySchemeType.ApiKey, In: ParameterLocation.Query }))
{
code += @"
if (_authorization != null)
{
__pathBuilder = __pathBuilder.AddRequiredParameter(_authorization.Name, _authorization.Value);
}";
}

var queryParameters = endPoint.QueryParameters
.Where(x =>
x.Type.IsEnum ||
(!x.Type.IsArray || (x.Type.SubTypes[0].Properties.Length == 0 && !x.Type.SubTypes[0].IsArray)))
.ToArray();

if (queryParameters.Length > 0 ||
endPoint.Authorizations.Any(x => x is { Type: SecuritySchemeType.ApiKey, In: ParameterLocation.Query }))
if (queryParameters.Length > 0)
{
code += @"
__pathBuilder";
}

if (endPoint.Authorizations.Any(x => x is { Type: SecuritySchemeType.ApiKey, In: ParameterLocation.Query }))
{
code += @"
.AddRequiredParameter(_authorization!.Name, _authorization!.Value)";
}
foreach (var parameter in queryParameters)
{
var additionalArguments = parameter.Type.IsArray
Expand All @@ -330,8 +342,7 @@ public static string GeneratePathAndQuery(
}
}

if (queryParameters.Length > 0 ||
endPoint.Authorizations.Any(x => x is { Type: SecuritySchemeType.ApiKey, In: ParameterLocation.Query }))
if (queryParameters.Length > 0)
{
code += @"
;";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ public void AuthorizeUsingBearer(
{
apiKey = apiKey ?? throw new global::System.ArgumentNullException(nameof(apiKey));

_httpClient.DefaultRequestHeaders.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: "Bearer",
parameter: apiKey);
_authorization = new global::G.EndPointAuthorization
{
Name = "Bearer",
Value = apiKey,
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ partial void ProcessConvertDocumentFileStudioV1ChatFilesConvertPostResponseConte
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
using var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.Files, x => x))}]"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ partial void ProcessV1AnswerResponseContent(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
var __httpRequestContentBody = global::Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerOptions);
var __httpRequestContent = new global::System.Net.Http.StringContent(
content: __httpRequestContentBody,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ partial void ProcessV1ConversationalRagResponseContent(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
var __httpRequestContentBody = global::Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerOptions);
var __httpRequestContent = new global::System.Net.Http.StringContent(
content: __httpRequestContentBody,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ partial void ProcessV1EmbedResponseContent(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
var __httpRequestContentBody = global::Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerOptions);
var __httpRequestContent = new global::System.Net.Http.StringContent(
content: __httpRequestContentBody,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ partial void ProcessV1J2UltraChatResponseContent(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
var __httpRequestContentBody = global::Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerOptions);
var __httpRequestContent = new global::System.Net.Http.StringContent(
content: __httpRequestContentBody,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ partial void ProcessV1J2GrandeCompleteResponseContent(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
var __httpRequestContentBody = global::Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerOptions);
var __httpRequestContent = new global::System.Net.Http.StringContent(
content: __httpRequestContentBody,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ partial void ProcessV1J2GrandeCustomModelCompleteResponseContent(
using var httpRequest = new global::System.Net.Http.HttpRequestMessage(
method: global::System.Net.Http.HttpMethod.Post,
requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));

if (_authorization != null)
{{
httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
scheme: _authorization.Name,
parameter: _authorization.Value);
}}
var __httpRequestContentBody = global::Newtonsoft.Json.JsonConvert.SerializeObject(request, JsonSerializerOptions);
var __httpRequestContent = new global::System.Net.Http.StringContent(
content: __httpRequestContentBody,
Expand Down
Loading

0 comments on commit 7a64774

Please sign in to comment.