chore: rename SharpbinV3 dir to SharpbinV3.Server

This commit is contained in:
2025-12-30 12:39:26 -05:00
parent 31142e0cf9
commit 1ec4877aad
45 changed files with 7 additions and 94 deletions
@@ -0,0 +1,115 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.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." });
if (!string.IsNullOrEmpty(request.Email))
{
var existingEmailUser = await _userService.GetByEmail(request.Email);
if (existingEmailUser != null)
return Conflict(new { message = "Email already in use." });
if (!IsValidEmail(request.Email))
return BadRequest(new { message = "Invalid email." });
}
if (!IsValidPassword(request.Password))
return BadRequest(new { message = "Password should have at least 8 characters, including uppercase, lowercase, and digits." });
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);
await _authService.UpdateLoginTime(user);
return Ok(new { token.Result });
}
[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 });
}
}
private static bool IsValidPassword(string password)
{
if (password.Length < 6)
return false;
if (!password.Any(char.IsUpper))
return false;
if (!password.Any(char.IsLower))
return false;
if (!password.Any(char.IsDigit))
return false;
return true;
}
private static bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
}
}
@@ -0,0 +1,212 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Settings;
using System.Security.Claims;
namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(IPasteService pasteService, IUserService userService, IOptions<PasteSettings> options) : ControllerBase
{
private readonly IPasteService _pasteService = pasteService;
private readonly IUserService _userService = userService;
private readonly PasteSettings _pasteSettings = options.Value;
[HttpPost]
[Route("create")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
{
if (!await _pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(visibility))
return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(syntax))
return BadRequest(new { message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(title))
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
var httpUser = HttpContext.User;
var userUUID = httpUser?.FindFirst("UUID")?.Value;
User? user = userUUID is not null ? await _userService.GetByUUID(Guid.Parse(userUUID)) : null;
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
return Ok(new
{
paste.ID,
paste.UUID,
paste.IsCompressed,
paste.Size,
paste.TrueSize,
paste.ExpiresAt
});
}
[HttpGet]
[Route("{id}")]
public async Task<IActionResult> GetPasteByID(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
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
});
}
[HttpGet]
[Route("raw/{id}")]
public async Task<IActionResult> GetRawPasteByID(string id)
{
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");
}
}
[HttpPut]
[Route("{id}/edit")]
[Authorize]
public async Task<IActionResult> EditPaste(string id)
{
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content == null || id == null) return NotFound();
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.User;
var uuidClaim = user?.FindFirst("UUID")?.Value;
if (uuidClaim == null || user == null) return Forbid();
var hasPrivilegedRole = user.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) || !hasPrivilegedRole)
return Forbid();
bool result = await _pasteService.EditText(paste, content);
if (!result) return NotFound();
return Ok(new { message = "Paste edited successfully." });
}
[HttpPatch]
[Route("{id}/modify")]
[Authorize]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] PasteMetadataUpdateRequest request)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.User;
var uuidClaim = user?.FindFirst("UUID")?.Value;
if (uuidClaim == null || user == null) return Forbid();
var hasPrivilegedRole = user.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) || !hasPrivilegedRole)
return Forbid();
if (request.Title != null)
paste.Title = request.Title;
if (request.Syntax != null)
paste.Syntax = request.Syntax;
if (request.Visibility.HasValue)
paste.Visibility = request.Visibility.Value;
if (request.ExpiresAt.HasValue)
paste.ExpiresAt = request.ExpiresAt.Value;
if (!await _pasteService.ValidateExpiresAt(paste.ExpiresAt))
return BadRequest(new { message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(paste.Visibility))
return BadRequest(new { message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(paste.Syntax ?? "plaintext"))
return BadRequest(new { message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(paste.Title ?? ""))
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
var newPaste = await _pasteService.Edit(paste);
return Ok(new
{
message = "Paste metadata updated successfully.",
paste = new
{
newPaste.ID,
newPaste.UUID,
newPaste.Title,
newPaste.Size,
newPaste.TrueSize,
newPaste.IsCompressed,
newPaste.Views,
newPaste.Syntax,
newPaste.Visibility,
newPaste.ExpiresAt
}
});
}
[HttpDelete]
[Route("{id}")]
[Authorize]
public async Task<IActionResult> DeletePaste(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.User;
var uuidClaim = user?.FindFirst("UUID")?.Value;
if (uuidClaim == null || user == null) return Forbid();
var hasPrivilegedRole = user.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) || !hasPrivilegedRole)
return Forbid();
bool result = await _pasteService.Delete(paste);
if (!result) return NotFound();
return Ok(new { message = "Paste deleted successfully." });
}
[HttpGet]
[Route("create/options")]
public IActionResult GetCreatePasteOptions()
{
var options = new
{
syntaxes = _pasteSettings.ValidSyntaxLanguages,
visibilities = new[]
{
new { value = 0, displayName = "Public" },
new { value = 1, displayName = "Unlisted" },
new { value = 2, displayName = "Private" }
},
maxTitleLength = _pasteSettings.MaxTitleLength,
maxPasteSize = _pasteSettings.MaxPasteSizeInBytes
};
return Ok(options);
}
}
}
@@ -0,0 +1,120 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(IUserService userService, AppDbContext db) : ControllerBase
{
private readonly IUserService _userService = userService;
private readonly AppDbContext _db = db;
[HttpGet("{username}")]
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
{
var user = await _userService.GetByUsername(username, withPastes: true);
return user == null ? NotFound() : Ok(await BuildUserResponse(user, page));
}
[HttpGet("uuid/{uuid}")]
public async Task<IActionResult> GetByUUID(Guid uuid, [FromQuery] int page = 1)
{
var user = await _userService.GetByUUID(uuid, withPastes: true);
return user == null ? NotFound() : Ok(await BuildUserResponse(user, page));
}
[HttpGet("me")]
[Authorize]
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
{
var userUUID = HttpContext.User?.FindFirst("UUID")?.Value;
if (userUUID is null)
return Unauthorized(new { message = "Invalid token." });
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
return user == null ? NotFound() : Ok(await BuildUserResponse(user, page));
}
private async Task<object> BuildUserResponse(User user, int page = 1)
{
var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString();
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser)
{
if (user.Visibility == 1 || user.Visibility == 2)
return NotFound();
else
pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
}
if (page < 1)
page = 1;
const int pageSize = 50;
var totalCount = await pasteQuery.CountAsync();
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var skip = (page - 1) * pageSize;
var pastes = await pasteQuery
.OrderByDescending(p => p.UUID)
.ThenByDescending(p => p.ID)
.Skip(skip)
.Take(pageSize)
.Select(p => new
{
p.ID,
p.UUID,
p.Title,
p.Syntax,
p.Size,
p.TrueSize,
p.Views,
p.Visibility,
p.EditedAt,
p.ExpiresAt
})
.ToListAsync();
var pagination = new
{
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
};
if (isAuthenticatedUser)
{
return new
{
user.UID,
user.Username,
user.UUID,
user.DisplayName,
user.Email,
user.LastLogin,
user.Roles,
user.Visibility,
Pastes = pastes,
Pagination = pagination
};
}
return new
{
user.UID,
user.Username,
user.UUID,
user.DisplayName,
user.Roles,
Pastes = pastes,
Pagination = pagination
};
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.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; }
}
}
+13
View File
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
{
public class LoginRequest
{
[StringLength(50, MinimumLength = 3)]
public string? Username { get; set; }
public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
}
}
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs
{
public class PasteMetadataUpdateRequest
{
public string? Title { get; set; }
public string? Syntax { get; set; }
public int? Visibility { get; set; }
public long? ExpiresAt { get; set; }
}
}
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
{
public class RefreshTokenRequest
{
[Required]
public required string Token { get; set; }
[Required]
public required string RefreshToken { get; set; }
}
}
+19
View File
@@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
{
public class RegisterRequest
{
[Required]
[StringLength(50, MinimumLength = 3)]
public required string Username { get; set; }
[Required]
[StringLength(128, MinimumLength = 6)]
public required string Password { get; set; }
public string? Email { get; set; }
public string? DisplayName { get; set; }
}
}
+30
View File
@@ -0,0 +1,30 @@
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["SharpbinV3.Server.csproj", "./"]
RUN dotnet restore "./SharpbinV3.Server.csproj"
COPY . .
WORKDIR "/src/SharpbinV3"
RUN dotnet build "../SharpbinV3.Server.csproj" -c $BUILD_CONFIGURATION -o /app/build
# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "../SharpbinV3.Server.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "SharpbinV3.Server.dll"]
@@ -0,0 +1,197 @@
// <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("20251125015039_Init")]
partial class Init
{
/// <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.Property<int>("Visiblity")
.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.HasIndex("Visiblity");
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 =>
{
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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visiblity")
.HasColumnType("INTEGER");
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.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,159 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
UID = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
UUID = table.Column<Guid>(type: "TEXT", nullable: false),
Username = table.Column<string>(type: "TEXT", nullable: false),
PasswordHash = table.Column<string>(type: "TEXT", nullable: false),
Email = table.Column<string>(type: "TEXT", nullable: true),
DisplayName = table.Column<string>(type: "TEXT", 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 =>
{
table.PrimaryKey("PK_Users", x => x.UID);
});
migrationBuilder.CreateTable(
name: "Pastes",
columns: table => new
{
PID = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
UUID = table.Column<string>(type: "TEXT", nullable: false),
ID = table.Column<string>(type: "TEXT", nullable: true),
Title = table.Column<string>(type: "TEXT", nullable: true),
AuthorUUID = table.Column<string>(type: "TEXT", nullable: false),
UserUID = table.Column<int>(type: "INTEGER", nullable: true),
FilePath = table.Column<string>(type: "TEXT", nullable: false),
EditedAt = table.Column<long>(type: "INTEGER", nullable: true),
Size = table.Column<int>(type: "INTEGER", nullable: false),
TrueSize = table.Column<int>(type: "INTEGER", nullable: false),
Views = table.Column<int>(type: "INTEGER", nullable: false),
Syntax = table.Column<string>(type: "TEXT", nullable: true),
Visiblity = table.Column<int>(type: "INTEGER", nullable: false),
ExpiresAt = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Pastes", x => x.PID);
table.ForeignKey(
name: "FK_Pastes_Users_UserUID",
column: x => x.UserUID,
principalTable: "Users",
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(
name: "IX_Pastes_UserUID",
table: "Pastes",
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 />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Pastes");
migrationBuilder.DropTable(
name: "RefreshTokens");
migrationBuilder.DropTable(
name: "Users");
}
}
}
@@ -0,0 +1,198 @@
// <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("20251125053617_ImprovePastes")]
partial class ImprovePastes
{
/// <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<Guid>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Data")
.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<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visiblity")
.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.HasIndex("Visiblity");
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 =>
{
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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visiblity")
.HasColumnType("INTEGER");
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.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,51 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class ImprovePastes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FilePath",
table: "Pastes");
migrationBuilder.AddColumn<byte[]>(
name: "Data",
table: "Pastes",
type: "BLOB",
nullable: false,
defaultValue: new byte[0]);
migrationBuilder.AddColumn<bool>(
name: "IsCompressed",
table: "Pastes",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Data",
table: "Pastes");
migrationBuilder.DropColumn(
name: "IsCompressed",
table: "Pastes");
migrationBuilder.AddColumn<string>(
name: "FilePath",
table: "Pastes",
type: "TEXT",
nullable: false,
defaultValue: "");
}
}
}
@@ -0,0 +1,198 @@
// <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("20251125055340_PasteContent")]
partial class PasteContent
{
/// <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<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<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visiblity")
.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.HasIndex("Visiblity");
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 =>
{
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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visiblity")
.HasColumnType("INTEGER");
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.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class PasteContent : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Data",
table: "Pastes",
newName: "Content");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Content",
table: "Pastes",
newName: "Data");
}
}
}
@@ -0,0 +1,198 @@
// <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("20251125061310_GrammarFix")]
partial class GrammarFix
{
/// <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<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<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
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("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
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 =>
{
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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visiblity")
.HasColumnType("INTEGER");
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.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class GrammarFix : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Visiblity",
table: "Pastes",
newName: "Visibility");
migrationBuilder.RenameIndex(
name: "IX_Pastes_Visiblity",
table: "Pastes",
newName: "IX_Pastes_Visibility");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Visibility",
table: "Pastes",
newName: "Visiblity");
migrationBuilder.RenameIndex(
name: "IX_Pastes_Visibility",
table: "Pastes",
newName: "IX_Pastes_Visiblity");
}
}
}
@@ -0,0 +1,195 @@
// <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("20251228173503_UserGrammarFix")]
partial class UserGrammarFix
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
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<int>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<int>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
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("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.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.Server.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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserGrammarFix : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_UID",
table: "Users");
migrationBuilder.RenameColumn(
name: "Visiblity",
table: "Users",
newName: "Visibility");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Visibility",
table: "Users",
newName: "Visiblity");
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID",
unique: true);
}
}
}
@@ -0,0 +1,195 @@
// <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("20251228175338_LongFileSizes")]
partial class LongFileSizes
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
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?>("UserUID")
.HasColumnType("INTEGER");
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("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.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.Server.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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class LongFileSizes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
@@ -0,0 +1,192 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
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?>("UserUID")
.HasColumnType("INTEGER");
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("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.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.Server.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.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
});
#pragma warning restore 612, 618
}
}
}
+111
View File
@@ -0,0 +1,111 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Settings;
using System.Text;
using System.Threading.RateLimiting;
namespace SharpbinV3.Server
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddDbContext<AppDbContext>(opt =>
{
opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddSingleton<ICompressionService, CompressionService>();
builder.Services.AddSingleton<IHostedService, PasteCleanUpService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IPasteService, PasteService>();
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwt =>
{
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var key = Encoding.UTF8.GetBytes(jwtSettings["Secret"]!);
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = jwtSettings["Issuer"],
ValidateAudience = true,
ValidAudience = jwtSettings["Audience"],
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
};
});
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;
});
builder.Services.AddCors(o =>
{
o.AddDefaultPolicy(p =>
p.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.AllowAnyMethod());
});
builder.Services.Configure<PasteSettings>(builder.Configuration.GetSection("PasteSettings"));
builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings"));
var app = builder.Build();
app.UseRateLimiter();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();
}
app.Run();
}
}
}
@@ -0,0 +1,31 @@
{
"profiles": {
"http": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5050"
},
"https": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7149;http://localhost:5050"
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json"
}
+172
View File
@@ -0,0 +1,172 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Settings;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services
{
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> options) : IAuthService
{
private readonly AppDbContext _db = db;
private readonly JWTSettings _jwtSettings = options.Value;
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.UTF8.GetBytes(_jwtSettings.Secret);
var claims = new List<Claim>
{
new("UUID", user.UUID.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
if (user.Roles != null)
{
foreach (var role in user.Roles)
claims.Add(new Claim(ClaimTypes.Role, role.ToString()));
}
else
{
claims.Add(new Claim(ClaimTypes.Role, "0"));
}
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Issuer = _jwtSettings.Issuer,
Audience = _jwtSettings.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 = Utilities.GenerateRandomString(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 = Utilities.GenerateRandomString(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<JWTResult> RefreshJWTToken(string token, string refreshToken)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
try
{
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ClockSkew = TimeSpan.Zero,
ValidateLifetime = false,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
}, 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, Errors = ["Invalid refresh token, possibly already used or expired."] };
}
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 == Guid.Parse(userUUID));
if (user == null || storedRefreshToken.UserUUID != Guid.Parse(userUUID))
return new JWTResult() { Success = false, Errors = ["Invalid token."] };
return await GenerateJWTToken(user);
}
catch
{
return new JWTResult() { Success = false, Errors = ["Server Error"] };
}
}
public async Task<User> UpdateUser(User user)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.Username = user.Username;
existingUser.Email = user.Email;
existingUser.DisplayName = user.DisplayName;
existingUser.Roles = user.Roles;
existingUser.LastLogin = user.LastLogin;
existingUser.Visibility = user.Visibility;
_db.Users.Update(existingUser);
await _db.SaveChangesAsync();
return user;
}
public async Task UpdateLoginTime(User user)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.LastLogin = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
_db.Users.Update(existingUser);
await _db.SaveChangesAsync();
}
}
}
@@ -0,0 +1,49 @@
using System.IO.Compression;
namespace SharpbinV3.Server.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[] Compress(string data)
{
ArgumentNullException.ThrowIfNull(data);
return Compress(System.Text.Encoding.UTF8.GetBytes(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;
}
}
}
@@ -0,0 +1,14 @@
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
namespace SharpbinV3.Server.Services
{
public interface IAuthService
{
Task<User> CreateUser(string username, string password, string? email, string? displayName);
Task<JWTResult> GenerateJWTToken(User user);
Task<JWTResult> RefreshJWTToken(string token, string refreshToken);
Task<User> UpdateUser(User user);
Task UpdateLoginTime(User user);
}
}
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Services
{
public interface ICompressionService
{
byte[] Compress(byte[] data);
byte[] Compress(string data);
byte[] Decompress(byte[] compressedData);
}
}
@@ -0,0 +1,20 @@
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public interface IPasteService
{
Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt);
Task<bool> Delete(Paste paste);
Task<Paste> Edit(Paste paste);
Task<bool> Exists(string id);
Task<bool> Exists(Guid uuid);
Task<bool> EditText(Paste paste, string text);
Task<Paste?> Get(string id);
Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false);
Task<bool> ValidateSyntax(string syntax);
Task<bool> ValidateTitle(string title);
Task<bool> ValidateVisibility(int visibility);
Task<bool> ValidateExpiresAt(long expiresAt);
}
}
@@ -0,0 +1,12 @@
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public interface IUserService
{
Task<User?> GetByUID(int uid, bool withPastes = false);
Task<User?> GetByUsername(string username, bool withPastes = false);
Task<User?> GetByUUID(Guid uuid, bool withPastes = false);
Task<User?> GetByEmail(string email, bool withPastes = false);
}
}
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services
{
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService
{
private readonly TimeSpan _period = TimeSpan.FromMinutes(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(_period);
await Cleanup(stoppingToken);
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await Cleanup(stoppingToken);
}
catch (Exception ex)
{
logger.LogError(ex, "Error occurred during paste cleanup");
}
}
}
private async Task Cleanup(CancellationToken stoppingToken)
{
using var scope = serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var expiredPastes = db.Pastes.Where(p => p.ExpiresAt != 0 && p.ExpiresAt <= now);
if (await expiredPastes.AnyAsync(stoppingToken))
{
var deletedCount = await expiredPastes.CountAsync(stoppingToken);
db.Pastes.RemoveRange(expiredPastes);
await db.SaveChangesAsync(stoppingToken);
logger.LogInformation("Deleted {Count} expired pastes", deletedCount);
}
}
}
}
+113
View File
@@ -0,0 +1,113 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Settings;
using System.Text;
namespace SharpbinV3.Server.Services
{
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options) : IPasteService
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
private readonly PasteSettings _pasteSettings = options.Value;
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt)
{
var compressedData = _cs.Compress(content);
var paste = new Paste
{
UUID = Guid.CreateVersion7(),
ID = Utilities.GenerateRandomString(8),
Title = title,
AuthorUUID = author?.UUID ?? Guid.Empty,
User = author,
Content = compressedData,
Size = compressedData.Length,
TrueSize = Encoding.UTF8.GetByteCount(content),
IsCompressed = compressedData.Length < Encoding.UTF8.GetByteCount(content),
Syntax = syntax,
Visibility = visibility,
ExpiresAt = expiresAt,
};
_db.Pastes.Add(paste);
if (author != null)
{
author.Pastes.Add(paste);
_db.Users.Update(author);
}
await _db.SaveChangesAsync();
return paste;
}
public async Task<bool> Delete(Paste paste)
{
_db.Pastes.Remove(paste);
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<Paste> Edit(Paste paste)
{
_db.Pastes.Update(paste);
await _db.SaveChangesAsync();
return paste;
}
public async Task<bool> Exists(string id)
{
return await _db.Pastes.AnyAsync(p => p.ID == id);
}
public async Task<bool> Exists(Guid uuid)
{
return await _db.Pastes.AnyAsync(p => p.UUID == uuid);
}
public async Task<bool> EditText(Paste paste, string text)
{
var compressedData = _cs.Compress(text);
paste.Content = compressedData;
paste.Size = compressedData.Length;
paste.TrueSize = Encoding.UTF8.GetByteCount(text);
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
paste.IsCompressed = compressedData.Length < Encoding.UTF8.GetByteCount(text);
_db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<Paste?> Get(string id)
{
var paste = await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
return paste ?? null;
}
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
{
var query = _db.Pastes.AsQueryable();
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
return await query
.OrderByDescending(p => p.PID)
.Skip(offset)
.Take(count)
.ToListAsync();
}
public async Task<bool> ValidateSyntax(string syntax)
{
return await Task.FromResult(_pasteSettings.ValidSyntaxLanguages.Contains(syntax));
}
public async Task<bool> ValidateTitle(string title)
{
return await Task.FromResult(title.Length <= _pasteSettings.MaxTitleLength);
}
public async Task<bool> ValidateVisibility(int visibility)
{
return await Task.FromResult(visibility >= 0 && visibility <= 2);
}
public async Task<bool> ValidateExpiresAt(long expiresAt)
{
if (expiresAt == 0) return true;
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
return await Task.FromResult(expiresAt > currentTime - 1000);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public sealed class UserService(AppDbContext db) : IUserService
{
private readonly AppDbContext _db = db;
public Task<User?> GetByUID(int uid, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.UID == uid);
}
public Task<User?> GetByUUID(Guid uuid, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.UUID == uuid);
}
public Task<User?> GetByUsername(string username, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.Username == username);
}
public Task<User?> GetByEmail(string email, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
if (withPastes)
query = query.Include(u => u.Pastes);
return query.FirstOrDefaultAsync(u => u.Email == email);
}
}
}
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Settings
{
public class JWTSettings
{
public string Secret { get; set; } = Utilities.GenerateRandomString(64);
public string Issuer { get; set; } = "SharpbinApi";
public string Audience { get; set; } = "SharpbinClient";
}
}
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Settings
{
public class PasteSettings
{
public string[] ValidSyntaxLanguages { get; set; } = [];
public int MaxTitleLength { get; set; } = 500;
public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB
}
}
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>a95b1aac-5cce-4fa9-8056-51f0d045cf2f</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<EnableStaticWebAssets>false</EnableStaticWebAssets>
<EnableDefaultContentItems>false</EnableDefaultContentItems>
</PropertyGroup>
<ItemGroup>
<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.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
</ItemGroup>
</Project>
+24
View File
@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV3.Server", "SharpbinV3.Server.csproj", "{79A5E17C-498C-F55E-C79E-1F32E48383EF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7F30EE13-B933-4515-AA54-DBDD2605C90C}
EndGlobalSection
EndGlobal
+12
View File
@@ -0,0 +1,12 @@
namespace SharpbinV3.Server
{
public class Utilities
{
public static string GenerateRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
}
}
}
@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"JwtSettings": {
"Secret": "ad277c181e51d2131017abc53a5805ccb85410ab902d2e1e09266304e4e86d6c38f2b2543b708d678dfdbfb76016dcf568925ddb25dc91638a69e479e31a23c9",
"Issuer": "SharpbinApi",
"Audience": "SharpbinClient"
}
}
+173
View File
@@ -0,0 +1,173 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Data Source=sharpbin.db"
},
"AllowedHosts": "*",
"JwtSettings": {
"Secret": "",
"Issuer": "SharpbinApi",
"Audience": "SharpbinClient"
},
"PasteSettings": {
"ValidSyntaxLanguages": [
"plaintext",
"abap",
"actionscript-3",
"ada",
"apache",
"apex",
"apl",
"applescript",
"ara",
"asm",
"astro",
"awk",
"ballerina",
"bat",
"berry",
"bibtex",
"bicep",
"blade",
"c",
"cadence",
"clarity",
"clojure",
"cmake",
"cobol",
"codeql",
"coffee",
"cpp",
"crystal",
"csharp",
"css",
"cue",
"d",
"dart",
"diff",
"docker",
"dream-maker",
"elixir",
"elm",
"erb",
"erlang",
"fish",
"fsharp",
"gdresource",
"gdscript",
"gdshader",
"gherkin",
"git-commit",
"git-rebase",
"glsl",
"gnuplot",
"go",
"graphql",
"groovy",
"hack",
"haml",
"handlebars",
"haskell",
"hcl",
"hjson",
"hlsl",
"html",
"ini",
"java",
"javascript",
"jison",
"json",
"json5",
"jsonc",
"jsonnet",
"jssm",
"jsx",
"julia",
"kotlin",
"latex",
"less",
"liquid",
"lisp",
"logo",
"lua",
"makefile",
"markdown",
"marko",
"matlab",
"mdx",
"nginx",
"nim",
"nix",
"objective-c",
"objective-cpp",
"ocaml",
"pascal",
"perl",
"php",
"plsql",
"postcss",
"powerquery",
"powershell",
"prisma",
"prolog",
"proto",
"pug",
"puppet",
"purescript",
"python",
"r",
"raku",
"razor",
"reg",
"rel",
"riscv",
"rst",
"ruby",
"rust",
"sas",
"sass",
"scala",
"scheme",
"scss",
"shaderlab",
"shell",
"smalltalk",
"solidity",
"sparql",
"sql",
"ssh-config",
"stata",
"stylus",
"svelte",
"swift",
"system-verilog",
"tasl",
"tcl",
"tex",
"toml",
"tsx",
"turtle",
"twig",
"typescript",
"v",
"vb",
"verilog",
"vhdl",
"viml",
"vue",
"wasm",
"wenyan",
"xml",
"xsl",
"yaml",
"zenscript"
],
"MaxPasteSizeBytes": 1048576,
"MaxTitleLength": 500
}
}