forked from simplcommerce/SimplCommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceCollectionExtensions.cs
More file actions
302 lines (273 loc) · 13.8 KB
/
ServiceCollectionExtensions.cs
File metadata and controls
302 lines (273 loc) · 13.8 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using SimplCommerce.Infrastructure;
using SimplCommerce.Infrastructure.Modules;
using SimplCommerce.Infrastructure.Web.ModelBinders;
using SimplCommerce.Module.Core.Data;
using SimplCommerce.Module.Core.Extensions;
using SimplCommerce.Module.Core.Models;
using SimplCommerce.WebHost.IdentityServer;
namespace SimplCommerce.WebHost.Extensions
{
public static class ServiceCollectionExtensions
{
private static readonly IModuleConfigurationManager _modulesConfig = new ModuleConfigurationManager();
public static IServiceCollection AddModules(this IServiceCollection services)
{
foreach (var module in _modulesConfig.GetModules())
{
if(!module.IsBundledWithHost)
{
TryLoadModuleAssembly(module.Id, module);
if (module.Assembly == null)
{
throw new Exception($"Cannot find main assembly for module {module.Id}");
}
}
else
{
module.Assembly = Assembly.Load(new AssemblyName(module.Id));
}
GlobalConfiguration.Modules.Add(module);
}
return services;
}
public static IServiceCollection AddCustomizedMvc(this IServiceCollection services, IList<ModuleInfo> modules)
{
var mvcBuilder = services
.AddMvc(o =>
{
o.EnableEndpointRouting = false;
o.ModelBinderProviders.Insert(0, new InvariantDecimalModelBinderProvider());
})
.AddViewLocalization()
.AddModelBindingMessagesLocalizer(services)
.AddDataAnnotationsLocalization(o =>
{
var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = factory.Create(null);
o.DataAnnotationLocalizerProvider = (t, f) => L;
})
.AddNewtonsoftJson();
foreach (var module in modules.Where(x => !x.IsBundledWithHost))
{
AddApplicationPart(mvcBuilder, module.Assembly);
}
return services;
}
/// <summary>
/// Localize ModelBinding messages, e.g. when user enters string value instead of number...
/// these messages can't be localized like data attributes
/// </summary>
/// <param name="mvc"></param>
/// <param name="services"></param>
/// <returns></returns>
public static IMvcBuilder AddModelBindingMessagesLocalizer
(this IMvcBuilder mvc, IServiceCollection services)
{
return mvc.AddMvcOptions(o =>
{
var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = factory.Create(null);
o.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => L["The value '{0}' is invalid.", x]);
o.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => L["The field {0} must be a number.", x]);
o.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) => L["A value for the '{0}' property was not provided.", x]);
o.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => L["The value '{0}' is not valid for {1}.", x, y]);
o.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => L["A value is required."]);
o.ModelBindingMessageProvider.SetMissingRequestBodyRequiredValueAccessor(() => L["A non-empty request body is required."]);
o.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) => L["The value '{0}' is not valid.", x]);
o.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() => L["The value provided is invalid."]);
o.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() => L["The field must be a number."]);
o.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => L["The supplied value is invalid for {0}.", x]);
o.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) => L["Null value is invalid."]);
});
}
private static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly)
{
var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly);
foreach (var part in partFactory.GetApplicationParts(assembly))
{
mvcBuilder.PartManager.ApplicationParts.Add(part);
}
var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false);
foreach (var relatedAssembly in relatedAssemblies)
{
partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly);
foreach (var part in partFactory.GetApplicationParts(relatedAssembly))
{
mvcBuilder.PartManager.ApplicationParts.Add(part);
}
}
}
public static IServiceCollection AddCustomizedIdentity(this IServiceCollection services, IConfiguration configuration)
{
services
.AddIdentity<User, Role>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 0;
options.ClaimsIdentity.UserNameClaimType = JwtRegisteredClaimNames.Sub;
})
.AddRoleStore<SimplRoleStore>()
.AddUserStore<SimplUserStore>()
.AddSignInManager<SimplSignInManager<User>>()
.AddDefaultTokenProviders();
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddInMemoryIdentityResources(IdentityServerConfig.Ids)
.AddInMemoryApiResources(IdentityServerConfig.Apis)
.AddInMemoryClients(IdentityServerConfig.Clients)
.AddAspNetIdentity<User>()
.AddProfileService<SimplProfileService>()
.AddDeveloperSigningCredential(); // not recommended for production - you need to store your key material somewhere secure
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie()
.AddFacebook(x =>
{
x.AppId = configuration["Authentication:Facebook:AppId"];
x.AppSecret = configuration["Authentication:Facebook:AppSecret"];
x.Events = new OAuthEvents
{
OnRemoteFailure = ctx => HandleRemoteLoginFailure(ctx)
};
})
.AddGoogle(x =>
{
x.ClientId = configuration["Authentication:Google:ClientId"];
x.ClientSecret = configuration["Authentication:Google:ClientSecret"];
x.Events = new OAuthEvents
{
OnRemoteFailure = ctx => HandleRemoteLoginFailure(ctx)
};
})
.AddLocalApi(JwtBearerDefaults.AuthenticationScheme, option => {
option.ExpectedScope = "api.simplcommerce";
});
services.ConfigureApplicationCookie(x =>
{
x.LoginPath = new PathString("/login");
x.Events.OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase) && context.Response.StatusCode == (int)HttpStatusCode.OK)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.CompletedTask;
}
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
};
x.Events.OnRedirectToAccessDenied = context =>
{
if (context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase) && context.Response.StatusCode == (int)HttpStatusCode.OK)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return Task.CompletedTask;
}
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
};
});
return services;
}
public static IServiceCollection AddCustomizedDataStore(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContextPool<SimplDbContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("SimplCommerce.WebHost"));
options.EnableSensitiveDataLogging();
});
return services;
}
/// <summary>
/// Discovers and configures all modules in the application by finding and initializing their module initializers.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add module services to.</param>
/// <returns>The same service collection so that multiple calls can be chained.</returns>
public static IServiceCollection ConfigureModules(this IServiceCollection services)
{
foreach (var module in GlobalConfiguration.Modules)
{
var moduleInitializerType = module.Assembly.GetTypes()
.FirstOrDefault(t => typeof(IModuleInitializer).IsAssignableFrom(t));
if (moduleInitializerType != null && moduleInitializerType != typeof(IModuleInitializer))
{
var moduleInitializer = (IModuleInitializer)Activator.CreateInstance(moduleInitializerType);
services.AddSingleton(typeof(IModuleInitializer), moduleInitializer);
moduleInitializer.ConfigureServices(services);
}
}
return services;
}
private static void TryLoadModuleAssembly(string moduleFolderPath, ModuleInfo module)
{
const string binariesFolderName = "bin";
var binariesFolderPath = Path.Combine(moduleFolderPath, binariesFolderName);
var binariesFolder = new DirectoryInfo(binariesFolderPath);
if (Directory.Exists(binariesFolderPath))
{
foreach (var file in binariesFolder.GetFileSystemInfos("*.dll", SearchOption.AllDirectories))
{
Assembly assembly;
try
{
assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file.FullName);
}
catch (FileLoadException)
{
// Get loaded assembly. This assembly might be loaded
assembly = Assembly.Load(new AssemblyName(Path.GetFileNameWithoutExtension(file.Name)));
if (assembly == null)
{
throw;
}
string loadedAssemblyVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
string tryToLoadAssemblyVersion = FileVersionInfo.GetVersionInfo(file.FullName).FileVersion;
// Or log the exception somewhere and don't add the module to list so that it will not be initialized
if (tryToLoadAssemblyVersion != loadedAssemblyVersion)
{
throw new Exception($"Cannot load {file.FullName} {tryToLoadAssemblyVersion} because {assembly.Location} {loadedAssemblyVersion} has been loaded");
}
}
if (Path.GetFileNameWithoutExtension(assembly.ManifestModule.Name) == module.Id)
{
module.Assembly = assembly;
}
}
}
}
private static Task HandleRemoteLoginFailure(RemoteFailureContext ctx)
{
ctx.Response.Redirect("/login");
ctx.HandleResponse();
return Task.CompletedTask;
}
}
}