Files
game-ideas/src/GameIdeas/Server/GameIdeas.WebAPI/Program.cs
Egamorf ebb831d741
All checks were successful
Game Ideas deploy / build-test-deploy (push) Successful in 1m28s
Fix startup programs for deployment (#29)
Co-authored-by: Maxime Adler <madler@sqli.com>
Reviewed-on: #29
2025-04-28 14:47:56 +02:00

164 lines
4.7 KiB
C#

using GameIdeas.Resources;
using GameIdeas.Shared.Model;
using GameIdeas.WebAPI.Context;
using GameIdeas.WebAPI.Services.Categories;
using GameIdeas.WebAPI.Services.Games;
using GameIdeas.WebAPI.Services.Users;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
#if DEBUG
LoadEnvironmentVariable("../../../../.env");
#else
LoadEnvironmentVariable("../.env");
#endif
Action<DbContextOptionsBuilder> dbContextOptions = options =>
{
options.UseNpgsql(
GetConnectionString(),
npgOption =>
{
npgOption.CommandTimeout(60);
npgOption.MigrationsAssembly("GameIdeas.WebAPI");
});
};
// Add services to the container.
services.AddDbContext<GameIdeasContext>(dbContextOptions);
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<GameIdeasContext>()
.AddDefaultTokenProviders();
var jwtKey = Environment.GetEnvironmentVariable("JWT_KEY")
?? throw new ArgumentNullException(message: "Invalid key for JWT token", null);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Environment.GetEnvironmentVariable("JWT_ISSUER"),
ValidAudience = Environment.GetEnvironmentVariable("JWT_AUDIENCE"),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
services.Configure<IdentityOptions>(options =>
{
// Default Password settings.
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
});
services.AddAuthorization();
services.AddSingleton<TranslationService>();
services.AddSingleton<Translations>();
services.AddScoped<IUserReadService, UserReadService>();
services.AddScoped<IUserWriteService, UserWriteService>();
services.AddScoped<IGameReadService, GameReadService>();
services.AddScoped<IGameWriteService, GameWriteService>();
services.AddScoped<ICategoryService, CategoryService>();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
services.AddOpenApi();
services.AddCors(option => option.AddDefaultPolicy(policy =>
policy.AllowAnyOrigin()
.AllowAnyHeader()
.WithMethods("GET", "POST", "PUT", "DELETE")));
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<GameIdeasContext>();
await db.Database.MigrateAsync();
}
await LoadTranslations();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
async Task LoadTranslations()
{
var filesDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Files");
var translationFiles = Directory.GetFiles(filesDirectory, "*.json");
var dictionary = new Dictionary<string, string>();
foreach (var file in translationFiles)
{
var name = file.Split('.');
var culture = name[^2];
var content = await File.ReadAllTextAsync(file);
dictionary.Add(culture, content);
}
app.Services.GetRequiredService<TranslationService>().Initialize(dictionary);
ResourcesKey.Initialize(app.Services.GetRequiredService<Translations>());
}
string GetConnectionString()
{
var host = Environment.GetEnvironmentVariable("DB_HOST");
var login = Environment.GetEnvironmentVariable("DB_USERNAME");
var pass = Environment.GetEnvironmentVariable("DB_PASSWORD");
var database = Environment.GetEnvironmentVariable("DB_DATABASE");
return $"Host={host};Username={login};Password={pass};Database={database}";
}
static void LoadEnvironmentVariable(string filePath)
{
if (!File.Exists(filePath))
return;
foreach (var line in File.ReadAllLines(filePath))
{
var parts = line.Split(
'=',
StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
continue;
Environment.SetEnvironmentVariable(parts[0], parts[1]);
}
}