-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
175 lines (144 loc) · 6.63 KB
/
Program.cs
File metadata and controls
175 lines (144 loc) · 6.63 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
using System.Text.Json.Serialization;
using Asp.Versioning;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Scalar.AspNetCore;
using WarehouseEngine.Api.Configuration;
using WarehouseEngine.Api.Examples;
using WarehouseEngine.Api.Middleware.Auth;
using WarehouseEngine.Application.Implementations;
using WarehouseEngine.Application.Interfaces;
using WarehouseEngine.Domain.Models.Auth;
using WarehouseEngine.Infrastructure.DataContext;
namespace WarehouseEngine.Api;
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var env = builder.Environment;
if (env.EnvironmentName != "Integration")
{
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.local.json", optional: true, reloadOnChange: true);
}
var connectionString = builder.Configuration.GetConnectionString("WarehouseEngine")
?? throw new ArgumentException("Connection string is not in the app settings");
services.AddDbContext<IWarehouseEngineContext, WarehouseEngineContext>(options => options.UseSqlServer(connectionString));
// For Identity
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<WarehouseEngineContext>()
.AddDefaultTokenProviders();
#if DEBUG
services.AddCors(opt => opt.AddPolicy("localhost", policy => policy.WithOrigins("http://localhost:4201", "https://localhost:4201", "http://127.0.0.1:4201", "https://127.0.0.1:4201").AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("bearer")));
#endif
// Add services to the container.
services.Configure<JwtConfiguration>(builder.Configuration.GetSection(nameof(JwtConfiguration)));
services.ConfigureOptions<ConfigureJwtBearerOptions>();
services.AddScoped<IJwtService, JwtService>();
services.AddScoped<IItemService, ItemService>();
services.AddScoped<ICustomerService, CustomerService>();
services.AddScoped<IVendorService, VendorService>();
services.AddTransient<IIdGenerator, SequentialIdGenerator>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer();
services.AddTransient<IClaimsTransformation, WarehouseClaimsTransformation>();
// Registers IApiVersionDescriptionProvider for swagger gen and swagger ui
services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
})
.AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
// Using ..Configure<JsonOptions> rather than .AddJsonOptions() according to docs
//https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/include-metadata?view=aspnetcore-10.0&tabs=minimal-apis#mvc-json-options-and-global-json-options
services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.SerializerOptions.MaxDepth = 128;
});
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
services.AddOpenApi(options =>
{
options.AddOperationTransformer((operation, context, cancellationToken) =>
{
if (operation.Tags.Select(t => t.Name).Contains("Authenticate"))
{
var authenticate200Response = operation.Responses.FirstOrDefault(x => x.Key == "200").Value;
authenticate200Response?.Headers.Add("Bearer", new OpenApiHeader() { Description = "Contains JWT" });
}
return Task.CompletedTask;
});
options.AddSchemaTransformer((schema, context, cancellationToken) =>
{
var type = context.JsonTypeInfo.Type;
if (ExampleDictionary.Examples.TryGetValue(type, out var exampleValue))
{
schema.Example = exampleValue;
}
return Task.CompletedTask;
});
});
services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
if (app.Environment.IsDevelopment())
{
// Uses the exception handling strategy detailed here:
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-8.0#produce-a-problemdetails-payload-for-exceptions
app.UseDeveloperExceptionPage();
}
if (env.EnvironmentName != "Integration")
{
await SeedData(app.Services);
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment() || app.Environment.EnvironmentName == "Integration")
{
// configure openapi here
app.MapOpenApi();
app.MapScalarApiReference();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
#if DEBUG
app.UseCors("localhost");
#endif
await app.RunAsync();
}
public static async Task SeedData(IServiceProvider services)
{
#if DEBUG
using var scope = services.CreateScope();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
var demoUser = new IdentityUser
{
Email = "demo@carlosmartos.com",
UserName = "demo"
};
IdentityUser? demoUserId = await userManager.FindByNameAsync(demoUser.UserName);
if (demoUserId is not null) return;
IdentityResult result = await userManager.CreateAsync(demoUser, "P@ssword1");
if (!result.Succeeded) throw new ArgumentException(result.ToString());
#endif
}
}