-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathStartupExtensions.cs
More file actions
201 lines (174 loc) · 7.49 KB
/
StartupExtensions.cs
File metadata and controls
201 lines (174 loc) · 7.49 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
195
196
197
198
199
200
201
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using AutoMapper;
using HwProj.EventBus.Client;
using HwProj.EventBus.Client.Implementations;
using HwProj.EventBus.Client.Interfaces;
using HwProj.Utils.Auth;
using HwProj.Utils.Configuration.Middleware;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Polly;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using Swashbuckle.AspNetCore.Swagger;
namespace HwProj.Utils.Configuration
{
public static class StartupExtensions
{
public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services, string serviceName)
{
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
.AddCors()
.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = serviceName, Version = "v1" });
if (serviceName == "API Gateway")
{
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter into field the word 'Bearer' following by space and JWT",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", Enumerable.Empty<string>() },
});
}
});
if (serviceName != "AuthService API")
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false; //TODO: dev env setting
x.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "AuthService",
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
IssuerSigningKey = AuthorizationKey.SecurityKey,
ValidateIssuerSigningKey = true
};
});
}
services.AddTransient<NoApiGatewayMiddleware>();
services.AddHttpContextAccessor();
return services;
}
public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
{
var eventBusSection = configuration.GetSection("EventBus");
var retryCount = 5;
if (!string.IsNullOrEmpty(eventBusSection["EventBusRetryCount"]))
{
retryCount = int.Parse(eventBusSection["EventBusRetryCount"]);
}
services.AddSingleton(sp => Policy.Handle<SocketException>()
.Or<BrokerUnreachableException>()
.WaitAndRetry(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
services.AddSingleton<IConnectionFactory, ConnectionFactory>(sp => new ConnectionFactory
{
HostName = eventBusSection["EventBusHostName"],
UserName = eventBusSection["EventBusUserName"],
Password = eventBusSection["EventBusPassword"],
VirtualHost = eventBusSection["EventBusVirtualHost"]
});
services.AddSingleton<IDefaultConnection, DefaultConnection>();
services.AddSingleton<IEventBus, EventBusRabbitMq>();
var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).ToList();
var eventTypes = types.Where(x => typeof(Event).IsAssignableFrom(x));
foreach (var eventType in eventTypes)
{
var fullTypeInterface = typeof(IEventHandler<>).MakeGenericType(eventType);
var handlersTypes = types.Where(x =>
fullTypeInterface.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract);
foreach (var handlerType in handlersTypes)
{
services.AddTransient(handlerType);
}
}
return services;
}
public static IApplicationBuilder ConfigureHwProj(this IApplicationBuilder app, IHostingEnvironment env,
string serviceName, DbContext? context = null)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage()
.UseSwagger()
.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", serviceName); });
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseMvc();
if (context != null)
{
if (env.IsDevelopment())
{
context.Database.EnsureCreated();
return app;
}
var logger = app.ApplicationServices
.GetService<ILoggerFactory>()
.CreateLogger(typeof(StartupExtensions));
var tries = 0;
const int maxTries = 100;
while (!context.Database.CanConnect() && ++tries <= maxTries)
{
logger.LogWarning($"Can't connect to database. Try {tries}.");
Thread.Sleep(5000);
}
if (tries > maxTries) throw new Exception("Can't connect to database");
context.Database.Migrate();
}
return app;
}
public static AuthenticationBuilder AddUserIdAuthentication(this AuthenticationBuilder builder)
{
builder
.AddScheme<UserIdAuthenticationOptions, UserIdAuthenticationHandler>(
AuthSchemeConstants.UserIdAuthentication, null);
return builder;
}
public static AuthenticationBuilder AddGuestModeAuthentication(this AuthenticationBuilder builder)
{
builder
.AddScheme<GuestModeAuthenticationOptions, GuestModeAuthenticationHandler>(
AuthSchemeConstants.GuestModeAuthentication, null);
return builder;
}
}
}