Files
2026-06-18 21:39:20 +10:00

244 lines
6.8 KiB
C#

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CarParkValidationAPI.Authorization;
using CarParkValidationAPI.Datas;
using CarParkValidationAPI.Interface;
using CarParkValidationAPI.Models;
using CarParkValidationAPI.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
// Define cross-origin sharing policy name
var myAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
#region Services
var services = builder.Services;
services.AddCors();
/*
services.AddCors(options =>
{
options.AddPolicy(name: myAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:3000") // 👈 Your React app location
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials(); // 👈 MANDATORY: Permits cookie exchange
});
});
*/
services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
var appSettingsSection = builder.Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddHttpContextAccessor();
//services.AddScoped<ImportPersonRepository>();
services.AddDbContext<DataContext>(options =>
{
// options.LogTo(s => Console.WriteLine(s));
//options.UseNpgsql(appSettings.SQLConnectionString);
string? conn = builder.Configuration.GetValue<string>("AppSettings:SQLConnectionString");
// options.UseSqlServer(conn);
if (!string.IsNullOrEmpty(conn))
options.UseNpgsql(conn);
// options.LogTo(s => Console.WriteLine(s));
// if (conn != null)
// options.UseNpgsql(conn);
});
/*
services.AddGraphQLServer()
.AddFiltering()
.AddSorting()
.AddProjections()
// .RegisterDbContextFactory<FamilyTreeDBContext>()
//.AddQueryType<QueryFamilyTree>();
*/
services.AddHttpContextAccessor();
services.AddScoped<IJwtUtils, JwtUtils>();
services.AddScoped<IConcessionType, ConcessionTypeRepository>();
services.AddScoped<IValidationPoint, ValidationPointRepository>();
services.AddScoped<IAdminUser, AdminUserRepository>();
services.AddScoped<IUserService, UserServiceFakeRepository>();
services.AddScoped<IConcessionValidation, ConcessionValidationRepository>();
services.AddScoped<ILookupCode, LookupCodeRepository>();
services.AddScoped(typeof(ConcessionValidationReportRepository));
services.AddScoped<Seed>();
/*
// services.AddScoped<IUserService, UserRepository>();
/*
public FamilyTreeDBContext(DbContextOptions<FamilyTreeDBContext> options)
: base(options)
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
}
services.AddScoped<IAdminUser, AdminUserRepository>();
services.AddScoped<IMotorVehicles, MotorVehiclesRepository>();
*/
#endregion
#region app
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
try
{
var context = scope.ServiceProvider.GetRequiredService<DataContext>();
var db = context.Database;
if (db != null)
{
/*
try
{
using var cts = new CancellationTokenSource();
CancellationToken cancellationToken = cts.Token;
await db.MigrateAsync(cancellationToken);
db.EnsureCreated();
}
catch
{
//continue
}
*/
var staff = scope.ServiceProvider.GetService<Seed>();
int id = staff.InsertOneUser();
if (id < 0)
{
var databaseCreator = (context.GetService<IDatabaseCreator>() as RelationalDatabaseCreator);
if (databaseCreator != null)
{
try
{
if (!databaseCreator.Exists())
databaseCreator.Create();
databaseCreator.CreateTables();
}
catch
{
//continue
}
}
id = staff.InsertOneUser();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
app.UseMiddleware<JwtMiddleware>();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())//
//{
app.UseSwagger();
app.UseSwaggerUI();
//}
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Content-Disposition")
.AllowCredentials()); // 👈 MANDATORY: Permits cookie exchange
//app.UseCors(myAllowSpecificOrigins);
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
#endregion
/*
https://www.youtube.com/watch?v=WQFx2m5Ub9M
https://csharptotypescript.azurewebsites.net/
\ services.AddDbContext<BloggingContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("BloggingContext")));
dotnet ef dbcontext scaffold "host=postgresdb;port=5432;Database=carparkvalidationdb;Username=postgres;password=Positive~1" Npgsql.EntityFrameworkCore.PostgreSQL -Schemas schema1 --output-dir Models
PM> Scaffold-DbContext "Host=postgresdb;Port=5432;database=carparkvalidationdb;user id=postgres;Password=Positive~1" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models
*/
/*
graphql
https://www.youtube.com/watch?v=HnXA8RI7Tvc
query {
persons {
nodes{
id
firstName
sex
email
}
}
}
*/