summaryrefslogtreecommitdiffstats
path: root/api/WhatApi/Program.cs
blob: 7d9c1b4e97f71643702c5eb3f2c6fac0cc31ff97 (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
global using System.Text.Json;
global using System.Text.Json.Serialization;
global using Microsoft.EntityFrameworkCore;
global using NetTopologySuite.IO.Converters;
global using Microsoft.EntityFrameworkCore.Metadata.Builders;
global using NetTopologySuite.Geometries;
global using Microsoft.AspNetCore.Http.Extensions;
global using Microsoft.AspNetCore.Mvc;
global using NetTopologySuite;
global using WhatApi.Database.Tables;
global using WhatApi.Database;
global using System.Text;
global using WhatApi.Extras;
global using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Npgsql;
using WhatApi;
using WhatApi.Middleware;

var builder = WebApplication.CreateBuilder(args);
var dev = builder.Environment.IsDevelopment();

builder.Services.AddHttpContextAccessor();
builder.Services.AddDbContextPool<AppDatabase>(b => {
    var connectionString = builder.Configuration.GetValue<string>(Constants.Env.MasterDbConnectionString);
    var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
    dataSourceBuilder.EnableDynamicJson();
    if (dev) {
        b.EnableSensitiveDataLogging();
        dataSourceBuilder.EnableParameterLogging();
        dataSourceBuilder.UseNetTopologySuite();
    }
    b.UseNpgsql(dataSourceBuilder.Build(), o => {
        o.EnableRetryOnFailure();
        o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
        o.UseNetTopologySuite();
    });
});

if (dev) builder.Configuration["DISABLE_AUDIT_TRAILS"] = "true";

builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));

var tokenEntropy = builder.Configuration.GetValue<string>(Constants.Env.TokenEntropy);
ArgumentException.ThrowIfNullOrEmpty(tokenEntropy);
var tokenIssuer = builder.Configuration.GetValue<string>(Constants.Env.TokenIssuer);
var tokenAudience = builder.Configuration.GetValue<string>(Constants.Env.TokenAudience);

builder.Services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options => {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = tokenIssuer,
            ValidAudience = tokenAudience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenEntropy)),
            ClockSkew = TimeSpan.Zero
        };
    });
builder.Services.AddAuthorization();
builder.Services.AddControllers()
    .AddJsonOptions(o => {
        o.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        o.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals;
        o.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        o.JsonSerializerOptions.Converters.Add(new GeoJsonConverterFactory());
    });


var app = builder.Build();

if (dev) {
    using var scope = app.Services.CreateScope();
    var db = scope.ServiceProvider.GetRequiredService<AppDatabase>();
    Seed.Full(db, opt => {
        opt.ClearTables = false;
    });
}

app.UseRouting();
app.UseForwardedHeaders();
app.UseCors();
app.MapStaticAssets();
app.UseMiddleware<UserLastSeenMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapGet("/", () => Results.Redirect("/map"));
app.Run();

return 0;