-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
181 lines (158 loc) · 5.62 KB
/
Program.cs
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
using System.Diagnostics;
using System.Text;
using Spacebar.API.Middlewares;
using Spacebar.API.Tasks;
using Spacebar.DbModel;
using Spacebar.ConfigModel;
using Spacebar.Util;
using Spacebar.Util.Rewrites;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting.Systemd;
using Microsoft.IdentityModel.Tokens;
using Sentry;
if (!Directory.Exists("cache_formatted")) Directory.CreateDirectory("cache_formatted");
if (!Directory.Exists("cache")) Directory.CreateDirectory("cache");
/*foreach (var file in Directory.GetFiles("cache").Where(x => x.EndsWith(".js")))
{
//JsFormatter.FormatJsFile(File.OpenRead(file), File.OpenWrite(file.Replace("cache", "cache_formatted")));
}*/
/*var processes = Directory.GetFiles("cache").Where(x => x.EndsWith(".js")).Select(file => JsFormatter.SafeFormat(file, file.Replace("cache", "cache_formatted"))).ToList();
while (processes.Any(x => !x.HasExited))
{
Thread.Sleep(100);
}*/
//Environment.Exit(0);
Tasks.RunStartup();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//builder.Services.AddHttpLogging(o => { o.LoggingFields = HttpLoggingFields.All; });
builder.Services.AddLogging(o =>
{
if (SystemdHelpers.IsSystemdService())
o.AddSystemdConsole();
else if(Debugger.IsAttached)
o.AddConsole();
// else
// o.AddSimpleConsole(o =>
// {
// o.IncludeScopes = true;
// o.SingleLine = true;
// o.TimestampFormat = "HH:mm:ss ";
//
// });
if (Config.Instance.Sentry.Enabled)
o.AddSentry(p =>
{
p.Dsn = Config.Instance.Sentry.Dsn;
p.TracesSampleRate = 1.0;
p.AttachStacktrace = true;
p.MaxQueueItems = int.MaxValue;
p.StackTraceMode = StackTraceMode.Original;
p.Environment = Config.Instance.Sentry.Environment;
p.Release = GenericUtils.GetVersion();
});
});
if (Config.Instance.Sentry.Enabled)
{
Console.WriteLine("Sentry enabled!");
builder.WebHost.UseSentry(o =>
{
o.Dsn = Config.Instance.Sentry.Dsn;
o.TracesSampleRate = 1.0;
o.AttachStacktrace = true;
o.MaxQueueItems = int.MaxValue;
o.StackTraceMode = StackTraceMode.Original;
o.Environment = Config.Instance.Sentry.Environment;
o.Release = GenericUtils.GetVersion();
});
}
builder.Services.AddDbContext<Db>(optionsBuilder =>
{
var cfg = Config.Instance.DbConfig;
optionsBuilder
.UseNpgsql(
$"Host={cfg.Host};Database={cfg.Database};Username={cfg.Username};Password={cfg.Password};Port={cfg.Port};Include Error Detail=true");
//.LogTo(str => Debug.WriteLine(str), LogLevel.Information).EnableSensitiveDataLogging().EnableDetailedErrors()
if (Debugger.IsAttached)
optionsBuilder.LogTo(str => Console.WriteLine(str), LogLevel.Information).EnableSensitiveDataLogging()
.EnableDetailedErrors();
});
builder.Services.AddScoped(typeof(JwtAuthenticationManager));
var tokenKey = Config.Instance.Security.JwtSecret;
var key = Encoding.UTF8.GetBytes(tokenKey);
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
var app = builder.Build();
app.UseOptions();
//
if (true || app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
if(Debugger.IsAttached) app.UseHttpLogging();
app.UseRouting();
app.UseSentryTracing();
app.UseAuthentication();
//app.UseAuthorization();
app.UseRewriter(new RewriteOptions().Add(new ApiVersionRewriteRule()));
app.UseWebSockets();
app.UseMiddleware<RightsMiddleware>();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
app.Use((context, next) =>
{
context.Response.Headers["Content-Type"] += "; charset=utf-8";
context.Response.Headers["Access-Control-Allow-Origin"] = "*";
return next.Invoke();
});
app.UseCors("*");
app.MapControllers();
app.UseDeveloperExceptionPage();
//
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=FrontendController}/{action=Index}/{id?}");
});
Console.WriteLine("[DEBUG] Calling getter on config default rights");
var defaultRights = Config.Instance.Security.Register.DefaultRights;
Console.WriteLine("[DEBUG] Calling setter on config default rights");
Config.Instance.Security.Register.DefaultRights = defaultRights;
Config.Instance.Save(Environment.GetEnvironmentVariable("CONFIG_PATH") ?? "");
Console.WriteLine("Starting web server!");
if (args.Contains("--exit-on-modified"))
{
Console.WriteLine("[WARN] --exit-on-modified enabled, exiting on source file change!");
new FileSystemWatcher()
{
Path = Environment.CurrentDirectory,
Filter = "*.cs",
NotifyFilter = NotifyFilters.LastWrite,
EnableRaisingEvents = true
}.Changed += async (sender, args) =>
{
Console.WriteLine("Source modified. Exiting...");
await app.StopAsync();
Environment.Exit(0);
};
}
app.Run();