-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartup.cs
More file actions
262 lines (228 loc) · 10.8 KB
/
Startup.cs
File metadata and controls
262 lines (228 loc) · 10.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
using System;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using ShoppingListServer.Database;
using ShoppingListServer.Helpers;
using ShoppingListServer.Services;
using ShoppingListServer.LiveUpdates;
using ShoppingListServer.Services.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http.Features;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
namespace ShoppingListServer
{
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
Environment = env;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; }
public static ServiceProvider _serviceProvider;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
services.AddCors();
services.AddControllers();
// Replaced asp .net core 2.0 AddMvc()
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllersWithViews();
// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false
};
// API Key AUTH.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is on update hub
// TO DO get rout from config
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/shoppingserver/update")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddSignalR();
// configure DI for application services
// Scoped services are created once per request.
services.AddScoped<IFilesystemService, FilesystemService>();
services.AddScoped<IShoppingListStorageService, ShoppingListStorageSevice>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IRestService, RestService>();
services.AddScoped<IEMailVerificationService, EMailVerificationService>();
services.AddScoped<IResetPasswordService, ResetPasswordService>();
services.AddScoped<IShoppingService, ShoppingService>();
// Transient services are created each time they are requested.
services.AddTransient<IUserHub, UserHubService>();
services.AddTransient<IShoppingHub, ShoppingHubService>();
services.AddTransient<IPushNotificationService, PushNotificationService>();
services.AddTransient<IAuthenticationService, AuthenticationService>();
//_serviceProvider = services.BuildServiceProvider();
// MySql database
// Pomelo.EntityFrameworkCore.MySql: https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql
// A MySql database must be setup in the system with a name and user access specified in appsettings.json
//string dbServerAddress = appSettings.UseDocker == "False" ? appSettings.DbServerAddress : appSettings.DbServerAddressDocker;
string dbServerAddress = appSettings.UseDocker == "False" ? appSettings.DbServerAddress : appSettings.DbServerAddressDocker;
string connectionString = dbServerAddress +
"user=" + appSettings.DbUser + ";" +
"password=" + appSettings.DbPassword + ";" +
"database=" + appSettings.DbName + ";";
// Console.WriteLine("Database connection string = " + connectionString);
services.AddDbContextPool<AppDb>(
options => {
options.UseLazyLoadingProxies();
bool useSQLite = Configuration.GetValue<bool>("UseSQLite");
if (useSQLite)
{
options.UseSqlite("Data Source=shoppinglist.db");
}
else
{
ServerVersion service_version = ServerVersion.AutoDetect(connectionString);
options.UseMySql(
connectionString,
service_version,
mysqlOptions =>
{
// mysqlOptions.CharSetBehavior(CharSetBehavior.NeverAppend);
// mysqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(5), null);
});
}
options
#if DEBUG
.EnableDetailedErrors()
#endif
;
if (env.IsDevelopment())
{
options.EnableSensitiveDataLogging();
}
});
Console.WriteLine("Network adapter prioritization:");
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
Console.WriteLine(ni.NetworkInterfaceType.ToString());
}
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// All non handled exceptions in the controllers are handled by simply responding with the exceptions message.
// https://stackoverflow.com/a/55166404
// https://stackoverflow.com/a/38935583
app.UseExceptionHandler(c => c.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature.Error;
// Setting the reason phrase: https://stackoverflow.com/a/42039124
context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = exception.Message;
context.Response.ContentType = "application/json";
await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(exception.Message));
}));
// Handle all other non cached exceptions
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Unhandled_Exceptions);
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
// Server accessibility on browser routes
// Define new StaticFileOptions to enable access of files with no ending (apple-app-site-association)
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "text/plain"
});
var appSettingsSection = Configuration.GetSection("AppSettings");
var appSettings = appSettingsSection.Get<AppSettings>();
if (appSettings.UseHttpsRedirect == "True")
app.UseHttpsRedirection();
#if DEBUG
// This overwrites the exception handler from the call app.UseExceptionHandler() above.
//app.UseDeveloperExceptionPage();
app.UseHsts();
#else
app.UseHsts();
#endif
try
{
bool useFirebase = Configuration.GetValue<bool>("UseFirebase");
if (useFirebase)
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
}
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to initialize Firebase.\n" + ex.StackTrace);
}
// SignalR/Websockets
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<UpdateHub_Controller>("/shoppingserver/update");
endpoints.MapControllers();
});
Console.WriteLine("Apply Database Migrations.");
// apply migrations
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<AppDb>();
context.Database.Migrate();
}
}
private void Unhandled_Exceptions(object sender, UnhandledExceptionEventArgs e)
{
// Console.WriteLine("Unhandled Exception:" + (e.ExceptionObject as Exception).Message);
}
}
}