HRM-10/HRM.UI/Startup.cs
2026-11-03 17:03:07 +06:00

460 lines
16 KiB
C#

using Asp.Versioning;
using HRM.BO;
using HRM.BO.Configuration;
using HRM.DA;
using HRM.UI.BackgroundJobs.Calendar;
using HRM.UI.Configuration.DI;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.RateLimiting;
namespace HRM.UI.Api
{
public class Startup
{
public IWebHostEnvironment HostingEnvironment { get; private set; }
private readonly ILogger _logger;
private readonly AppSettings _appSettings;
private readonly JwtSettings _jwt;
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment env, ILogger<Startup> logger)
{
_logger = logger;
HostingEnvironment = env;
Configuration = configuration;
_appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
_jwt = Configuration.GetSection("Jwt").Get<JwtSettings>();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllersWithViews();
//services.AddSpaStaticFiles(configuration =>
//{
// configuration.RootPath = "ClientApp/dist";
//});
_logger.LogTrace("Startup::ConfigureServices");
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
services.Configure<EmployeeApiInfo>(Configuration.GetSection("EmployeeApiInfo"));
services.Configure<AdminPendingJob>(Configuration.GetSection("AdminPendingJob"));
services.Configure<MobileAppSettings>(Configuration.GetSection("MobileAppSettings"));
services.Configure<FundInfo>(Configuration.GetSection("FundInfo"));
// Calendar reminders and notifications (Hangfire)
services.AddCalendarBackgroundJobs(Configuration, HostingEnvironment);
try
{
if (AppSettings.IsValid())
{
#region Dependency injection with services
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
#endregion
_logger.LogDebug("Startup::ConfigureServices::valid AppSettings");
#region App settings
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
#endregion
#region jwt
services.Configure<JwtSettings>(Configuration.GetSection("Jwt"));
#endregion
#region Controllers
services.AddHttpClient<ApiIntegrationService>();
services.AddControllers(
options => { options.Filters.Add(new ProducesAttribute("application/json")); })
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews(options => { options.AllowEmptyInputInBodyModelBinding = true; });
#endregion
#region Add Rate Limit
services.AddRateLimiter(options =>
{
options.AddPolicy("LoginPolicy", context =>
{
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault()
?? context.Connection.RemoteIpAddress?.ToString()
?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter(ip, _ =>
new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
});
});
options.AddPolicy("MfaPolicy", context =>
{
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault()
?? context.Connection.RemoteIpAddress?.ToString()
?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter(ip, _ =>
new FixedWindowRateLimiterOptions
{
PermitLimit = 5, // Max 5 OTP attempts per window
Window = TimeSpan.FromMinutes(1), // 1 minute window
QueueLimit = 0,
AutoReplenishment = true
});
});
options.AddPolicy("ResendOtpPolicy", context =>
{
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault()
?? context.Connection.RemoteIpAddress?.ToString()
?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter(ip, _ =>
new FixedWindowRateLimiterOptions
{
PermitLimit = 2, // max 2 resend per window
Window = TimeSpan.FromMinutes(1), // 1 min window
QueueLimit = 0,
AutoReplenishment = true
});
});
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, token) =>
{
context.HttpContext.Response.ContentType = "application/json";
var path = context.HttpContext.Request.Path.Value?.ToLower() ?? "";
string msg = path.Contains("verify-mfa")
? "Too many OTP attempts. Please try again later."
: path.Contains("resend-otp")
? "You can only resend OTP 2 times per minute. Please wait."
: "Too many login attempts. Please try again after 1 minute.";
await context.HttpContext.Response.WriteAsync(
$"{{\"message\":\"{msg}\"}}",
token
);
};
});
#endregion
#region API versioning
IApiVersioningBuilder apiVersioning = services.AddApiVersioning(
options =>
{
options.ReportApiVersions = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ApiVersionReader = new UrlSegmentApiVersionReader();
})
.AddMvc();
#endregion
#region CORS
services.AddCors(options =>
{
options.DefaultPolicyName = "CORSPolicy";
options.AddDefaultPolicy(
builder =>
{
//builder.WithOrigins("http://localhost:4200")
//.SetIsOriginAllowedToAllowWildcardSubdomains();
//builder.AllowAnyMethod();
//builder.AllowAnyHeader();
//builder.AllowCredentials();
builder.WithOrigins("http://localhost:4200")
.SetIsOriginAllowedToAllowWildcardSubdomains();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
builder.AllowCredentials();
});
});
#endregion
#region Versioned Api Explorer
//Format the version as "'v'major[.minor][-status]"
apiVersioning.AddApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
#endregion
#region Session
services.AddDistributedMemoryCache();
services.AddSession(
options => { options.IdleTimeout = TimeSpan.FromMinutes(60); });
#endregion
#region JWT Authentication
var key = Ease.Core.Utility.JwtSigningKey.FromSecret(_appSettings.Secret);
services.AddAuthentication(
options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var cookieToken = context.Request.Cookies["JWToken"];
if (!string.IsNullOrEmpty(cookieToken))
{
context.Token = cookieToken;
}
return System.Threading.Tasks.Task.CompletedTask;
}
};
});
#endregion
#region Antiforgery
services.AddMvc();
services.AddAntiforgery(options => { options.HeaderName = "Ease.HR.X-XSRF-TOKEN"; });
#endregion
#region Auto Mapper Configurations
//var mappingConfig = new MapperConfiguration(mc =>
//{
// mc.AddProfile(new APIMappingProfile());
//});
//IMapper mapper = mappingConfig.CreateMapper();
//services.AddSingleton(mapper);
#endregion
#region SWAGGER
//if (_appSettings.Swagger.Enabled)
//{
// services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
// services.AddSwaggerGen(options =>
// {
// options.OperationFilter<SwaggerDefaultValues>();
// options.IncludeXmlComments(XmlCommentsFilePath);
// });
//}
#endregion
#region AI Integration (OpenAI)
services.AddSingleton<OpenAIService>(provider =>
{
var config = provider.GetRequiredService<IConfiguration>();
var encryptedkey = config["OpenAI:ApiKey"];
var model = config["OpenAI:Model"];
int maxLimit = 50;
return new OpenAIService(encryptedkey, model, maxLimit);
});
#endregion
#region Business Service
services.ConfigureBusinessServices(Configuration);
#endregion
#region Memory Cashing Configuration
services.AddMemoryCache();
services.AddSingleton<ICacheManager, MemoryCacheService>();
#endregion
_logger.LogDebug("Startup::ConfigureServices::ApiVersioning, Swagger and DI settings");
}
else
{
_logger.LogDebug("Startup::ConfigureServices::invalid AppSettings");
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
#region CORS
app.UseCors("CORSPolicy");
#endregion
app.UseHttpsRedirection();
//app.UseDefaultFiles();
app.UseStaticFiles();
//if (!env.IsDevelopment())
//{
// app.UseSpaStaticFiles();
//}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.UseSession();
app.UseCalendarBackgroundJobs();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
public class AppSettings
{
[Required] public string DefaultDB { get; set; }
public string Secret { get; set; }
public string DownloadFolder { get; set; }
[Required] public ApiSettings API { get; set; }
// [Required]
//public Swagger Swagger { get; set; }
//[Required]
public static bool IsValid()
{
return true;
}
public string RDLCLocation { get; set; }
//public static bool IsValid<T>(this T data)
//{
// if (data == null)
// throw new ArgumentNullException(nameof(data));
// var validationResult = new List<ValidationResult>();
// var result = Validator.TryValidateObject(data, new System.ComponentModel.DataAnnotations.ValidationContext(data), validationResult, false);
// if (!result)
// {
// foreach (var item in validationResult)
// {
// Debug.WriteLine($"ERROR::{item.MemberNames}:{item.ErrorMessage}");
// }
// }
// return result;
//}
}
public class ApiSettings
{
[Required] public string Title { get; set; }
public string Description { get; set; }
public ApiContact Contact { get; set; }
public string TermsOfServiceUrl { get; set; }
public ApiLicense License { get; set; }
}
public class ApiContact
{
public string Name { get; set; }
public string Email { get; set; }
public string Url { get; set; }
}
public class ApiLicense
{
public string Name { get; set; }
public string Url { get; set; }
}
public class JwtSettings
{
private string _secret;
private string _issuer;
private string _audience;
[Required]
public string Secret
{
get => _secret;
set => _secret = !string.IsNullOrEmpty(value) ? Ease.Core.Utility.Global.CipherFunctions.Decrypt("CeLiMiTeD.AdMIn", value) : value;
}
[Required]
public string Issuer
{
get => _issuer;
set => _issuer = !string.IsNullOrEmpty(value) ? Ease.Core.Utility.Global.CipherFunctions.Decrypt("CeLiMiTeD.AdMIn", value) : value;
}
[Required]
public string Audience
{
get => _audience;
set => _audience = !string.IsNullOrEmpty(value) ? Ease.Core.Utility.Global.CipherFunctions.Decrypt("CeLiMiTeD.AdMIn", value) : value;
}
public int TokenLifetimeMinutes { get; set; }
}
}