feat: auth, compression, jwt, paste wip, roles, ratelimiting

This commit is contained in:
2025-11-24 21:50:26 -05:00
parent 050f0bc935
commit 6ec1a7fa7b
26 changed files with 611 additions and 473 deletions
+78
View File
@@ -0,0 +1,78 @@
using Microsoft.AspNetCore.Mvc;
using SharpbinV3.Services;
using SharpbinV3.DTOs;
using Bcrypt = BCrypt.Net.BCrypt;
using SharpbinV3.Data.Entities;
using Microsoft.AspNetCore.RateLimiting;
namespace SharpbinV3.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController(IUserService userService, IAuthService authService) : ControllerBase
{
private readonly IAuthService _authService = authService;
private readonly IUserService _userService = userService;
[HttpPost]
[EnableRateLimiting("Sliding")]
[Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest request)
{
var existingUser = await _userService.GetByUsername(request.Username);
if (existingUser != null)
return Conflict(new { message = "Username already exists." });
var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
return Ok(new
{
message = "User registered successfully.",
user = new
{
user.UID,
user.UUID,
user.Username,
user.Email,
user.DisplayName,
user.Roles
}
}
);
}
[HttpPost]
[Route("login")]
[EnableRateLimiting("Sliding")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
return BadRequest(new { message = "Username or email is required." });
User? user = null;
if (!string.IsNullOrEmpty(request.Username))
user = await _userService.GetByUsername(request.Username);
if (user == null && !string.IsNullOrEmpty(request.Email))
user = await _userService.GetByEmail(request.Email);
if (user == null) return BadRequest(new { message = "Invalid username/email or password." });
if (!Bcrypt.Verify(request.Password, user.PasswordHash))
return BadRequest(new { message = "Invalid username/email or password." });
var token = _authService.GenerateJWTToken(user);
return Ok(new { token });
}
[HttpPost]
[Route("refresh")]
[EnableRateLimiting("Sliding")]
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
{
try
{
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken);
return Ok(new { token = jwtResult });
}
catch (Exception ex)
{
return BadRequest(new { message = ex.Message });
}
}
}
}
+6 -19
View File
@@ -1,5 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SharpbinV3.DTOs;
using SharpbinV3.Services; using SharpbinV3.Services;
namespace SharpbinV3.Controllers namespace SharpbinV3.Controllers
@@ -10,21 +10,7 @@ namespace SharpbinV3.Controllers
{ {
private readonly IUserService _userService = userService; private readonly IUserService _userService = userService;
[HttpPost] [HttpGet("{uid}")]
public async Task<IActionResult> Create([FromBody] CreateUserDto dto)
{
if (await _userService.GetByUsername(dto.Username) != null)
return Conflict("Username already exists.");
if (!string.IsNullOrEmpty(dto.Email) && await _userService.GetByEmail(dto.Email) != null)
return Conflict("Email already exists.");
var user = await _userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.DisplayName);
return CreatedAtAction(nameof(GetByUid), new { uid = user.UID }, new { user.UID, user.Username, user.UUID });
}
[HttpGet("{uid:int}")]
public async Task<IActionResult> GetByUid(int uid) public async Task<IActionResult> GetByUid(int uid)
{ {
var user = await _userService.GetByUID(uid); var user = await _userService.GetByUID(uid);
@@ -32,15 +18,16 @@ namespace SharpbinV3.Controllers
return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName }); return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName });
} }
[HttpGet("username/{username:string}")] [HttpGet("username/{username}")]
public async Task<IActionResult> GetByUsername(string username) public async Task<IActionResult> GetByUsername(string username)
{ {
var user = await _userService.GetByUsername(username); var user = await _userService.GetByUsername(username);
if (user == null) return NotFound(); if (user == null) return NotFound();
return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName }); return Ok(new { user.UID, user.Username, user.UUID, user.DisplayName });
} }
[HttpGet("uuid/{uuid:guid}")] [HttpGet("uuid/{uuid}")]
public async Task<IActionResult> GetByUuid(Guid uuid) [Authorize]
public async Task<IActionResult> GetByUUID(Guid uuid)
{ {
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) return NotFound(); if (user == null) return NotFound();
+10
View File
@@ -0,0 +1,10 @@
namespace SharpbinV3.DTOs
{
public class JWTResult
{
public string? Token { get; set; }
public string? RefreshToken { get; set; }
public bool Success { get; set; }
public List<string>? Errors { get; set; }
}
}
+14
View File
@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.DTOs
{
public class LoginRequest
{
[StringLength(50, MinimumLength = 3)]
public string? Username { get; set; }
[EmailAddress]
public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
}
}
+12
View File
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.DTOs
{
public class RefreshTokenRequest
{
[Required]
public required string Token { get; set; }
[Required]
public required string RefreshToken { get; set; }
}
}
@@ -2,7 +2,7 @@ using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.DTOs namespace SharpbinV3.DTOs
{ {
public class CreateUserDto public class RegisterRequest
{ {
[Required] [Required]
[StringLength(50, MinimumLength = 3)] [StringLength(50, MinimumLength = 3)]
+1
View File
@@ -7,5 +7,6 @@ namespace SharpbinV3.Data
{ {
public DbSet<User> Users => Set<User>(); public DbSet<User> Users => Set<User>();
public DbSet<Paste> Pastes => Set<Paste>(); public DbSet<Paste> Pastes => Set<Paste>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
} }
} }
+16
View File
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Data.Entities
{
public sealed class RefreshToken
{
[Key]
public Guid UserUUID { get; set; }
public required string Token { get; set; }
public required string JwtId { get; set; }
public required long CreatedAt { get; set; }
public required long ExpiresAt { get; set; }
public bool Used { get; set; } = false;
public User? User { get; set; }
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ValueGeneration.Internal;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Data.Entities namespace SharpbinV3.Data.Entities
@@ -16,7 +15,7 @@ namespace SharpbinV3.Data.Entities
public string? Email { get; set; } public string? Email { get; set; }
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public long? LastLogin { get; set; } public long? LastLogin { get; set; }
public int Type { get; set; } = 0; // 0 = regular user, 1 = moderator, 255 = admin public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin
public int Visiblity { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private public int Visiblity { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public List<Paste> Pastes { get; set; } = []; public List<Paste> Pastes { get; set; } = [];
} }
@@ -1,122 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
#nullable disable
namespace SharpbinV3.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251124021817_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("AuthorUUID")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("FilePath")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<string>("UUID")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("UserUID");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Property<int>("UID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
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.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("UID");
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -1,143 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Data;
#nullable disable
namespace SharpbinV3.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20251124181150_AddPasteIndexes")]
partial class AddPasteIndexes
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("AuthorUUID")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("FilePath")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<string>("UUID")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.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("UserUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Property<int>("UID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
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.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("UID");
b.HasIndex("UID")
.IsUnique();
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -1,95 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Migrations
{
/// <inheritdoc />
public partial class AddPasteIndexes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Users_UUID",
table: "Users",
column: "UUID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_AuthorUUID",
table: "Pastes",
column: "AuthorUUID");
migrationBuilder.CreateIndex(
name: "IX_Pastes_ExpiresAt",
table: "Pastes",
column: "ExpiresAt");
migrationBuilder.CreateIndex(
name: "IX_Pastes_ID",
table: "Pastes",
column: "ID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_PID",
table: "Pastes",
column: "PID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_UUID",
table: "Pastes",
column: "UUID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_Views",
table: "Pastes",
column: "Views");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_UID",
table: "Users");
migrationBuilder.DropIndex(
name: "IX_Users_UUID",
table: "Users");
migrationBuilder.DropIndex(
name: "IX_Pastes_AuthorUUID",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_ExpiresAt",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_ID",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_PID",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_UUID",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_Views",
table: "Pastes");
}
}
}
@@ -1,60 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Migrations
{
/// <inheritdoc />
public partial class AddVisibility : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Type",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "Visiblity",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "Visiblity",
table: "Pastes",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_Pastes_Visiblity",
table: "Pastes",
column: "Visiblity");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Pastes_Visiblity",
table: "Pastes");
migrationBuilder.DropColumn(
name: "Type",
table: "Users");
migrationBuilder.DropColumn(
name: "Visiblity",
table: "Users");
migrationBuilder.DropColumn(
name: "Visiblity",
table: "Pastes");
}
}
}
@@ -11,8 +11,8 @@ using SharpbinV3.Data;
namespace SharpbinV3.Migrations namespace SharpbinV3.Migrations
{ {
[DbContext(typeof(AppDbContext))] [DbContext(typeof(AppDbContext))]
[Migration("20251124184531_AddVisibility")] [Migration("20251125015039_Init")]
partial class AddVisibility partial class Init
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)
@@ -92,6 +92,39 @@ namespace SharpbinV3.Migrations
b.ToTable("Pastes"); b.ToTable("Pastes");
}); });
modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.ValueGeneratedOnAdd()
.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.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.HasIndex("UserUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{ {
b.Property<int>("UID") b.Property<int>("UID")
@@ -111,8 +144,9 @@ namespace SharpbinV3.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<int>("Type") b.PrimitiveCollection<string>("Roles")
.HasColumnType("INTEGER"); .IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID") b.Property<Guid>("UUID")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -144,6 +178,15 @@ namespace SharpbinV3.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{ {
b.Navigation("Pastes"); b.Navigation("Pastes");
@@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace SharpbinV3.Migrations namespace SharpbinV3.Migrations
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class InitialCreate : Migration public partial class Init : Migration
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
@@ -22,7 +22,9 @@ namespace SharpbinV3.Migrations
PasswordHash = table.Column<string>(type: "TEXT", nullable: false), PasswordHash = table.Column<string>(type: "TEXT", nullable: false),
Email = table.Column<string>(type: "TEXT", nullable: true), Email = table.Column<string>(type: "TEXT", nullable: true),
DisplayName = table.Column<string>(type: "TEXT", nullable: true), DisplayName = table.Column<string>(type: "TEXT", nullable: true),
LastLogin = table.Column<long>(type: "INTEGER", nullable: true) LastLogin = table.Column<long>(type: "INTEGER", nullable: true),
Roles = table.Column<string>(type: "TEXT", nullable: false),
Visiblity = table.Column<int>(type: "INTEGER", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
@@ -46,6 +48,7 @@ namespace SharpbinV3.Migrations
TrueSize = table.Column<int>(type: "INTEGER", nullable: false), TrueSize = table.Column<int>(type: "INTEGER", nullable: false),
Views = table.Column<int>(type: "INTEGER", nullable: false), Views = table.Column<int>(type: "INTEGER", nullable: false),
Syntax = table.Column<string>(type: "TEXT", nullable: true), Syntax = table.Column<string>(type: "TEXT", nullable: true),
Visiblity = table.Column<int>(type: "INTEGER", nullable: false),
ExpiresAt = table.Column<long>(type: "INTEGER", nullable: false) ExpiresAt = table.Column<long>(type: "INTEGER", nullable: false)
}, },
constraints: table => constraints: table =>
@@ -58,10 +61,87 @@ namespace SharpbinV3.Migrations
principalColumn: "UID"); principalColumn: "UID");
}); });
migrationBuilder.CreateTable(
name: "RefreshTokens",
columns: table => new
{
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
Token = table.Column<string>(type: "TEXT", nullable: false),
JwtId = table.Column<string>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
ExpiresAt = table.Column<long>(type: "INTEGER", nullable: false),
Used = table.Column<bool>(type: "INTEGER", nullable: false),
UserUID = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RefreshTokens", x => x.UserUUID);
table.ForeignKey(
name: "FK_RefreshTokens_Users_UserUID",
column: x => x.UserUID,
principalTable: "Users",
principalColumn: "UID");
});
migrationBuilder.CreateIndex(
name: "IX_Pastes_AuthorUUID",
table: "Pastes",
column: "AuthorUUID");
migrationBuilder.CreateIndex(
name: "IX_Pastes_ExpiresAt",
table: "Pastes",
column: "ExpiresAt");
migrationBuilder.CreateIndex(
name: "IX_Pastes_ID",
table: "Pastes",
column: "ID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_PID",
table: "Pastes",
column: "PID",
unique: true);
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_Pastes_UserUID", name: "IX_Pastes_UserUID",
table: "Pastes", table: "Pastes",
column: "UserUID"); column: "UserUID");
migrationBuilder.CreateIndex(
name: "IX_Pastes_UUID",
table: "Pastes",
column: "UUID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_Views",
table: "Pastes",
column: "Views");
migrationBuilder.CreateIndex(
name: "IX_Pastes_Visiblity",
table: "Pastes",
column: "Visiblity");
migrationBuilder.CreateIndex(
name: "IX_RefreshTokens_UserUID",
table: "RefreshTokens",
column: "UserUID");
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Users_UUID",
table: "Users",
column: "UUID",
unique: true);
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -70,6 +150,9 @@ namespace SharpbinV3.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Pastes"); name: "Pastes");
migrationBuilder.DropTable(
name: "RefreshTokens");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Users"); name: "Users");
} }
@@ -89,6 +89,39 @@ namespace SharpbinV3.Migrations
b.ToTable("Pastes"); b.ToTable("Pastes");
}); });
modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.ValueGeneratedOnAdd()
.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.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.HasIndex("UserUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{ {
b.Property<int>("UID") b.Property<int>("UID")
@@ -108,8 +141,9 @@ namespace SharpbinV3.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<int>("Type") b.PrimitiveCollection<string>("Roles")
.HasColumnType("INTEGER"); .IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID") b.Property<Guid>("UUID")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -141,6 +175,15 @@ namespace SharpbinV3.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{ {
b.Navigation("Pastes"); b.Navigation("Pastes");
+46
View File
@@ -1,6 +1,11 @@
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SharpbinV3.Data; using SharpbinV3.Data;
using SharpbinV3.Services; using SharpbinV3.Services;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace SharpbinV3 namespace SharpbinV3
{ {
@@ -19,9 +24,49 @@ namespace SharpbinV3
{ {
opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")); opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
}); });
builder.Services.AddSingleton<ICompressionService, CompressionService>();
builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
var key = Encoding.ASCII.GetBytes(builder.Configuration.GetSection("JwtConfig:Secret").Value ?? string.Empty);
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JwtConfig:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["JwtConfig:Audience"],
RequireExpirationTime = true,
ValidateLifetime = true
};
});
builder.Services.AddRateLimiter(options =>
{
options.AddSlidingWindowLimiter("Sliding", opt =>
{
opt.Window = TimeSpan.FromSeconds(10);
opt.PermitLimit = 10;
opt.QueueLimit = 2;
opt.SegmentsPerWindow = 5;
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
});
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
var app = builder.Build(); var app = builder.Build();
app.UseRateLimiter();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
@@ -31,6 +76,7 @@ namespace SharpbinV3
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
+160
View File
@@ -0,0 +1,160 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Data;
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Services
{
public sealed class AuthService(AppDbContext db, IConfiguration configuration) : IAuthService
{
private readonly AppDbContext _db = db;
private readonly IConfiguration _configuration = configuration;
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
{
var user = new User
{
Username = username,
PasswordHash = Bcrypt.HashPassword(password),
Email = email,
DisplayName = displayName,
UUID = Guid.CreateVersion7()
};
_db.Users.Add(user);
await _db.SaveChangesAsync();
return user;
}
public async Task<JWTResult> GenerateJWTToken(User user)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]!);
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(
[
new Claim("UUID", user.UUID.ToString()),
new Claim("Roles", user.Roles != null ? string.Join(",", user.Roles) : "0"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
]),
Issuer = _configuration["JwtConfig:Issuer"],
Audience = _configuration["JwtConfig:Audience"],
Expires = DateTime.UtcNow.AddMinutes(15),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = jwtHandler.CreateToken(descriptor);
var jwtToken = jwtHandler.WriteToken(token);
var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.UserUUID == user.UUID);
if (existingToken != null)
{
existingToken.JwtId = token.Id;
existingToken.Used = false;
existingToken.CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
existingToken.ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds();
existingToken.Token = RandomString(36) + Guid.NewGuid();
_db.RefreshTokens.Update(existingToken);
}
else
{
var refreshToken = new RefreshToken()
{
JwtId = token.Id,
Used = false,
User = user,
UserUUID = user.UUID,
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(),
Token = RandomString(36) + Guid.NewGuid()
};
await _db.RefreshTokens.AddAsync(refreshToken);
}
await _db.SaveChangesAsync();
return new JWTResult()
{
Token = jwtToken,
Success = true,
RefreshToken = existingToken?.Token ?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token
};
}
public async Task<bool> ValidateJWTToken(string token)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]!);
try
{
jwtHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
}, out SecurityToken validatedToken);
return true;
}
catch
{
return false;
}
}
public async Task<JWTResult> RefreshJWTToken(string token, string refreshToken)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["JwtConfig:Secret"]!);
try
{
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero,
ValidateLifetime = false
}, out SecurityToken validatedToken);
var jwtId = validatedToken.Id;
var storedRefreshToken = await _db.RefreshTokens
.FirstOrDefaultAsync(rt => rt.Token == refreshToken);
if (storedRefreshToken == null
|| storedRefreshToken.Used
|| storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|| storedRefreshToken.JwtId != jwtId)
{
return new JWTResult() { Success = false };
}
storedRefreshToken.Used = true;
await _db.SaveChangesAsync();
var userUUID = principal.Claims.First(c => c.Type == "UUID").Value;
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID.ToString() == userUUID);
if (user == null)
{
return new JWTResult() { Success = false };
}
return await GenerateJWTToken(user);
}
catch
{
return new JWTResult() { Success = false };
}
}
private static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[Random.Shared.Next(s.Length)])]);
}
}
}
+44
View File
@@ -0,0 +1,44 @@
using System.IO.Compression;
namespace SharpbinV3.Services
{
public class CompressionService : ICompressionService
{
public byte[] Compress(byte[] data)
{
byte[] result = new byte[data.Length];
using (MemoryStream ms = new())
{
using (GZipStream gzip = new(ms, CompressionMode.Compress))
{
gzip.Write(data, 0, data.Length);
}
result = ms.ToArray();
}
if (result.Length > 0 && result.Length < data.Length)
return result;
return data;
}
public byte[] Decompress(byte[] compressedData)
{
ArgumentNullException.ThrowIfNull(compressedData);
if (!IsCompressed(compressedData))
throw new ArgumentException("Data is not in a valid compressed format.", nameof(compressedData));
using (MemoryStream ms = new())
{
using MemoryStream compressedStream = new(compressedData);
using GZipStream gzip = new(compressedStream, CompressionMode.Decompress);
gzip.CopyTo(ms);
}
return compressedData;
}
private static bool IsCompressed(byte[] data)
{
return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B;
}
}
}
+13
View File
@@ -0,0 +1,13 @@
using SharpbinV3.Data.Entities;
using SharpbinV3.DTOs;
namespace SharpbinV3.Services
{
public interface IAuthService
{
Task<User> CreateUser(string username, string password, string? email, string? displayName);
Task<JWTResult> GenerateJWTToken(User user);
Task<bool> ValidateJWTToken(string token);
Task<JWTResult> RefreshJWTToken(string token, string refreshToken);
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Services
{
public interface ICompressionService
{
byte[] Compress(byte[] data);
byte[] Decompress(byte[] compressedData);
}
}
+15
View File
@@ -0,0 +1,15 @@
using SharpbinV3.Data.Entities;
namespace SharpbinV3.Services
{
public interface IPasteService
{
Task<Paste> Create(Paste paste);
Task<bool> Delete(Paste paste);
Task<Paste> Edit(Paste paste);
Task<bool> Exists(string id);
Task<bool> EditText(Paste paste, string text);
Task<Paste> Get(string id);
Task<List<Paste>> GetList(int offset, int count);
}
}
-1
View File
@@ -8,6 +8,5 @@ namespace SharpbinV3.Services
Task<User?> GetByUsername(string username); Task<User?> GetByUsername(string username);
Task<User?> GetByUUID(Guid uuid); Task<User?> GetByUUID(Guid uuid);
Task<User?> GetByEmail(string email); Task<User?> GetByEmail(string email);
Task<User> CreateUser(string username, string password, string? email, string? displayName);
} }
} }
+1 -17
View File
@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SharpbinV3.Data; using SharpbinV3.Data;
using SharpbinV3.Data.Entities; using SharpbinV3.Data.Entities;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Services namespace SharpbinV3.Services
{ {
@@ -13,21 +13,5 @@ namespace SharpbinV3.Services
public Task<User?> GetByUUID(Guid uuid) => _db.Users.FirstOrDefaultAsync(u => u.UUID == uuid); public Task<User?> GetByUUID(Guid uuid) => _db.Users.FirstOrDefaultAsync(u => u.UUID == uuid);
public Task<User?> GetByUsername(string username) => _db.Users.FirstOrDefaultAsync(u => u.Username == username); public Task<User?> GetByUsername(string username) => _db.Users.FirstOrDefaultAsync(u => u.Username == username);
public Task<User?> GetByEmail(string email) => _db.Users.FirstOrDefaultAsync(u => u.Email == email); public Task<User?> GetByEmail(string email) => _db.Users.FirstOrDefaultAsync(u => u.Email == email);
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
{
var user = new User
{
Username = username,
PasswordHash = Bcrypt.HashPassword(password),
Email = email,
DisplayName = displayName,
UUID = Guid.CreateVersion7()
};
_db.Users.Add(user);
await _db.SaveChangesAsync();
return user;
}
} }
} }
+2 -4
View File
@@ -14,6 +14,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
@@ -26,10 +27,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
</ItemGroup> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
<ItemGroup>
<Folder Include="Controllers\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+6 -1
View File
@@ -8,5 +8,10 @@
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Data Source=sharpbin.db" "DefaultConnection": "Data Source=sharpbin.db"
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"JwtConfig": {
"Secret": "",
"Issuer": "SharpbinApi",
"Audience": "SharpbinClient"
}
} }