-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
184 lines (154 loc) · 5.37 KB
/
Program.cs
File metadata and controls
184 lines (154 loc) · 5.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using TodoApi.Helpers;
using TodoApi.Models.db;
using TodoApi.Services;
var env1 = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Console.WriteLine($"env1: {env1}");
var env = env1 ?? "Production";
Console.WriteLine($"sbmtLog: Current ENV var is:{env}------------------");
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env}.json")
.Build();
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://*:5000");
// Add services to the container.
//https://gavilan.blog/2021/05/19/fixing-the-error-a-possible-object-cycle-was-detected-in-different-versions-of-asp-net-core/
builder
.Services.AddControllers()
.AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
string? dbServer = Environment.GetEnvironmentVariable("DB_SERVER");
string? dbPort = Environment.GetEnvironmentVariable("DB_PORT");
string? dbPass = Environment.GetEnvironmentVariable("DB_PASS");
string? dbUser = Environment.GetEnvironmentVariable("DB_USER");
string? dbName = Environment.GetEnvironmentVariable("DB_NAME");
string dbSsl = configuration["DbConfig:sslMode"];
// use scripts/load_env.sh to setup ENV before migration
if (string.IsNullOrEmpty(dbServer))
{
throw new Exception("Invalid ENV value for: dbServer");
}
if (string.IsNullOrEmpty(dbPort))
{
throw new Exception("Invalid ENV value for: dbPort");
}
if (string.IsNullOrEmpty(dbPass))
{
throw new Exception("Invalid ENV value for: dbPass");
}
if (string.IsNullOrEmpty(dbUser))
{
throw new Exception("Invalid ENV value for: dbUser");
}
if (string.IsNullOrEmpty(dbName))
{
throw new Exception("Invalid ENV value for: dbName");
}
bool includeError = bool.Parse(configuration["DbConfig:includeError"]);
bool enableSensitiveDataLogging = bool.Parse(configuration["DbConfig:enableSensitiveDataLogging"]);
string connectionString =
$""
+ $"Server={dbServer};"
+ $"Database={dbName};"
+ $"Port={dbPort};"
+ $"User Id={dbUser};"
+ $"Password={dbPass};"
+ $"Ssl Mode={dbSsl};"
+ $"Trust Server Certificate=true;"
+ $"Include Error Detail={includeError};";
string connectionStringSafe =
$""
+ $"Server={dbServer};"
+ $"Database={dbName};"
+ $"Port={dbPort};"
+ $"User Id={dbUser};"
+ $"Password=XXXXXXXXX;"
+ $"Ssl Mode={dbSsl};"
+ $"Trust Server Certificate=true;"
+ $"Include Error Detail={includeError};";
Console.WriteLine($"{connectionStringSafe}");
builder.Services.AddDbContext<sbmtContext>(opt =>
{
opt.UseNpgsql(
connectionString,
psqlOpt => psqlOpt.EnableRetryOnFailure() //this buys 90 seconds of startup without the DB
);
opt.EnableSensitiveDataLogging(enableSensitiveDataLogging);
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IStravaService, StravaService>();
builder.Services.AddSingleton(new StravaLimitService());
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<IAuthorizationHandler, AdminAuthHandler>();
builder
.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
//options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
options.Cookie.Name = configuration["CookieName"];
options.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = (ctx) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 401;
}
return Task.CompletedTask;
},
OnRedirectToAccessDenied = (ctx) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 403;
}
return Task.CompletedTask;
},
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(
"UserIsAdminPolicy",
policy =>
{
//policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
policy.Requirements.Add(new UserIsAdminRequirement());
}
);
});
builder.Services.AddHostedService<TimedHostedService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMiddleware<JwtMiddleware>();
app.UseAuthorization();
app.UseMiddleware<ResponseHeaderMiddleware>();
app.Use(
async (context, next) =>
{
var request = context.Request;
var fullUrl = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
Console.WriteLine($"{fullUrl}");
await next();
}
);
app.MapControllers();
app.MapControllerRoute(name: "default", pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
app.Run();