summaryrefslogtreecommitdiffstats
path: root/src/server/Startup.cs
blob: effe0a750e10ebca5b70a62aa9510123c7abac7b (plain) (blame)
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
namespace IOL.BookmarkThing.Server;

public class Startup
{
	public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment) {
		Configuration = configuration;
		WebHostEnvironment = webHostEnvironment;
	}

	private IWebHostEnvironment WebHostEnvironment { get; }
	private IConfiguration Configuration { get; }

	// This method gets called by the runtime. Use this method to add services to the container.
	public void ConfigureServices(IServiceCollection services) {
		services.AddDataProtection()
				.PersistKeysToFileSystem(new DirectoryInfo(AppPaths.DataProtectionKeys.HostPath));

		StartupTasks.Execute();

		if (WebHostEnvironment.IsDevelopment()) {
			services.AddCors();
		}

		services.Configure(AppJsonSettings.Default);

		services.AddDbContext<AppDbContext>(options => {
			options.UseNpgsql(ConnectionStrings.AppDatabaseConnectionString(Configuration),
							  builder => {
								  builder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
								  builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), default);
							  })
				   .UseSnakeCaseNamingConvention();
			if (WebHostEnvironment.IsDevelopment()) {
				options.EnableSensitiveDataLogging();
			}
		});

		services.AddQuartz(options => {
			options.UsePersistentStore(o => {
				o.UsePostgres(ConnectionStrings.QuartzDatabaseConnectionString(Configuration));
				o.UseSerializer<QuartzJsonSerializer>();
			});
			options.UseMicrosoftDependencyInjectionJobFactory();
			options.RegisterJobs();
		});

		services.AddQuartzHostedService(options => {
			options.WaitForJobsToComplete = true;
		});

		services.AddAuthentication(options => {
					options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
					options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
				})
				.AddCookie(options => {
					options.Cookie.Name = "bookmarkthing_session";
					options.Cookie.SameSite = SameSiteMode.Strict;
					options.Cookie.HttpOnly = true;
					options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
					options.Cookie.IsEssential = true;
					options.SlidingExpiration = true;
					options.Events.OnRedirectToAccessDenied =
							options.Events.OnRedirectToLogin = c => {
								c.Response.StatusCode = StatusCodes.Status401Unauthorized;
								return Task.FromResult<CookieAuthenticationOptions>(default);
							};
				})
				.AddGitHub(options => {
					options.ClientSecret = Configuration.GetValue<string>("GH_CLIENT_SECRET");
					options.ClientId = Configuration.GetValue<string>("GH_CLIENT_ID");
					options.SaveTokens = true;
					options.CorrelationCookie = new CookieBuilder {
							Name = "gh_correlation",
							SameSite = SameSiteMode.Lax,
							SecurePolicy = CookieSecurePolicy.Always,
							HttpOnly = true,
					};
					options.Events.OnCreatingTicket = context => HandleGithubCreatingTicket.Handle(context, Configuration);
				})
				.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>(Constants.BASIC_AUTH_SCHEME, default);

		services.AddLogging();
		services.AddHttpClient();
		services.AddControllers()
				.AddJsonOptions(AppJsonSettings.Default);

		services.AddApiVersioning(options => {
			options.ApiVersionReader = new UrlSegmentApiVersionReader();
			options.ReportApiVersions = true;
			options.AssumeDefaultVersionWhenUnspecified = false;
		});
		services.AddVersionedApiExplorer(options => {
			options.SubstituteApiVersionInUrl = true;
		});
		services.AddSwaggerGen(options => {
			options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".xml"));
			options.UseApiEndpoints();
			options.OperationFilter<SwaggerDefaultValues>();
			options.SwaggerDoc(ApiSpecV1.Document.VersionName, ApiSpecV1.Document.OpenApiInfo);
			options.AddSecurityDefinition("Basic",
										  new OpenApiSecurityScheme {
												  Name = "Authorization",
												  Type = SecuritySchemeType.ApiKey,
												  Scheme = "Basic",
												  BearerFormat = "Basic",
												  In = ParameterLocation.Header,
												  Description =
														  "Enter your token in the text input below.\r\n\r\nExample: \"Basic 12345abcdef\"",
										  });

			options.AddSecurityRequirement(new OpenApiSecurityRequirement {
					{
							new OpenApiSecurityScheme {
									Reference = new OpenApiReference {
											Type = ReferenceType.SecurityScheme,
											Id = "Basic"
									}
							},
							Array.Empty<string>()
					}
			});
		});
	}

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app) {
		if (WebHostEnvironment.IsDevelopment()) {
			app.UseDeveloperExceptionPage();
			app.UseCors(x => x
							 .AllowAnyMethod()
							 .AllowAnyHeader()
							 .WithOrigins("http://localhost:3000")
							 .WithOrigins("https://bmt.ivarlovlie.no")
							 .AllowCredentials());
		}

		app.UseRouting();
		app.UseSerilogRequestLogging();
		app.UseStatusCodePages();
		app.UseAuthentication();
		app.UseAuthorization();
		app.UseEndpoints(endpoints => {
			endpoints.MapControllers();
		});
		app.UseSwagger();
		app.UseSwaggerUI(options => {
			options.SwaggerEndpoint(ApiSpecV1.Document.SwaggerPath, ApiSpecV1.Document.VersionName);
			options.DocumentTitle = Constants.API_NAME;
		});
	}
}