using Microsoft.EntityFrameworkCore; using RhSolutions.Models; using RhSolutions.Api.Services; using RhSolutions.Api.Middleware; using RhSolutions.Parsers; using Microsoft.OpenApi.Models; using System.Reflection; using Microsoft.AspNetCore.Identity; using System.Text; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Authentication.JwtBearer; using System.Security.Claims; var builder = WebApplication.CreateBuilder(args); ConnectionStringsUtil connectionStringsUtil = new(builder.Configuration); builder.Services.AddDbContext(opts => { opts.UseNpgsql(connectionStringsUtil.GetRhDbString()); if (builder.Environment.IsDevelopment()) { opts.EnableSensitiveDataLogging(true); } }); builder.Services.AddDbContext(opts => { opts.UseNpgsql(connectionStringsUtil.GetIdentityDbString()); }); builder.Services.AddIdentity() .AddEntityFrameworkStores(); builder.Services.AddScoped() .AddScoped(); builder.Services.AddModifiers(); builder.Services.AddControllers(); builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "RhSolutions API", Description = "API к базе данных артикулов РЕХАУ для поиска с помощью ML.NET и полнотестового поиска PostgreSQL", Contact = new OpenApiContact { Name = "Serghei Cebotari", Url = new Uri("https://cebotari.ru/"), Email = @"serghei@cebotari.ru" } }); var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); }); builder.Services.AddAuthentication() .AddJwtBearer(opts => { opts.RequireHttpsMetadata = false; opts.SaveToken = true; opts.TokenValidationParameters = new() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes(builder.Configuration["JWT_SECRET"] ?? "mold-smartness-arrive-overstate-aspirin")), ValidateAudience = false, ValidateIssuer = false }; opts.Events = new JwtBearerEvents() { OnTokenValidated = async context => { var userManager = context.HttpContext.RequestServices .GetRequiredService>(); var signInManager = context.HttpContext.RequestServices .GetRequiredService>(); string username = context.Principal!.FindFirst(ClaimTypes.Name)!.Value; IdentityUser? idUser = await userManager.FindByNameAsync(username); context.Principal = await signInManager.CreateUserPrincipalAsync(idUser!); } }; }); var app = builder.Build(); app.MapControllers(); app.UseMiddleware(); app.UseSwagger().UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); options.RoutePrefix = string.Empty; }); app.UseAuthentication(); app.UseAuthorization(); IdentitySeedData.CreateAdminAccount(app.Services, app.Configuration); app.Run();