-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExtensions.cs
More file actions
194 lines (169 loc) · 8.17 KB
/
Extensions.cs
File metadata and controls
194 lines (169 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using System.Security.Claims;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using TeachingRecordSystem.Api.Infrastructure.ApplicationModel;
using TeachingRecordSystem.Api.Infrastructure.Filters;
using TeachingRecordSystem.Api.Infrastructure.ModelBinding;
using TeachingRecordSystem.Api.Infrastructure.OpenApi;
using TeachingRecordSystem.Api.Infrastructure.RateLimiting;
using TeachingRecordSystem.Api.Infrastructure.Security;
using TeachingRecordSystem.Api.V3.Implementation.Operations;
using TeachingRecordSystem.Api.Validation;
using TeachingRecordSystem.Core.Infrastructure.Json;
using TeachingRecordSystem.Core.Services.GetAnIdentity;
using TeachingRecordSystem.Core.Services.Webhooks;
using TeachingRecordSystem.WebCommon.Filters;
namespace TeachingRecordSystem.Api;
public static class Extensions
{
public static IServiceCollection AddApiCommands(this IServiceCollection services)
{
services.Scan(scan =>
scan.FromAssemblyOf<Program>()
.AddClasses(filter => filter.AssignableTo(typeof(ICommandHandler<,>)))
.AsImplementedInterfaces()
.WithTransientLifetime());
services.AddTransient<ICommandDispatcher, CommandDispatcher>();
return services;
}
public static IHostApplicationBuilder AddApiServices(this IHostApplicationBuilder builder)
{
builder.Services.AddApiServices(builder.Configuration, builder.Environment);
return builder;
}
public static IServiceCollection AddApiServices(this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment)
{
services
.AddMvc(options =>
{
options.AddHybridBodyModelBinderProvider();
options.Filters.Add(new ServiceFilterAttribute<AddTrnToSentryScopeResourceFilter>() { Order = -1 });
options.Filters.Add(new DefaultErrorExceptionFilter(statusCode: StatusCodes.Status400BadRequest));
options.Filters.Add(new ValidationExceptionFilter());
options.Conventions.Add(new ApiVersionConvention(configuration));
options.Conventions.Add(new AuthorizationPolicyConvention());
options.Conventions.Add(new BackFillVersionedEndpointsConvention());
options.Filters.Add(new NoCachePageFilter());
options.OutputFormatters.RemoveType<StringOutputFormatter>();
})
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressInferBindingSourcesForParameters = true;
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.Converters.Add(new OneOfJsonConverterFactory());
options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver()
{
Modifiers =
{
Modifiers.OptionProperties
}
};
});
services.Decorate<Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory, CamelCaseErrorKeysProblemDetailsFactory>();
services.AddAuthentication(ApiKeyAuthenticationHandler.AuthenticationScheme)
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationHandler.AuthenticationScheme, _ => { })
.AddJwtBearer(AuthenticationSchemeNames.IdAccessToken, options =>
{
options.Authority = configuration["GetAnIdentity:BaseAddress"];
options.MapInboundClaims = false;
options.TokenValidationParameters.ValidateAudience = false;
options.TokenValidationParameters.RequireExpirationTime = false;
})
.AddJwtBearer(AuthenticationSchemeNames.AuthorizeAccessAccessToken, options =>
{
options.Authority = configuration.GetRequiredValue("AuthorizeAccessIssuer");
options.MapInboundClaims = false;
options.TokenValidationParameters.ValidateAudience = false;
});
services.AddAuthorization(options =>
{
options.AddPolicy(
AuthorizationPolicies.ApiKey,
policy => policy
.AddAuthenticationSchemes(ApiKeyAuthenticationHandler.AuthenticationScheme)
.RequireClaim(ClaimTypes.Name));
options.AddPolicy(
AuthorizationPolicies.IdentityUserWithTrn,
policy => policy
.AddAuthenticationSchemes(AuthenticationSchemeNames.IdAccessToken, AuthenticationSchemeNames.AuthorizeAccessAccessToken)
.RequireAssertion(ctx =>
{
var scopes = (ctx.User.FindFirstValue("scope") ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var isIdUser = scopes.Contains("dqt:read") && ctx.User.HasClaim(c => c.Type == "trn");
var isAuthorizeAccessUser = scopes.Contains("teaching_record");
return isIdUser || isAuthorizeAccessUser;
}));
});
services
.AddApiCommands()
.AddWebhookOptions(configuration)
.AddOpenApi(configuration)
.AddFluentValidation()
.AddApiMappers()
.AddHttpContextAccessor()
.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>())
.AddSingleton<ICurrentUserProvider, ClaimsPrincipalCurrentUserProvider>()
.AddMemoryCache()
.AddSingleton<AddTrnToSentryScopeResourceFilter>()
.AddTransient<GetPersonHelper>()
.AddEvidenceFilesHttpClient(configuration);
if (environment.IsProduction())
{
services
.AddStartupTask<ReferenceDataCache>()
.AddRateLimiting(configuration);
}
if (!environment.IsTests() && !environment.IsEndToEndTests())
{
services.AddIdentityApi(configuration);
}
return services;
}
private static IServiceCollection AddApiMappers(this IServiceCollection services)
{
services
.AddSingleton<V3.V20240101.ApiMapper>()
.AddSingleton<V3.V20240307.ApiMapper>()
.AddSingleton<V3.V20240412.ApiMapper>()
.AddSingleton<V3.V20240416.ApiMapper>()
.AddSingleton<V3.V20240606.ApiMapper>()
.AddSingleton<V3.V20240814.ApiMapper>()
.AddSingleton<V3.V20240912.ApiMapper>()
.AddSingleton<V3.V20240920.ApiMapper>()
.AddSingleton<V3.V20250203.ApiMapper>()
.AddSingleton<V3.V20250327.ApiMapper>()
.AddSingleton<V3.V20250425.ApiMapper>()
.AddSingleton<V3.V20250627.ApiMapper>();
return services;
}
private static IServiceCollection AddEvidenceFilesHttpClient(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<EvidenceFilesOptions>()
.Bind(configuration.GetSection("EvidenceFiles"))
.ValidateDataAnnotations()
.ValidateOnStart();
services
.AddTransient<DownloadEvidenceFilesFromBlobStorageHttpHandler>()
.AddHttpClient("EvidenceFiles", client =>
{
client.MaxResponseContentBufferSize = 5 * 1024 * 1024; // 5MB
client.Timeout = TimeSpan.FromSeconds(30);
})
.AddHttpMessageHandler<DownloadEvidenceFilesFromBlobStorageHttpHandler>();
return services;
}
private static IServiceCollection AddFluentValidation(this IServiceCollection services)
{
services.AddFluentValidationAutoValidation(options => options.DisableDataAnnotationsValidation = true)
.AddValidatorsFromAssemblyContaining(typeof(Program))
.AddTransient<IValidatorInterceptor, PreferModelBindingErrorsValidationInterceptor>();
return services;
}
}