Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
607 lines (461 loc) · 19 KB
/
Copy pathProgram.cs
File metadata and controls
607 lines (461 loc) · 19 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
using System.Text.Json;
using Microsoft.Extensions.FileProviders;
using System.Text.RegularExpressions;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.AspNetCore.Rewrite;
using OpenTelemetry.Trace;
using DotNetEnv;
Env.Load(); // Loads .env from root
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("this_is_a_very_secure_jwt_secret_key_1234567890!")
)
};
});
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter 'Bearer {token}'"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
// Setup OpenTelemetry Tracing
builder.Services.AddOpenTelemetry().WithTracing(builder =>
{
builder
// Configure ASP.NET Core Instrumentation
.AddAspNetCoreInstrumentation()
// Configure OpenTelemetry Protocol (OTLP) Exporter
.AddOtlpExporter();
});
builder.Services.AddSingleton<CategoryTagService>();
builder.Services.AddSingleton<PostService>();
builder.Services.AddSingleton<PostQueryService>();
builder.Services.AddSingleton<PostSchedulerService>();
builder.Services.AddSingleton<SubscriberService>();
builder.Services.AddSingleton<UserService>();
builder.Services.AddSingleton<ProfileService>();
builder.Services.AddSingleton<JwtService>();
builder.Services.AddSingleton<LikeCommentService>();
builder.Services.AddSingleton<TagService>();
builder.Services.AddSingleton<CategoryService>();
// builder.Services.AddSingleton<PostFileManager>();
var app = builder.Build();
var luceneService = app.Services.GetRequiredService<PostQueryService>();
luceneService.RebuildLuceneIndex();
//to change the slug
// Rewrite URLs (e.g., "/my-awesome-post") to "/post.html?slug=..."
app.MapGet("/{slug:regex(^[a-z0-9-]+$)}", async (HttpContext context, string slug) =>
{
// Serve post.html with the slug (URL bar stays clean)
context.Request.QueryString = new QueryString($"?slug={slug}");
await context.Response.SendFileAsync("wwwroot/Post.html");
});
app.MapGet("/admin-management", async context =>
{
await context.Response.SendFileAsync("wwwroot/Admin.html");
});
app.MapGet("/edit-profile", async context =>
{
await context.Response.SendFileAsync("wwwroot/EditProfile.html");
});
app.MapGet("/post-management", async context =>
{
await context.Response.SendFileAsync("wwwroot/PostManagement.html");
});
app.UseDefaultFiles(); // Serves index.html by default
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI();
// Ensure file-based storage directories exist before running the API
EnsureDirectoriesExist();
// Function to create necessary directories for file-based storage
static void EnsureDirectoriesExist()
{
string[] directories = {
"content/posts",
"content/users",
"content/categories",
"content/tags",
"content/lucene-index",
"config"
};
foreach (string dir in directories)
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
app.MapGet("/api/tags", () =>
{
var path = "content/tags/tag-name.json";
if (!System.IO.File.Exists(path))
return Results.NotFound("Tag file not found.");
var json = System.IO.File.ReadAllText(path);
return Results.Content(json, "application/json");
});
app.MapGet("/api/categories", () =>
{
var path = "content/categories/category-name.json";
if (!System.IO.File.Exists(path))
return Results.NotFound("Tag file not found.");
var json = System.IO.File.ReadAllText(path);
return Results.Content(json, "application/json");
});
//refactoring
//to fix the problem of enum values in json format
var jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() } // This handles enum conversion
};
//server can serve files inside content/posts/.../assets
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "content")),
RequestPath = "/content"
});
// API Endpoints
// loading the posts for the frontend display
app.MapGet("/api/posts", ([FromServices] PostQueryService queryService, [FromServices] PostSchedulerService schedulerService) =>
{
schedulerService.ActivateScheduledPosts(); // Check & promote scheduled posts
var posts = queryService.GetPublishedPostSummaries(); // Then return published ones
return Results.Json(new { posts });
});
// api to get posts by category
app.MapGet("/api/posts/by-category", ([FromServices] PostQueryService queryService, [FromQuery] string category) =>
{
var posts = queryService.GetPublishedPostsForCategory(category);
return Results.Json(new { posts });
});
//api to get posts by tags
app.MapGet("/api/posts/by-tags", ([FromServices] PostQueryService queryService, [FromQuery] string tags) =>
{
var tagList = tags.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var posts = queryService.GetPublishedPostsForTags(tagList);
return Results.Json(new { posts });
});
//search across post title, descritpion, content for the search content
app.MapGet("/api/posts/search", ([FromServices] PostQueryService queryService, [FromQuery] string query) =>
{
var posts = queryService.SearchPublishedPosts(query);
return Results.Json(new { posts });
});
//Api to get a specific post
app.MapGet("/api/posts/{slug}", ([FromServices] PostQueryService queryService, string slug) =>
{
var post = queryService.GetPostBySlug(slug);
return post != null ? Results.Json(post) : Results.NotFound("Post not found.");
});
// app.MapPost("/api/subscribe", async (HttpRequest request, SubscriberService subscriberService) =>
// {
// var form = await request.ReadFormAsync();
// var email = form["email"].ToString();
// Console.WriteLine($"Email received: '{email}'");
// return await subscriberService.HandleSubscription(email);
// });
//api to unsubscribe
// app.MapGet("/api/unsubscribe", (HttpRequest request, SubscriberService subscriberService) =>
// {
// var email = request.Query["email"].ToString();
// if (string.IsNullOrWhiteSpace(email))
// return Results.BadRequest("Missing email.");
// var success = subscriberService.Remove(email);
// return success ? Results.Ok("Unsubscribed.") : Results.NotFound("Subscriber not found.");
// });
app.MapPost("/api/register", async (HttpRequest request, UserService service) =>
await service.RegisterUser(request));
//add user by admin api
var userGroup = app.MapGroup("/api/users").RequireAuthorization();
userGroup.MapPost("/admin-add", async (HttpRequest request, UserService userService) =>
await userService.RegisterUserAsAdmin(request));
// retrieve the count of each type of users
app.MapGet("/api/users/counts", () =>
{
var service = new UserService();
return Results.Json(service.GetUserRoleCounts());
});
//retrieve users by role
app.MapGet("/api/users/by-role/{role}", (string role) =>
{
var service = new UserService();
var users = service.GetUsersByRole(role);
return Results.Json(users);
});
//change the role of a user by admin
app.MapPost("/api/users/change-role", (HttpRequest request) =>
{
var service = new UserService();
return service.ChangeUserRole(request);
});
//delete user by admin
app.MapPost("/api/users/delete", (HttpRequest request) =>
{
var service = new UserService();
return service.DeleteUser(request);
});
app.MapGet("/api/verify", (HttpRequest request, UserService service) =>
{
var email = request.Query["email"].ToString();
var token = request.Query["token"].ToString();
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(token))
return Results.BadRequest("Missing email or token.");
var success = service.VerifyUserEmail(email, token);
if (!success)
return Results.Redirect("/?token=invalid");
return Results.Redirect("/?verified=true&showLogin=true");
});
//login api
app.MapPost("/api/login", async (HttpRequest request, UserService userService, JwtService jwt) =>
await userService.LoginUser(request, jwt));
//api to get post stats for each user for admin display all for authors display their own posts
app.MapGet("/api/posts/stats", async (HttpContext context, PostService postService) =>
{
var userId = context.User.FindFirst("UserID")?.Value;
var role = context.User.FindFirst(ClaimTypes.Role)?.Value;
var queryAll = context.Request.Query["all"] == "true";
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
var stats = await postService.GetPostStatsAsync(userId, role, queryAll);
return Results.Ok(stats);
});
//api to get post by status and for a specific user
app.MapGet("/api/posts/status", async (HttpContext context, PostService postService) =>
{
var userId = context.User.FindFirst("UserID")?.Value;
var role = context.User.FindFirst(ClaimTypes.Role)?.Value;
var status = context.Request.Query["status"].ToString();
var showAll = context.Request.Query["all"] == "true";
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
var posts = await postService.GetPostsByStatusAsync(status, userId, role, showAll);
return Results.Ok(posts);
});
var postGroup = app.MapGroup("/api/posts").RequireAuthorization();
//api to draft the posts
postGroup.MapPost("/draft", async (HttpContext context, PostService postService) =>
{
var form = await context.Request.ReadFormAsync();
var userId = context.User.FindFirst("UserID")?.Value;
var userName = context.User.FindFirst("name")?.Value;
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(userName))
{
return Results.BadRequest("User credentials are missing. Post cannot be created.");
}
var result = await postService.PublishPostAsync(form, userId, userName, isDraft: true);
return result.success ? Results.Ok(result.message) : Results.BadRequest(result.message);
});
//api to publish post
postGroup.MapPost("/publish", async (HttpContext context, PostService postService) =>
{
Console.WriteLine("Publish post API hit.");
var form = await context.Request.ReadFormAsync();
Console.WriteLine($"Title: {form["title"]}");
var userId = context.User.FindFirst("UserID")?.Value;
var userName = context.User.FindFirst("name")?.Value;
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(userName))
{
return Results.BadRequest("User credentials are missing. Post cannot be created.");
}
var result = await postService.PublishPostAsync(form, userId, userName);
return result.success ? Results.Ok(result.message) : Results.BadRequest(result.message);
});
postGroup.MapPost("/{slug}/like", async (HttpContext context, string slug, LikeCommentService service) =>
{
var userId = context.User.FindFirst(ClaimTypes.Email)?.Value;
if (string.IsNullOrWhiteSpace(userId))
return Results.Unauthorized();
return await service.ToggleLike(slug, userId);
});
postGroup.MapPost("/{slug}/comment", async (HttpContext context, HttpRequest req, string slug, LikeCommentService service) =>
{
var subscriberId = context.User.FindFirst("name")?.Value;
var form = await req.ReadFormAsync();
var content = form["content"].ToString();
if (string.IsNullOrWhiteSpace(subscriberId) || string.IsNullOrWhiteSpace(content))
return Results.BadRequest("Missing comment data.");
return await service.AddComment(slug, subscriberId, content);
});
//api to delete post by authorized users
postGroup.MapPost("/delete", async (HttpRequest request, PostService postService) =>
{
var form = await request.ReadFormAsync();
var slug = form["slug"].ToString().Trim();
if (string.IsNullOrEmpty(slug))
return Results.BadRequest("Missing post slug.");
var result = await postService.DeletePostAsync(slug);
return result.success ? Results.Ok(result.message) : Results.BadRequest(result.message);
});
var tagGroup = app.MapGroup("/api/tags").RequireAuthorization();
// Add Tag
tagGroup.MapPost("/add", async (HttpContext context, TagService tagService) =>
{
var userId = context.User.FindFirst("UserID")?.Value;
if (string.IsNullOrEmpty(userId))
return Results.Unauthorized();
var form = await context.Request.ReadFormAsync();
var name = form["name"].ToString();
if (string.IsNullOrWhiteSpace(name))
return Results.BadRequest("Tag name is required.");
var msg = await tagService.CreateTagAsync(name);
if (msg.Contains("already exists", StringComparison.OrdinalIgnoreCase))
return Results.BadRequest(msg);
return Results.Ok(msg);
});
// Get All Tags
tagGroup.MapGet("/all", async (TagService tagService) =>
{
var tags = await tagService.GetAllTagsAsync();
return Results.Ok(tags);
});
// Update Tag
tagGroup.MapPost("/update", async (HttpContext context, TagService service) =>
{
var form = await context.Request.ReadFormAsync();
var id = form["id"].ToString();
var name = form["name"].ToString();
var result = await service.UpdateTagAsync(id, name);
return Results.Ok(result);
});
// Delete Tag
tagGroup.MapPost("/delete", async (HttpContext context, TagService service) =>
{
var form = await context.Request.ReadFormAsync();
var id = form["id"].ToString();
var result = await service.DeleteTagAsync(id);
return Results.Ok(result);
});
var categoryGroup = app.MapGroup("/api/categories").RequireAuthorization();
// Add Category
categoryGroup.MapPost("/add", async (HttpContext context, CategoryService categoryService) =>
{
var userId = context.User.FindFirst("UserID")?.Value;
if (string.IsNullOrEmpty(userId))
return Results.Unauthorized();
var form = await context.Request.ReadFormAsync();
var name = form["name"].ToString();
var description = form["description"].ToString();
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(description))
return Results.BadRequest("Name and description are required.");
var msg = await categoryService.CreateCategoryAsync(name, description);
if (msg.Contains("already exists", StringComparison.OrdinalIgnoreCase))
return Results.BadRequest(msg);
return Results.Ok(msg);
});
// Get All Categories
categoryGroup.MapGet("/all", async (CategoryService categoryService) =>
{
var categories = await categoryService.GetAllCategoriesAsync();
return Results.Ok(categories);
});
//Update Category
categoryGroup.MapPost("/update", async (HttpContext context, CategoryService service) =>
{
var form = await context.Request.ReadFormAsync();
var id = form["id"].ToString();
var name = form["name"].ToString();
var description = form["description"].ToString();
var result = await service.UpdateCategoryAsync(id, name, description);
return Results.Ok(result);
});
// Delete Category
categoryGroup.MapPost("/delete", async (HttpContext context, CategoryService service) =>
{
var form = await context.Request.ReadFormAsync();
var id = form["id"].ToString();
var result = await service.DeleteCategoryAsync(id);
return Results.Ok(result);
});
userGroup.MapGet("/me", (HttpContext context, UserService userService) =>
{
var email = context.User.FindFirst(ClaimTypes.Email)?.Value;
if (string.IsNullOrWhiteSpace(email))
return Results.Unauthorized();
return userService.GetUserProfileJson(email);
});
userGroup.MapPost("/change-name", async (HttpContext context, ProfileService profileService, JwtService jwt) =>
{
var payload = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(context.Request.Body);
if (payload == null || !payload.TryGetValue("newName", out var newName))
return Results.BadRequest(new { error = "Name is required" });
var email = context.User.FindFirst(ClaimTypes.Email)?.Value;
if (string.IsNullOrWhiteSpace(email))
return Results.Unauthorized();
return profileService.ChangeUserName(email, newName, jwt);
});
userGroup.MapPost("/change-password", async (HttpContext context, ProfileService profileService, JwtService jwt) =>
{
var email = context.User.FindFirst(ClaimTypes.Email)?.Value;
var payload = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(context.Request.Body);
if (payload == null ||
!payload.TryGetValue("currentPassword", out var current) ||
!payload.TryGetValue("newPassword", out var next))
return Results.BadRequest(new { error = "Missing fields." });
return profileService.ChangePassword(email, current, next);
});
userGroup.MapPost("/delete-account", async (HttpContext context, ProfileService profileService, JwtService jwt) =>
{
var email = context.User.FindFirst(ClaimTypes.Email)?.Value;
var payload = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(context.Request.Body);
if (payload == null || !payload.TryGetValue("password", out var password))
return Results.BadRequest(new { error = "Missing password." });
return profileService.DeleteAccount(email, password);
});
userGroup.MapPost("/request-role-change", async (HttpContext context, ProfileService profileService, JwtService jwt) =>
{
var email = context.User.FindFirst(ClaimTypes.Email)?.Value;
var payload = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(context.Request.Body);
if (payload == null ||
!payload.TryGetValue("requestedRole", out var role) ||
!payload.TryGetValue("requestMessage", out var msg))
return Results.BadRequest(new { error = "Missing fields." });
return profileService.SaveRoleRequest(email, role, msg);
});
userGroup.MapPost("/role-request/review", async (HttpRequest request, ProfileService service) =>
{
return await service.ReviewRoleRequest(request);
});
app.Run();