-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
243 lines (208 loc) · 8.47 KB
/
Program.cs
File metadata and controls
243 lines (208 loc) · 8.47 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
using System.Net;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using fim_queueing_admin;
using fim_queueing_admin.Auth;
using fim_queueing_admin.Data;
using fim_queueing_admin.Hubs;
using fim_queueing_admin.Services;
using Firebase.Database;
using FirebaseAdmin;
using FirebaseAdmin.Auth;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Diagnostics.Common;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using SlackNet;
using softaware.Authentication.Hmac;
using softaware.Authentication.Hmac.AspNetCore;
using softaware.Authentication.Hmac.AuthorizationProvider;
using TwitchLib.Api;
using Action = fim_queueing_admin.Auth.Action;
var builder = WebApplication.CreateBuilder(args);
var accountCred = await GoogleCredential.GetApplicationDefaultAsync();
var credential = accountCred.CreateScoped(
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.database");
async Task<string> GetAccessToken()
{
return await (credential as ITokenAccess).GetAccessTokenForRequestAsync();
}
FirebaseApp.Create(new AppOptions
{
ProjectId = builder.Configuration["Firebase:ProjectId"] ?? "fim-queueing",
Credential = credential
});
builder.Services.AddSingleton(_ => new FirebaseClient(builder.Configuration["Firebase:BaseUrl"],
new FirebaseOptions
{
AuthTokenAsyncFactory = GetAccessToken,
AsAccessToken = true
}));
builder.Services.AddDbContext<FimDbContext>(opt =>
{
var connectionString = builder.Configuration.GetConnectionString("Default");
opt.UseNpgsql(connectionString).UseSnakeCaseNamingConvention();
});
builder.Services.AddSingleton<FirebaseAuth>(_ => FirebaseAuth.DefaultInstance);
builder.Services.AddControllersWithViews();
builder.Services.AddMemoryCache();
builder.Services.AddTransient<IHmacAuthorizationProvider>(_ =>
new MemoryHmacAuthenticationProvider((builder.Configuration
.GetRequiredSection("Service2Service:Apps")
.Get<HmacAuthenticationClientConfiguration[]>() ?? [])
.ToDictionary(e => e.AppId, e => e.ApiKey)));
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opt =>
{
opt.LoginPath = "/Home/Login";
opt.SlidingExpiration = true;
opt.ExpireTimeSpan = TimeSpan.FromDays(31);
opt.AccessDeniedPath = "/Home/AccessDenied";
})
.AddScheme<AuthTokenAuthSchemeOptions, AuthTokenAuthSchemeHandler>(AuthTokenScheme.AuthenticationScheme, _ => { })
.AddHmacAuthentication(HmacAuthenticationDefaults.AuthenticationScheme, "Service2Service", opt =>
{
opt.MaxRequestAgeInSeconds = 15;
opt.TrustProxy = bool.TryParse(builder.Configuration["EnableForwardedHeaders"], out var b) && b;
});
builder.Services.AddAuthorization(opt =>
{
opt.DefaultPolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build();
opt.AddPolicy(AuthTokenScheme.AuthenticationScheme,
new AuthorizationPolicyBuilder(AuthTokenScheme.AuthenticationScheme).RequireClaim(ClaimTypes.CartId).Build());
opt.AddPolicy(HmacAuthenticationDefaults.AuthenticationScheme,
new AuthorizationPolicyBuilder(HmacAuthenticationDefaults.AuthenticationScheme).RequireAuthenticatedUser()
.Build());
foreach (var action in typeof(Action).GetFields().Select(f => (string)f.GetValue(null)!))
{
opt.AddPolicy($"Action:{action}",
new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme)
.AddRequirements(new UserAccessRequirement(action)).Build());
}
});
builder.Services.AddSingleton<IAuthorizationHandler, UserAccessHandler>();
builder.Services.AddSingleton<DisplayHubManager>();
builder.Services.AddScoped<FimRepository>();
builder.Services.AddSignalR().AddJsonProtocol(opt =>
{
opt.PayloadSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter() }
};
});
builder.Services.AddCors(opt => opt.AddDefaultPolicy(pol =>
{
pol.AllowAnyHeader();
pol.AllowAnyMethod();
pol.AllowCredentials();
pol.SetIsOriginAllowed(_ => true);
}));
var services = Assembly.GetExecutingAssembly().GetTypes()
.Where(mytype => mytype.GetInterfaces().Contains(typeof(IService)));
foreach (var service in services) builder.Services.AddScoped(service);
if (string.IsNullOrWhiteSpace(builder.Configuration["FRCAPIToken"]))
throw new ApplicationException("FRC API Token is required to start up");
builder.Services.AddHttpClient("FRC", client =>
{
client.BaseAddress = new Uri("https://frc-api.firstinspires.org/v3.0/");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(builder.Configuration["FRCAPIToken"]!)));
});
if (string.IsNullOrWhiteSpace(builder.Configuration["TBAAPIToken"]))
throw new ApplicationException("TBA API Token is required to start up");
builder.Services.AddHttpClient("TBA", client =>
{
client.BaseAddress = new Uri("https://www.thebluealliance.com/api/v3/");
client.DefaultRequestHeaders.Add("X-TBA-Auth-Key", builder.Configuration["TBAAPIToken"]);
});
if (!string.IsNullOrEmpty(builder.Configuration["Twitch:ClientId"]) &&
!string.IsNullOrEmpty(builder.Configuration["Twitch:ClientSecret"]))
{
builder.Services.AddSingleton(_ => new TwitchAPI
{
Settings =
{
ClientId = builder.Configuration["Twitch:ClientId"],
Secret = builder.Configuration["Twitch:ClientSecret"]
}
});
}
if (!string.IsNullOrEmpty(builder.Configuration["Slack:Token"]))
{
builder.Services.AddSingleton(_ =>
new SlackServiceBuilder().UseApiToken(builder.Configuration["Slack:Token"]).GetApiClient());
}
// Some stuff will hardly ever change, so just fetch it once at startup.
// If I cared more this might be an expiring cache
builder.Services.AddSingleton<GlobalState>(provider =>
{
var season = provider.GetRequiredService<FirebaseClient>().Child("/current_season")
.OnceSingleAsync<string>();
season.Wait();
using var versionStream = Assembly.GetEntryAssembly()?
.GetManifestResourceStream("fim_queueing_admin.Assets.Version.txt");
if (versionStream == null) throw new NullReferenceException("Version info was null");
using var version = new StreamReader(versionStream);
return new GlobalState(season.Result, version.ReadToEnd());
});
if (!string.IsNullOrEmpty(builder.Configuration["Logging:GoogleProjectId"]))
{
builder.Logging.AddGoogle(new LoggingServiceOptions()
{
ProjectId = builder.Configuration["Logging:GoogleProjectId"],
ServiceName = "fim-queueing-admin"
});
}
var isBehindProxy = bool.TryParse(builder.Configuration["EnableForwardedHeaders"], out var res) && res;
if (isBehindProxy)
{
var proxyIpAddress = builder.Configuration["ProxyIPAddress"];
if (proxyIpAddress is null)
throw new ApplicationException("Forwarded headers were enabled but no proxy IP was defined");
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownProxies.Add(IPAddress.Parse(proxyIpAddress));
});
}
// builder.Services.AddHostedService<DatabaseKeepAliveService>();
builder.Services.AddCors(opt =>
{
opt.AddPolicy("assistant", pol =>
{
pol.SetIsOriginAllowed(_ => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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();
}
app.UseCors();
if (bool.TryParse(app.Configuration["EnableForwardedHeaders"], out var proxy) && proxy)
app.UseForwardedHeaders();
else
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors();
app.MapHub<DisplayHub>("/DisplayHub");
app.MapHub<AssistantHub>("/AssistantHub").RequireCors("assistant");
app.MapControllerRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
app.Run();