Skip to content

Commit

Permalink
explicitly added secrets.json to configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
acatchpole committed Aug 12, 2024
1 parent be02345 commit 2c545e0
Showing 1 changed file with 72 additions and 71 deletions.
143 changes: 72 additions & 71 deletions app/Server/src/SERVERAPI/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
using Agri.CalculateService;
using Agri.Data;
using Agri.Models.Settings;
using AutoMapper;
using AutoMapper;
using FluentValidation.AspNetCore;
using MediatR;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Serialization;
using SERVERAPI.Controllers;
using SERVERAPI.Filters;
using SERVERAPI.Models.Impl;
using SERVERAPI.Models.Impl;
using SERVERAPI.Utility;
using System;
using System.Globalization;
using System.IO;

using System.IO;

namespace SERVERAPI
{
/// <summary>
Expand All @@ -46,6 +46,7 @@ public Startup(IWebHostEnvironment env)

if (env.IsDevelopment())
{
builder.AddJsonFile("secrets.json", optional: true, reloadOnChange: true);
builder.AddUserSecrets<Startup>();
}

Expand All @@ -60,7 +61,7 @@ public void ConfigureServices(IServiceCollection services)
//Creates the DbContext as a scoped Service
services.AddDbContext<AgriConfigurationContext>(options =>
{
options.UseNpgsql(agriConnectionString, b =>
options.UseNpgsql(agriConnectionString, b =>
b.MigrationsAssembly("Agri.Data"));
}, ServiceLifetime.Scoped, ServiceLifetime.Scoped);

Expand All @@ -85,61 +86,61 @@ public void ConfigureServices(IServiceCollection services)
options.Cookie.HttpOnly = true;
options.Cookie.Name = ".NMP.Session";
options.IdleTimeout = TimeSpan.FromHours(4);
});

//Re-enable When a stable redis cache solution has been determined
//Add distributed cache service backed by Redis cache
//services.AddDistributedRedisCache(options =>
//{
// options.Configuration = GetRedisConnectionString();
});

//Re-enable When a stable redis cache solution has been determined
//Add distributed cache service backed by Redis cache
//services.AddDistributedRedisCache(options =>
//{
// options.Configuration = GetRedisConnectionString();
//});

//Automapper
services.AddAutoMapper(typeof(Startup));
//Mediatr
services.AddMediatR(typeof(Startup));

// Add framework services.
services.AddMediatR(typeof(Startup));

// Add framework services.
services.AddControllersWithViews()
.AddNewtonsoftJson(
opts =>
{
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
opts.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
// ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model.
opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
opts.SerializerSettings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeNonAscii;
});

services.AddRazorPages()
});

services.AddRazorPages()
.AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining<Startup>(); })
.AddNewtonsoftJson(
opts =>
{
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
opts.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
// ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model.
opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
opts.SerializerSettings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeNonAscii;
});

var keyRingPath = Configuration.GetValue("KEY_RING_DIRECTORY", string.Empty);
var dpBuilder = services.AddDataProtection();

if (!string.IsNullOrEmpty(keyRingPath))
{
Console.Write($"Setting data protection keys to persist in {keyRingPath}");
dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath));
}
else
{
Console.Write("data protection key folder is not set, check if KEY_RING_DIRECTORY env var is missing");
}

});

var keyRingPath = Configuration.GetValue("KEY_RING_DIRECTORY", string.Empty);
var dpBuilder = services.AddDataProtection();

if (!string.IsNullOrEmpty(keyRingPath))
{
Console.Write($"Setting data protection keys to persist in {keyRingPath}");
dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath));
}
else
{
Console.Write("data protection key folder is not set, check if KEY_RING_DIRECTORY env var is missing");
}

services.AddScoped<UserData>();
services.AddTransient<BrowserData>();
services.AddScoped<IAgriConfigurationRepository, AgriConfigurationRepository>();
Expand Down Expand Up @@ -172,28 +173,28 @@ public void Configure(IApplicationBuilder app)
cultureInfo.NumberFormat.CurrencySymbol = "$";

CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

if (_hostingEnv.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

if (_hostingEnv.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error/Error");
}
app.UseMiddleware(typeof(ErrorHandlingMiddleware));

}
app.UseMiddleware(typeof(ErrorHandlingMiddleware));

app.UseSession();
app.UseResponseCompression();
app.UseDefaultFiles();
app.UseStaticFiles();

app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

UpdateDatabase(app);
Expand Down Expand Up @@ -234,26 +235,26 @@ private string GetConnectionString()
}
}

private string GetRedisConnectionString()
{
private string GetRedisConnectionString()
{
if (_hostingEnv.IsDevelopment())
{
return Configuration["Redis:ConnectionString"];
}
else
{
var redisConnection = Environment.GetEnvironmentVariable("REDIS_CONNECTION_STRING");
}
else
{
var redisConnection = Environment.GetEnvironmentVariable("REDIS_CONNECTION_STRING");
if (string.IsNullOrEmpty(redisConnection))
{
{
throw new Exception(@"Redis Connection String ""REDIS_CONNECTION_STRING"" variable not found");
}
var redisPassword = Environment.GetEnvironmentVariable("REDIS_PASSWORD");

}
var redisPassword = Environment.GetEnvironmentVariable("REDIS_PASSWORD");

if (!string.IsNullOrEmpty(redisPassword))
{
redisConnection = $"{redisConnection},password={redisPassword}";
}
return redisConnection;
{
redisConnection = $"{redisConnection},password={redisPassword}";
}
return redisConnection;
}
}

Expand All @@ -269,7 +270,7 @@ private void UpdateDatabase(IApplicationBuilder app)

if ((!string.IsNullOrEmpty(refreshDatabase) && refreshDatabase.ToLower() == "true") ||
(options.Value.RefreshDatabase && _hostingEnv.IsDevelopment()))
{
{
context.Database.EnsureDeleted();
}

Expand All @@ -293,4 +294,4 @@ private static void RunSeeding(IApplicationBuilder app)
} //Scope will be closed once seeding is completed
}
}
}
}

0 comments on commit 2c545e0

Please sign in to comment.