Files
DiunaBI/src/Backend/DiunaBI.WebAPI/Program.cs

170 lines
5.7 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
2025-06-02 16:54:33 +02:00
using System.Reflection;
using System.Text;
using DiunaBI.Core.Database.Context;
using DiunaBI.Core.Services;
2025-06-02 16:54:33 +02:00
using Google.Apis.Sheets.v4;
2025-06-02 17:20:49 +02:00
using Serilog;
2025-06-07 12:33:33 +02:00
using DiunaBI.Core.Interfaces;
var builder = WebApplication.CreateBuilder(args);
2025-06-07 12:33:33 +02:00
if (builder.Environment.IsProduction())
2025-06-02 17:20:49 +02:00
{
2025-06-07 12:33:33 +02:00
builder.Host.UseSerilog((context, configuration) =>
{
2025-07-04 13:36:59 +02:00
var instanceName = context.Configuration["InstanceName"] ?? "unknown";
2025-06-07 12:33:33 +02:00
configuration
.ReadFrom.Configuration(context.Configuration)
.Enrich.FromLogContext()
2025-07-04 13:15:47 +02:00
.Enrich.WithProperty("Application", $"DiunaBI-{instanceName}")
2025-06-07 12:33:33 +02:00
.Enrich.WithProperty("Version", Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "unknown")
.Enrich.WithEnvironmentName()
.Enrich.WithMachineName();
});
}
2025-06-02 17:20:49 +02:00
var connectionString = builder.Configuration.GetConnectionString("SQLDatabase");
2025-06-08 10:18:52 +02:00
builder.Services.AddDbContext<AppDbContext>(x =>
{
x.UseSqlServer(connectionString);
x.EnableSensitiveDataLogging();
});
builder.Services.AddCors(options =>
{
options.AddPolicy("CORSPolicy", corsPolicyBuilder =>
{
corsPolicyBuilder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
corsPolicyBuilder.WithOrigins("https://diuna.bim-it.pl")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
2025-10-29 17:56:10 +01:00
corsPolicyBuilder.WithOrigins("https://morska.diunabi.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
builder.Services.AddControllers();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Secret"]!))
};
});
2025-06-08 10:18:52 +02:00
// Google Sheets dependencies
2025-06-08 10:56:20 +02:00
Console.WriteLine("Adding Google Sheets dependencies...");
2025-06-02 16:54:33 +02:00
builder.Services.AddSingleton<GoogleSheetsHelper>();
builder.Services.AddSingleton<GoogleDriveHelper>();
builder.Services.AddSingleton<SpreadsheetsResource.ValuesResource>(provider =>
{
var googleSheetsHelper = provider.GetRequiredService<GoogleSheetsHelper>();
var valuesResource = googleSheetsHelper.Service?.Spreadsheets.Values;
2025-06-08 10:18:52 +02:00
2025-06-02 16:54:33 +02:00
if (valuesResource == null)
{
throw new InvalidOperationException("Google Sheets Service is not initialized properly");
}
2025-06-08 10:18:52 +02:00
2025-06-02 16:54:33 +02:00
return valuesResource;
});
builder.Services.AddSingleton<PluginManager>();
var app = builder.Build();
2025-06-07 12:33:33 +02:00
if (app.Environment.IsProduction())
2025-06-02 17:20:49 +02:00
{
2025-06-07 12:33:33 +02:00
app.UseSerilogRequestLogging(options =>
2025-06-02 17:20:49 +02:00
{
2025-06-07 12:33:33 +02:00
options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
2025-06-02 17:20:49 +02:00
{
2025-06-07 12:33:33 +02:00
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
2025-06-08 10:18:52 +02:00
2025-06-07 12:33:33 +02:00
var userAgent = httpContext.Request.Headers.UserAgent.FirstOrDefault();
if (!string.IsNullOrEmpty(userAgent))
{
diagnosticContext.Set("UserAgent", userAgent);
}
2025-06-08 10:18:52 +02:00
2025-06-07 12:33:33 +02:00
diagnosticContext.Set("RemoteIP", httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown");
diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType ?? "none");
};
});
}
2025-06-02 16:54:33 +02:00
2025-06-08 10:18:52 +02:00
// Plugin initialization
2025-06-02 17:20:49 +02:00
var pluginManager = app.Services.GetRequiredService<PluginManager>();
2025-06-02 16:54:33 +02:00
var executablePath = Assembly.GetExecutingAssembly().Location;
var executableDir = Path.GetDirectoryName(executablePath)!;
var pluginsPath = Path.Combine(executableDir, "Plugins");
2025-06-07 12:33:33 +02:00
if (app.Environment.IsProduction())
{
Log.Information("Starting DiunaBI application");
Log.Information("Loading plugins from: {PluginsPath}", pluginsPath);
}
else
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Starting DiunaBI application (Development)");
logger.LogInformation("Loading plugins from: {PluginsPath}", pluginsPath);
}
2025-06-02 17:20:49 +02:00
2025-06-02 16:54:33 +02:00
pluginManager.LoadPluginsFromDirectory(pluginsPath);
app.Use(async (context, next) =>
{
var token = context.Request.Headers.Authorization.ToString();
if (token.Length > 0
&& !context.Request.Path.ToString().Contains("getForPowerBI")
&& !context.Request.Path.ToString().Contains("getConfiguration")
2025-06-08 11:08:48 +02:00
&& !context.Request.Path.ToString().Contains("DataInbox/Add"))
{
var handler = new JwtSecurityTokenHandler();
var data = handler.ReadJwtToken(token.Split(' ')[1]);
context.Request.Headers.Append("UserId", new Microsoft.Extensions.Primitives.StringValues(data.Subject));
}
await next(context);
});
app.UseCors("CORSPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
2025-06-02 17:20:49 +02:00
2025-06-07 12:33:33 +02:00
if (app.Environment.IsProduction())
{
Log.CloseAndFlush();
2025-06-08 14:21:45 +02:00
}
// for testing purposes
public partial class Program { }