artify / src /Program.cs
mfoud444's picture
first commit
a949060
using System.Text;
using System.Text.Json.Serialization;
using Backend_Teamwork.src.Database;
using Backend_Teamwork.src.Entities;
using Backend_Teamwork.src.Middleware;
using Backend_Teamwork.src.Repository;
using Backend_Teamwork.src.Services.artwork;
using Backend_Teamwork.src.Services.booking;
using Backend_Teamwork.src.Services.category;
using Backend_Teamwork.src.Services.order;
using Backend_Teamwork.src.Services.user;
using Backend_Teamwork.src.Services.workshop;
using Backend_Teamwork.src.Utils;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Npgsql;
using static Backend_Teamwork.src.Entities.User;
var builder = WebApplication.CreateBuilder(args);
// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));
// Database configuration
var dataSourceBuilder = new NpgsqlDataSourceBuilder(
builder.Configuration.GetConnectionString("DefaultConnection")
);
dataSourceBuilder.MapEnum<UserRole>();
dataSourceBuilder.MapEnum<Status>();
// Configure DbContext with warning suppression
builder.Services.AddDbContext<DatabaseContext>(options =>
options.UseNpgsql(dataSourceBuilder.Build())
.ConfigureWarnings(w =>
{
w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.CoreEventId.ManyServiceProvidersCreatedWarning);
}));
// Add AutoMapper
builder.Services.AddAutoMapper(typeof(MapperProfile).Assembly);
// Register services and repositories
builder.Services.AddScoped<ICategoryService, CategoryService>();
builder.Services.AddScoped<CategoryRepository>();
builder.Services.AddScoped<IArtworkService, ArtworkService>();
builder.Services.AddScoped<ArtworkRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<UserRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<OrderRepository>();
builder.Services.AddScoped<IWorkshopService, WorkshopService>();
builder.Services.AddScoped<WorkshopRepository>();
builder.Services.AddScoped<IBookingService, BookingService>();
builder.Services.AddScoped<BookingRepository>();
// Configure Authentication
builder.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 = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])
),
};
});
// Configure Authorization
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
options.AddPolicy("CustomerOnly", policy => policy.RequireRole("Customer"));
});
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
policyBuilder => policyBuilder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
// Configure Controllers
builder.Services.AddControllers()
.AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Build the application
var app = builder.Build();
// Configure timestamp format
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
// Optional: Database connection test and migration (uncomment if needed)
// using (var scope = app.Services.CreateScope())
// {
// var dbContext = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
// try
// {
// if (dbContext.Database.CanConnect())
// {
// Console.WriteLine("Database is connected");
// dbContext.Database.Migrate();
// }
// else
// {
// Console.WriteLine("Unable to connect to the database.");
// }
// }
// catch (Exception ex)
// {
// Console.WriteLine($"Database connection failed: {ex.Message}");
// }
// }
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowAll");
app.UseMiddleware<ErrorHandlerMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapGet("/", () => "Server is running");
app.Run();