feat: reporting apis; better rate limiting

refactor: change certain apis to be more REST like (e.g. DELETE /api/paste/{pasteId}/delete -> DELETE /api/paste/{pasteId}
This commit is contained in:
2026-01-10 00:06:36 -05:00
parent 864a4ee91a
commit 14bbd9c762
15 changed files with 954 additions and 48 deletions
@@ -29,7 +29,7 @@ namespace SharpbinV3.Server.Controllers
private readonly AppDbContext _db = db;
[HttpPost]
[EnableRateLimiting("Sliding")]
[EnableRateLimiting("Strict")]
[Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterUserDto request)
{
@@ -75,7 +75,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPost]
[Route("login")]
[EnableRateLimiting("Sliding")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> Login([FromBody] LoginUserDto request)
{
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
@@ -169,6 +169,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPost]
[Authorize]
[Route("totp/enable")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
+144 -31
View File
@@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
@@ -12,17 +14,20 @@ namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService,
ReportService reportService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
{
private readonly PasteService _pasteService = pasteService;
private readonly VerificationService _verificationService = verificationService;
private readonly AuthService _authService = authService;
private readonly ReportService _reportService = reportService;
private readonly PasteSettings _pasteSettings = options.Value;
private readonly AuthSettings _authSettings = authSettings.Value;
[HttpPost]
[Route("create")]
[Authorize(Policy = "NotBanned")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null)
{
if (!await _pasteService.ValidateExpiresAt(expiresAt))
@@ -59,33 +64,38 @@ namespace SharpbinV3.Server.Controllers
paste.ExpiresAt
});
}
[HttpGet]
[Route("{id}")]
public async Task<IActionResult> GetPasteByID(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
if (paste == null)
return NotFound(new { success = false, message = "Paste not found"});
return Ok(new
{
paste.ID,
paste.UUID,
paste.Title,
paste.Size,
paste.TrueSize,
paste.IsCompressed,
paste.Views,
paste.Syntax,
paste.Visibility,
paste.ExpiresAt,
paste.EditedAt,
Author = paste.User != null && paste.User.Visibility == 0 ? new
{
paste.User.UID,
paste.User.UUID,
paste.User.Username,
paste.User.DisplayName,
paste.User.Visibility
} : null
success = true,
paste = new {
paste.ID,
paste.UUID,
paste.Title,
paste.Size,
paste.TrueSize,
paste.IsCompressed,
paste.Views,
paste.Syntax,
paste.Visibility,
paste.ExpiresAt,
paste.EditedAt,
Author = paste.User != null && paste.User.Visibility == 0 ? new
{
paste.User.UID,
paste.User.UUID,
paste.User.Username,
paste.User.DisplayName,
paste.User.Visibility
} : null
}
});
}
[HttpGet]
@@ -95,18 +105,13 @@ namespace SharpbinV3.Server.Controllers
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
if (paste.IsCompressed)
{
Response.Headers.Append("Content-Encoding", "gzip");
return File(paste.Content, "application/octet-stream");
}
else
{
return File(paste.Content, "text/plain; charset=utf-8");
}
return File(paste.Content, "text/plain; charset=utf-8");
}
[HttpPut]
[Route("{id}/edit")]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> EditPaste(string id)
{
@@ -134,7 +139,7 @@ namespace SharpbinV3.Server.Controllers
}
[HttpPatch]
[Route("{id}/modify")]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
{
@@ -190,8 +195,9 @@ namespace SharpbinV3.Server.Controllers
}
});
}
[HttpDelete]
[Route("{id}/delete")]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> DeletePaste(string id)
{
@@ -221,6 +227,7 @@ namespace SharpbinV3.Server.Controllers
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
if (_pasteSettings.View_HMAC_Secret == null)
return StatusCode(500, new { success = false, message = "View recording is not configured properly." });
if (!string.IsNullOrWhiteSpace(_pasteSettings.View_Internal_API_Key)
@@ -237,6 +244,112 @@ namespace SharpbinV3.Server.Controllers
return Ok(new { success = true, message = "Paste view recorded." });
}
[HttpPost]
[Route("{id}/report")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext
{
Token = request.VerificationToken,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { success = false, message = "Verification failed." });
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
return Ok(new { success = true, message = "Paste reported successfully.", report = new
{
id = report.ReportID,
reportType,
description = report.Description
}
});
}
[HttpPatch]
[Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
report.Type = reportType;
report.Description = request.Description;
var updatedReport = await _reportService.UpdateReport(report);
if (updatedReport == null)
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete]
[Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _reportService.DeleteReport(report);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
return Ok(new { success = true, message = "Report deleted successfully." });
}
[HttpGet]
[Route("recent")]
public async Task<IActionResult> GetRecentPastes()
+103 -1
View File
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
@@ -16,12 +17,14 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, VerificationService verificationService, IOptions<AuthSettings> authSettings) : ControllerBase
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp,
VerificationService verificationService, ReportService reportServer, IOptions<AuthSettings> authSettings) : ControllerBase
{
private readonly UserService _userService = userService;
private readonly AppDbContext _db = db;
private readonly TotpVerificationProvider _totp = totp;
private readonly VerificationService _verificationService = verificationService;
private readonly ReportService _reportService = reportServer;
private readonly AuthSettings _authSettings = authSettings.Value;
[HttpGet("{username}")]
@@ -52,6 +55,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch("uuid/{uuid}")]
[Authorize]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
{
if (!ModelState.IsValid)
@@ -99,6 +103,7 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete("uuid/{uuid}")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
{
var jwtUser = HttpContext.GetJwtUser();
@@ -142,6 +147,103 @@ namespace SharpbinV3.Server.Controllers
return Ok(new { message = "User deleted successfully." });
}
[HttpPost]
[Route("{uuid}/report")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
{
var reporter = HttpContext.GetJwtUser();
if (reporter == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var reportedUser = await _userService.GetByUUID(uuid);
if (reportedUser == null)
return NotFound(new { success = false, message = "User not found." });
if (reportedUser.UUID == reporter.UUID)
return BadRequest(new { success = false, message = "You cannot report yourself." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext
{
Token = request.VerificationToken,
Ip = HttpContext.GetRequestIP()
}))
return Unauthorized(new { success = false, message = "Invalid verification token." });
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
return Ok(new
{
success = true,
message = "Paste reported successfully.",
report = new
{
id = report.ReportID,
reportType,
description = report.Description
}
});
}
[HttpPatch]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
return NotFound(new { success = false, message = "Report not found." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
report.Type = reportType;
report.Description = request.Description ?? report.Description;
await _db.SaveChangesAsync();
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
return NotFound(new { success = false, message = "Report not found." });
var result = await _reportService.DeleteReport(report);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
return Ok(new { success = true, message = "Report deleted successfully." });
}
private async Task<object> BuildUserResponse(User user, int page = 1)
{
var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString();
+15
View File
@@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
{
public class ReportDto
{
[Required]
[MaxLength(1000)]
public string Description { get; set; } = string.Empty;
[Required]
public string ReportType { get; set; } = string.Empty; // e.g., "Spam", "Abuse", etc.
public string ReportStatus { get; set; } = "Open";
public string? VerificationToken { get; set; }
}
}
+13 -1
View File
@@ -10,6 +10,7 @@ namespace SharpbinV3.Server.Data
public DbSet<PasteView> PasteViews => Set<PasteView>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
public DbSet<Report> Reports => Set<Report>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -38,7 +39,18 @@ namespace SharpbinV3.Server.Data
.WithOne(u => u.Totp)
.HasForeignKey<UserTotp>(t => t.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
}
modelBuilder.Entity<Report>()
.HasOne(r => r.Paste)
.WithMany(p => p.Reports)
.HasForeignKey(r => r.PastePID)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Report>()
.HasOne(r => r.User)
.WithMany(u => u.Reports)
.HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
}
}
}
+1
View File
@@ -34,5 +34,6 @@ namespace SharpbinV3.Server.Data.Entities
public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never
public List<PasteView> PasteViews { get; set; } = [];
public List<Report> Reports { get; set; } = [];
}
}
+56
View File
@@ -0,0 +1,56 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(ReportID), IsUnique = true)]
[Index(nameof(ReporterUUID))]
[Index(nameof(TargetType))]
[Index(nameof(PastePID))]
[Index(nameof(UserUUID))]
public class Report
{
public int? ReportID { get; set; }
public ReportType Type { get; set; }
public ReportStatus Status { get; set; } = ReportStatus.Open;
[MaxLength(1000)]
public string? Description { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
public long? UpdatedAt { get; set; }
public Guid ReporterUUID { get; set; }
public ReportTargetType TargetType { get; set; }
public int? PastePID { get; set; }
public Guid? UserUUID { get; set; }
public Paste? Paste { get; set; }
public User? User { get; set; }
}
public enum ReportStatus
{
Open,
InProgress,
Resolved,
Closed
}
public enum ReportType
{
Spam,
Abuse,
InappropriateContent,
CopyrightViolation,
Fraud,
Other
}
public enum ReportTargetType
{
Paste,
User
}
}
+1
View File
@@ -21,6 +21,7 @@ namespace SharpbinV3.Server.Data.Entities
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = [];
public List<Report> Reports { get; set; } = [];
public UserTotp? Totp { get; set; }
}
}
@@ -0,0 +1,331 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260110050306_Reports")]
partial class Reports
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("PID")
.IsUnique();
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<int?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,81 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class Reports : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Reports",
columns: table => new
{
ReportID = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Type = table.Column<int>(type: "INTEGER", nullable: false),
Status = table.Column<int>(type: "INTEGER", nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 1000, nullable: true),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedAt = table.Column<long>(type: "INTEGER", nullable: true),
ReporterUUID = table.Column<Guid>(type: "TEXT", nullable: false),
TargetType = table.Column<int>(type: "INTEGER", nullable: false),
PastePID = table.Column<int>(type: "INTEGER", nullable: true),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Reports", x => x.ReportID);
table.ForeignKey(
name: "FK_Reports_Pastes_PastePID",
column: x => x.PastePID,
principalTable: "Pastes",
principalColumn: "PID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Reports_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Reports_PastePID",
table: "Reports",
column: "PastePID");
migrationBuilder.CreateIndex(
name: "IX_Reports_ReporterUUID",
table: "Reports",
column: "ReporterUUID");
migrationBuilder.CreateIndex(
name: "IX_Reports_ReportID",
table: "Reports",
column: "ReportID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Reports_TargetType",
table: "Reports",
column: "TargetType");
migrationBuilder.CreateIndex(
name: "IX_Reports_UserUUID",
table: "Reports",
column: "UserUUID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Reports");
}
}
}
@@ -135,6 +135,56 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<int?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
@@ -227,6 +277,23 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -241,6 +308,8 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
@@ -249,6 +318,8 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
+55 -6
View File
@@ -7,6 +7,7 @@ using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Authorization;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
@@ -40,6 +41,7 @@ namespace SharpbinV3.Server
builder.Services.AddScoped<VerificationService>();
builder.Services.AddScoped<TotpVerificationProvider>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddScoped<ReportService>();
builder.Services.AddMemoryCache();
builder.Services.AddHealthChecks()
@@ -97,16 +99,63 @@ namespace SharpbinV3.Server
builder.Services.AddRateLimiter(options =>
{
options.AddSlidingWindowLimiter("Sliding", opt =>
options.AddPolicy("Sliding", httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(httpContext.GetRequestIP(), _ => new SlidingWindowRateLimiterOptions
{
Window = TimeSpan.FromSeconds(10),
PermitLimit = 10,
QueueLimit = 2,
SegmentsPerWindow = 5,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
options.AddPolicy("Strict", httpContext =>
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 5,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromSeconds(30),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
options.AddPolicy("Sensitive", httpContext =>
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 3,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromMinutes(1),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
opt.Window = TimeSpan.FromSeconds(10);
opt.PermitLimit = 10;
opt.QueueLimit = 2;
opt.SegmentsPerWindow = 5;
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
var remoteIp = httpContext.GetRequestIP();
return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
});
});
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
await context.HttpContext.Response.WriteAsJsonAsync(new
{
success = false,
Message = "Too many requests. Please try again later."
}, cancellationToken: cancellationToken);
};
});
builder.Services.AddCors(o =>
{
@@ -0,0 +1,71 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public class ReportService(AppDbContext db)
{
private readonly AppDbContext _db = db;
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, Guid userUUID, ReportType type, string description)
{
var report = new Report
{
ReporterUUID = reporterUUID,
TargetType = targetType,
UserUUID = userUUID,
Type = type,
Description = description
};
await _db.Reports.AddAsync(report);
await _db.SaveChangesAsync();
return report;
}
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, int? pastePID, ReportType type, string description)
{
var report = new Report
{
ReporterUUID = reporterUUID,
TargetType = targetType,
PastePID = pastePID,
Type = type,
Description = description,
};
await _db.Reports.AddAsync(report);
await _db.SaveChangesAsync();
return report;
}
public async Task<List<Report>> GetReports(Guid reporterUUID)
{
return await _db.Reports
.Where(r => r.ReporterUUID == reporterUUID)
.ToListAsync();
}
public async Task<List<Report>> GetReports(ReportTargetType targetType, int? pastePID)
{
return await _db.Reports
.Where(r => r.TargetType == targetType && r.PastePID == pastePID)
.ToListAsync();
}
public async Task<Report?> GetReportByID(int reportID)
{
return await _db.Reports
.FirstOrDefaultAsync(r => r.ReportID == reportID);
}
public async Task<Report> UpdateReport(Report report)
{
_db.Reports.Update(report);
await _db.SaveChangesAsync();
return report;
}
public async Task<bool> DeleteReport(Report report)
{
_db.Reports.Remove(report);
var result = await _db.SaveChangesAsync();
return result > 0;
}
}
}