Files
bank-backend/src/IO.Swagger/Startup.cs
2023-08-13 20:36:50 -04:00

196 lines
7.6 KiB
C#

/*
* T&J Central Bank API
*
* API documentation for T&J Central Bank's digital wallets
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.IO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using IO.Swagger.Filters;
using IO.Swagger.Security;
using IO.Swagger.Repositories;
using IO.Swagger.Services;
using Microsoft.EntityFrameworkCore;
namespace IO.Swagger
{
/// <summary>
/// Startup
/// </summary>
public class Startup
{
private readonly IWebHostEnvironment _hostingEnv;
private IConfiguration Configuration { get; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="env"></param>
/// <param name="configuration"></param>
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
_hostingEnv = env;
Configuration = configuration;
}
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services
.AddMvc(options =>
{
options.InputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>();
options.OutputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter>();
})
.AddNewtonsoftJson(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy()));
})
.AddXmlSerializerFormatters();
services.AddAuthentication(BearerAuthenticationHandler.SchemeName)
.AddScheme<AuthenticationSchemeOptions, BearerAuthenticationHandler>(BearerAuthenticationHandler.SchemeName, null);
services
.AddSwaggerGen(c =>
{
c.SwaggerDoc("1.0.0", new OpenApiInfo
{
Version = "1.0.0",
Title = "T&J Central Bank API",
Description = "T&J Central Bank API (ASP.NET 7.0)",
Contact = new OpenApiContact()
{
Name = "Swagger Codegen Contributors",
Url = new Uri("https://github.com/swagger-api/swagger-codegen"),
Email = ""
},
// TermsOfService = new Uri("")
});
c.CustomSchemaIds(type => type.FullName);
c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml");
// Sets the basePath property in the Swagger document generated
c.DocumentFilter<BasePathFilter>("/v1");
// Include DataAnnotation attributes on Controller Action parameters as Swagger validation rules (e.g required, pattern, ..)
// Use [ValidateModelState] on Actions to actually validate it in C# as well!
c.OperationFilter<GeneratePathParamsValidationFilter>();
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="bearerAuth"
}
},
new string[]{}
}
});
});
services.AddCors(opt => {
opt.AddDefaultPolicy(po =>
{
po.AllowAnyHeader()
.WithMethods("GET", "POST")
.SetIsOriginAllowedToAllowWildcardSubdomains();
po.SetIsOriginAllowed((or) => or.Contains("localhost") || or.Contains("shrukanslab"));
});
});
string connectionString = Environment.GetEnvironmentVariable("DATABASE_CONNECTION_STRING");
if (string.IsNullOrEmpty(connectionString))
{
throw new Exception("Database connection string not found in environment variable.");
}
Console.WriteLine(connectionString);
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<ICurrencyRepository, CurrencyRepository>();
services.AddDbContext<BankDbContext>(x => x.UseSqlServer(connectionString: connectionString));
services.AddSingleton<JwtService>();
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
/// <param name="context"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, BankDbContext context)
{
context.Database.Migrate();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
//TODO: Either use the SwaggerGen generated Swagger contract (generated from C# classes)
c.SwaggerEndpoint("/swagger/1.0.0/swagger.json", "T&J Central Bank API");
//TODO: Or alternatively use the original Swagger contract that's included in the static files
// c.SwaggerEndpoint("/swagger-original.json", "T&J Central Bank API Original");
});
//TODO: Use Https Redirection
// app.UseHttpsRedirection();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//TODO: Enable production exception handling (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling)
app.UseExceptionHandler("/Error");
app.UseHsts();
}
}
}
}