Projekt

Obecné

Profil

Stáhnout (3.44 KB) Statistiky
| Větev: | Tag: | Revize:
1
using System.Text.Json.Serialization;
2
using Core.Authentication;
3
using Core.Contexts;
4
using Core.Seeding;
5
using Core.Services;
6
using Microsoft.AspNetCore.Authentication.JwtBearer;
7
using Microsoft.EntityFrameworkCore;
8
using Microsoft.OpenApi.Models;
9
using RestAPI.Middleware;
10
using RestAPI.Utils;
11
using Serilog;
12
using Core.MapperProfiles;
13

    
14
var builder = WebApplication.CreateBuilder(args);
15

    
16
// Logging
17
builder.Host.UseSerilog((ctx, lc) => lc.WriteTo.Console());
18

    
19

    
20
builder.Services.AddControllers()
21
    .AddJsonOptions(options =>
22
        options.JsonSerializerOptions.Converters.Add(
23
            new JsonStringEnumConverter())); // In OpenAPI (Swagger) the enum item names will be generated (instead of numbers)
24

    
25
// Register our services
26
Registration.RegisterServices(builder);
27

    
28
// Swagger
29
builder.Services.AddEndpointsApiExplorer();
30
builder.Services.AddSwaggerGen(c =>
31
{
32
    c.SwaggerDoc("v1",
33
        new OpenApiInfo {Title = "AnnotationTool", Description = "KIV/ASWI ZČU Plzeň, 2022", Version = "0.1.1"});
34
});
35

    
36

    
37
builder.Services.AddCors();
38

    
39
// JWT authentication
40
var tokenValidationParams = JwtUtils.GetTokenValidationParameters(builder.Configuration);
41
builder.Services.AddSingleton(tokenValidationParams);
42
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JwtConfig"));
43
builder.Services.AddAuthentication(options =>
44
    {
45
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
46
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
47
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
48
    })
49
    .AddJwtBearer(jwt =>
50
        {
51
            jwt.SaveToken = true;
52
            jwt.TokenValidationParameters = tokenValidationParams;
53
        }
54
    );
55

    
56
builder.Services.AddHttpContextAccessor();
57
builder.Services.AddScoped<ClientInfo>(provider =>
58
    ContextUtils.GetClientInfo(provider.GetRequiredService<IHttpContextAccessor>().HttpContext));
59

    
60

    
61
// Database
62
builder.Services.AddDbContext<DatabaseContext>();
63

    
64
// AutoMapper
65
RegisterMappings.Register(builder);
66

    
67

    
68
var app = builder.Build();
69

    
70
app.UsePathBase(builder.Configuration["BasePath"]);
71

    
72
// Enable DateTime in PostgreSQL
73
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
74

    
75

    
76
// Configure the HTTP request pipeline.
77
if (app.Environment.IsDevelopment())
78
{
79
    app.UseSwagger();
80
    app.UseSwaggerUI();
81
}
82

    
83
// CORS
84
app.UseCors(builder => builder
85
    .AllowAnyHeader()
86
    .AllowAnyMethod()
87
    .SetIsOriginAllowed(_ => true)
88
    .AllowCredentials()
89
);
90

    
91
app.UseRouting();
92

    
93
// JWT Authentication
94
app.UseMiddleware<JwtMiddleware>();
95

    
96
// Error handling middleware
97
app.UseMiddleware<ErrorMiddleware>();
98

    
99
app.MapGet("/", () => "It works!");
100

    
101
app.MapControllers();
102

    
103
// Logging
104
app.UseSerilogRequestLogging();
105
app.Logger.LogInformation("Starting up");
106

    
107

    
108
// Database seeding
109
using (var scope = app.Services.CreateScope())
110
{
111
    var context = scope.ServiceProvider.GetService<DatabaseContext>();
112
    if (context == null)
113
    {
114
        app.Logger.LogCritical("Could not initialize database context, shutting down.");
115
        Environment.Exit(101);
116
    }
117

    
118

    
119
    // In development we seed dummy data
120
    if (app.Environment.IsDevelopment())
121
    {
122
        //context.Database.EnsureDeleted();
123
        //context.Database.EnsureCreated();
124
        context.Database.Migrate();
125
        Seeder.SeedDevelopment(context);
126
    }
127
    else
128
    {
129
        // In production we seed administrator 
130
        context.Database.Migrate();
131
        Seeder.SeedProduction(context);
132
    }
133
}
134

    
135
app.Run();
(3-3/6)