Newsbot.Collector/Newsbot.Collector.Api/Program.cs

215 lines
6.6 KiB
C#
Raw Normal View History

using System.Text;
2023-02-14 17:51:22 -08:00
using Hangfire;
using Hangfire.MemoryStorage;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newsbot.Collector.Api;
using Newsbot.Collector.Api.Authentication;
using Newsbot.Collector.Api.Services;
using Newsbot.Collector.Database;
using Newsbot.Collector.Database.Repositories;
using Newsbot.Collector.Domain.Consts;
using Newsbot.Collector.Domain.Entities;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Domain.Models;
using Newsbot.Collector.Domain.Models.Config;
using Newsbot.Collector.Domain.Models.Config.Sources;
using Serilog;
using Serilog.Events;
using ILogger = Serilog.ILogger;
2023-02-14 17:51:22 -08:00
var builder = WebApplication.CreateBuilder(args);
// Define Logger
builder.Host.UseSerilog();
2023-02-14 17:51:22 -08:00
// Build the config
var config = GetConfiguration();
2023-02-14 17:51:22 -08:00
builder.Configuration.AddConfiguration(config);
Log.Logger = GetLogger(config);
Log.Information("Starting up");
// configure Entity Framework
var dbconn = config.GetConnectionString("Database");
builder.Services.AddDbContext<DatabaseContext>(o => o.UseNpgsql(dbconn ?? ""));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>();
builder.Services.AddScoped<IArticlesRepository, ArticlesTable>();
builder.Services.AddScoped<IDiscordQueueRepository, DiscordQueueTable>();
builder.Services.AddScoped<IDiscordWebHooksRepository, DiscordWebhooksTable>();
builder.Services.AddScoped<IIconsRepository, IconsTable>();
builder.Services.AddScoped<ISourcesRepository, SourcesTable>();
builder.Services.AddScoped<IDiscordNotificationRepository, DiscordNotificationTable>();
builder.Services.AddScoped<IUserSourceSubscription, UserSourceSubscriptionTable>();
// Configure Identity
builder.Services.AddScoped<IIdentityService, IdentityService>();
// Configure Hangfire
2023-02-14 17:51:22 -08:00
builder.Services.AddHangfire(f => f.UseMemoryStorage());
builder.Services.AddHangfireServer();
GlobalConfiguration.Configuration.UseSerilogLogProvider();
2023-02-14 17:51:22 -08:00
// Add Health Checks
builder.Services.AddHealthChecks()
.AddNpgSql(config.GetValue<string>(ConfigConnectionStringConst.Database) ?? "");
2023-02-14 17:51:22 -08:00
builder.Services.AddControllers();
2023-02-14 17:51:22 -08:00
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrings"));
builder.Services.Configure<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings));
builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss));
builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube));
//builder.Services.Configure<
// Configure JWT for auth
var jwtSettings = new JwtSettings();
config.Bind(nameof(jwtSettings), jwtSettings);
builder.Services.AddSingleton(jwtSettings);
builder.Services.AddAuthentication(x =>
{
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret ?? "")),
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true
};
});
builder.Services.AddSwaggerGen(cfg =>
{
cfg.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{
Description = "The API key to access the API",
Type = SecuritySchemeType.ApiKey,
Name = "x-api-key",
In = ParameterLocation.Header,
Scheme = "ApiKeyScheme"
});
cfg.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization Header using the bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
cfg.AddSecurityRequirement(new OpenApiSecurityRequirement
{
//{
// new OpenApiSecurityScheme
// {
// Reference = new OpenApiReference
// {
// Type = ReferenceType.SecurityScheme,
// Id = "ApiKey"
// },
// In = ParameterLocation.Header
// },
// new List<string>()
//},
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
});
2023-02-14 17:51:22 -08:00
var app = builder.Build();
// Configure the HTTP request pipeline.
if (config.GetValue<bool>("EnableSwagger"))
{
app.UseSwagger();
app.UseSwaggerUI();
}
2023-02-14 17:51:22 -08:00
app.UseHttpsRedirection();
app.UseHangfireDashboard();
BackgroundJobs.SetupRecurringJobs(config);
2023-02-14 17:51:22 -08:00
//app.UseAuthorization();
app.UseAuthentication();
2023-02-14 17:51:22 -08:00
//app.UseMiddleware<ApiKeyAuthAuthentication>();
app.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
2023-02-14 17:51:22 -08:00
app.MapControllers();
app.Run();
static IConfiguration GetConfiguration()
{
return new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true)
.AddJsonFile("config/appsettings.json", true)
.AddEnvironmentVariables()
.Build();
}
static ILogger GetLogger(IConfiguration configuration)
{
var otel = configuration.GetValue<string>(ConfigConnectionStringConst.OpenTelemetry) ?? "";
2023-04-03 09:32:42 -07:00
if (otel == "")
return Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.MinimumLevel.Information()
.CreateLogger();
return Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.MinimumLevel.Information()
.WriteTo.OpenTelemetry(
otel,
resourceAttributes: new Dictionary<string, object>
{
{ "Application", "newsbot-collector-api"},
{ "service.name", "newsbot-collector-api" }
})
.CreateLogger();
}