This repository has been archived on 2023-02-13. You can view files and clone it, but cannot push or open issues or pull requests.
gswi-server/gswi/Startup.cs

187 lines
6.9 KiB
C#
Raw Normal View History

2022-02-20 19:04:11 +01:00
using System.Text;
using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using NLog.Extensions.Logging;
using NLog;
using gswi.Configuration;
using gswi.CredentialManager;
using gswi.Data;
using gswi.Data.Repositories;
using gswi.Filters;
using gswi.Interface.Repositories;
using gswi.Interface.Services;
using gswi.Service;
using gswi.SMTP.Interface;
using gswi.SMTP.Service;
using gswi.SignalR;
using Microsoft.AspNetCore.HttpOverrides;
namespace gswi
{
public class Startup
{
public IConfiguration Configuration { get; }
private static Logger _logger = LogManager.GetCurrentClassLogger();
public Startup(IHostEnvironment env)
{
try
{
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.IsNullOrEmpty(environmentName))
environmentName = "production";
var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile($"appsettings.{System.Net.Dns.GetHostName()}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
catch (Exception e)
{
_logger.Error(e);
}
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddConfiguration(Configuration.GetSection("Logging"));
builder.AddNLog();
builder.AddConsole();
});
var frontend = GetTypedSettingsFromSection<FrontendSettings>("Frontend");
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder.WithOrigins(frontend.URL)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
var dbSettings = GetTypedSettingsFromSection<DatabaseSettings>("Database");
var authSettings = GetTypedSettingsFromSection<AuthentificationSettings>("Authentification");
var emailSettings = GetTypedSettingsFromSection<EMailSettings>("EMail");
var apiSettings = GetTypedSettingsFromSection<APISettings>("API");
emailSettings.Credentials = Base64.Decode(emailSettings.Credentials);
services.AddSingleton(dbSettings);
services.AddSingleton(authSettings);
services.AddSingleton(emailSettings);
services.AddSingleton(apiSettings);
services.AddSingleton(GetTypedSettingsFromSection<FrontendSettings>("Frontend"));
services.AddDbContextPool<DatabaseContext>(opt => opt.UseMySql(
Base64.DecodeConnectionString(dbSettings.ConnectionString, dbSettings.Credentials),
new MySqlServerVersion(new Version(10, 3, 32))
));
services.AddTransient<IAuthService, AuthServiceImpl>();
services.AddTransient<ISMTPClient, SMTPClientImpl>();
services.AddScoped<IUnitOfWork>((s) => s.GetRequiredService<DatabaseContext>());
services.AddScoped<IAuthUserRepository>((s) => new AuthUserRepositoryImpl((DatabaseContext)s.GetService<IUnitOfWork>()));
services.AddSignalR();
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opt =>
{
opt.RequireHttpsMetadata = false;
opt.SaveToken = true;
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = authSettings.Issuer,
ValidAudience = authSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authSettings.SecretKey))
};
});
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// options.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
});
services.AddControllers(options =>
{
options.Filters.Add(typeof(CustomExceptionFilterAttribute));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder gswi, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
gswi.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
if (env.IsDevelopment())
{
gswi.UseDeveloperExceptionPage();
}
NLog.LogManager.LoadConfiguration($"nlog-{env.EnvironmentName}.config");
gswi.UseCors("CorsPolicy");
var apiSettings = GetTypedSettingsFromSection<APISettings>("API");
if (apiSettings.RedirectToHTTPS)
{
gswi.UseHttpsRedirection();
}
gswi.UseRouting();
gswi.UseAuthentication();
gswi.UseAuthorization();
gswi.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<NotifyHub>("/notify");
});
}
protected SettingType GetTypedSettingsFromSection<SettingType>(string sectionName) where SettingType : new()
{
try
{
var settings = new SettingType();
Configuration.GetSection(sectionName).Bind(settings);
return settings;
}
catch (Exception e)
{
_logger.Error(e);
return new SettingType();
}
}
}
}