Program.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. using Common.Global;
  2. using Database.Database;
  3. using Esim.Apis.Business;
  4. using log4net;
  5. using log4net.Config;
  6. using Microsoft.AspNetCore.Authentication.JwtBearer;
  7. using Microsoft.EntityFrameworkCore;
  8. using Microsoft.IdentityModel.Tokens;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. var builder = WebApplication.CreateBuilder(args);
  12. // Initialize log4net
  13. XmlConfigurator.Configure(
  14. new FileInfo(Path.Combine(builder.Environment.ContentRootPath, "log4net.config"))
  15. );
  16. // Set global configuration for use by singletons like ConfigManager
  17. GlobalConfig.Configuration = builder.Configuration;
  18. // Add services to the container.
  19. builder
  20. .Services.AddControllersWithViews()
  21. .AddJsonOptions(options =>
  22. {
  23. // Use camelCase for JSON property names (categoryId instead of CategoryId)
  24. options.JsonSerializerOptions.PropertyNamingPolicy = System
  25. .Text
  26. .Json
  27. .JsonNamingPolicy
  28. .CamelCase;
  29. });
  30. // Add DbContext with Oracle provider
  31. var connectionString = builder.Configuration.GetSection("Connection").Value;
  32. builder.Services.AddDbContext<ModelContext>(options => options.UseOracle(connectionString));
  33. // Add Business Services
  34. builder.Services.AddScoped<IUserBusiness, UserBusinessImpl>();
  35. builder.Services.AddScoped<IArticleBusiness, ArticleBusinessImpl>();
  36. builder.Services.AddScoped<IContentBusiness, ContentBusinessImpl>();
  37. // Configure CORS - Allow frontend to access APIs
  38. builder.Services.AddCors(options =>
  39. {
  40. options.AddPolicy(
  41. "AllowFrontend",
  42. policy =>
  43. {
  44. policy
  45. .WithOrigins(
  46. "http://localhost:3000", // React development
  47. "http://localhost:5173", // Vite development
  48. "http://localhost:4200", // Angular development
  49. "http://simgetgo.vn", // Production domain
  50. "http://simgetgo.com", // Production www domain
  51. "https://skysimhub.vn", // Production www domain
  52. "https://skysimhub.com", // Production www domain
  53. "https://simgetgo.vn", // Production www domain
  54. "https://simgetgo.com" // Production www domain
  55. )
  56. .AllowAnyMethod()
  57. .AllowAnyHeader()
  58. .AllowCredentials();
  59. }
  60. );
  61. });
  62. // Configure JWT Authentication
  63. var jwtKey =
  64. builder.Configuration["Jwt:Key"]
  65. ?? "EsimLaoSecretKey1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCD";
  66. var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "EsimLao";
  67. var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "EsimLaoClient";
  68. builder
  69. .Services.AddAuthentication(options =>
  70. {
  71. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  72. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  73. })
  74. .AddJwtBearer(options =>
  75. {
  76. options.TokenValidationParameters = new TokenValidationParameters
  77. {
  78. ValidateIssuer = true,
  79. ValidateAudience = true,
  80. ValidateLifetime = true,
  81. ValidateIssuerSigningKey = true,
  82. ValidIssuer = jwtIssuer,
  83. ValidAudience = jwtAudience,
  84. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtKey))
  85. };
  86. });
  87. // Add Swagger for API documentation
  88. builder.Services.AddEndpointsApiExplorer();
  89. builder.Services.AddSwaggerGen();
  90. var app = builder.Build();
  91. // Initialize ConfigManager to load configs from database
  92. using (var scope = app.Services.CreateScope())
  93. {
  94. var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
  95. try
  96. {
  97. logger.LogInformation("Initializing ConfigManager...");
  98. Esim.Apis.Singleton.ConfigManager.Instance.Initialize();
  99. logger.LogInformation("ConfigManager initialized successfully");
  100. byte[] keyBytes = Encoding.UTF8.GetBytes("9kw1wLMLG2u1j2zX");
  101. var encrypt = DotnetLib.Secure.SecureLogic.EncryptAes("{\"username\": \"10014331\",\"fullName\": \"User6066871357\",\"phoneNumber\": \"8560010014331\",\"email\": \"abc@gmail.com\",}", "9kw1wLMLG2u1j2zX");
  102. logger.LogInformation($"encrypt: {encrypt}");
  103. var decrypt = DotnetLib.Secure.SecureLogic.DecryptAes(encrypt, "9kw1wLMLG2u1j2zX");
  104. logger.LogInformation($"decrypt: {decrypt}");
  105. // Start background refresh task
  106. Task.Run(() => Esim.Apis.Singleton.ConfigManager.Instance.RefreshConfigs());
  107. }
  108. catch (Exception ex)
  109. {
  110. logger.LogError(ex, "Failed to initialize ConfigManager");
  111. }
  112. }
  113. app.UseSwagger();
  114. app.UseSwaggerUI();
  115. // Configure the HTTP request pipeline.
  116. //if (app.Environment.IsDevelopment())
  117. //{
  118. // app.UseSwagger();
  119. // app.UseSwaggerUI();
  120. //}
  121. //else
  122. //{
  123. // app.UseExceptionHandler("/Home/Error");
  124. // // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  125. // app.UseHsts();
  126. //}
  127. // Only redirect to HTTPS in production
  128. if (!app.Environment.IsDevelopment())
  129. {
  130. app.UseHttpsRedirection();
  131. }
  132. app.UseRouting();
  133. // Enable CORS - MUST be after UseRouting and before UseAuthentication
  134. app.UseCors("AllowFrontend");
  135. app.UseAuthentication();
  136. app.UseAuthorization();
  137. //app.MapStaticAssets();
  138. app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
  139. //.WithStaticAssets();
  140. app.MapControllers();
  141. app.Run();