feat: account deletion; auto incremental uids; display name renaming UI + account deletion UI; enhanced username validation

This commit is contained in:
2026-01-04 16:58:05 -05:00
parent b1d2d3f5bb
commit fe54ff15ce
18 changed files with 972 additions and 51 deletions
@@ -1,10 +1,14 @@
<script lang="ts">
export let show = false;
export let mode: 'decrypt' | 'encrypt' | 'confirm' = 'decrypt';
export let mode: 'decrypt' | 'encrypt' | 'confirm' | 'prompt' = 'decrypt';
export let title = '';
export let message = '';
export let error = '';
export let placeholder = '';
export let inputType = 'text';
export let onConfirm: (value: string | boolean) => void;
export let onCancel: () => void;
export let confirmButtonText = '';
let inputValue = '';
@@ -26,9 +30,17 @@
? 'Enter password to decrypt'
: mode === 'encrypt'
? 'Enter password to encrypt'
: 'Confirm action');
: mode === 'confirm'
? 'Confirm action'
: 'Enter value');
$: confirmLabel = mode === 'decrypt' ? 'Decrypt' : mode === 'encrypt' ? 'Encrypt' : 'Confirm';
$: confirmLabel =
confirmButtonText ||
(mode === 'decrypt' ? 'Decrypt' :
mode === 'encrypt' ? 'Encrypt' :
mode === 'confirm' ? 'Delete' :
'Confirm');
$: shouldShowInput = mode !== 'confirm';
</script>
{#if show}
@@ -41,12 +53,18 @@
{displayTitle}
</h2>
{#if mode !== 'confirm'}
{#if message}
<p class="mb-4 text-neutral-300">
{message}
</p>
{/if}
{#if shouldShowInput}
<input
type="text"
type={inputType}
bind:value={inputValue}
class="mb-3 w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
placeholder="Enter value..."
{placeholder}
/>
{/if}
@@ -59,7 +77,9 @@
<div class="flex gap-2">
<button
type="submit"
class="flex-1 cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white hover:bg-neutral-800"
class={`flex-1 cursor-pointer rounded px-4 py-2 font-semibold text-white transition-colors ${
mode === 'confirm' ? 'bg-red-900 hover:bg-red-800' : 'bg-neutral-700 hover:bg-neutral-800'
}`}
>
{confirmLabel}
</button>
@@ -13,8 +13,6 @@
export let data: PageData;
console.log(data);
let currentPath = page.url.pathname;
let returnParam =
currentPath !== '/' && !currentPath.startsWith('/login') && !currentPath.startsWith('/register')
+12
View File
@@ -98,3 +98,15 @@ export function clearServerTokens(cookies: Cookies) {
cookies.delete('token', { path: '/' });
cookies.delete('refreshToken', { path: '/' });
}
export function getUserUUIDFromToken() {
if (!browser) return null;
const token = getToken();
if (!token) return null;
try {
const payload = JSON.parse(atob(token.split('.')[1]));
return payload.UUID || null;
} catch {
return null;
}
}
+8 -8
View File
@@ -12,15 +12,15 @@
let error = '';
let title = '';
let content = '';
let selectedSyntax = data.options?.syntaxes[0];
let selectedSyntax = data.options?.syntaxes?.[0];
let expiresIn: number = 0;
let selectedVisibility = data.options?.visibilities[0].value;
let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = '';
const syntaxOptions = data.options?.syntaxes.map((lang: string) => ({
const syntaxOptions = data.options?.syntaxes?.map((lang: string) => ({
value: lang,
label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)
}));
})) ?? [];
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
@@ -38,12 +38,12 @@
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions = data.options?.visibilities.map(
const visibilityOptions = data.options?.visibilities?.map(
(visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
})
);
) ?? [];
async function handleSubmit(event: Event) {
event.preventDefault();
@@ -103,7 +103,7 @@
spellcheck="false"
autocomplete="off"
bind:value={title}
maxlength={data.options.maxTitleLength ?? 500}
maxlength={data.options?.maxTitleLength ?? 500}
/>
<textarea
placeholder="Your paste content here..."
@@ -111,7 +111,7 @@
spellcheck="false"
autocomplete="off"
bind:value={content}
maxlength={data.options.maxContentSize
maxlength={data.options?.maxContentSize
? Math.floor(data.options.maxContentSize / 4)
: undefined}
></textarea>
@@ -60,10 +60,10 @@
: false;
let interval: ReturnType<typeof setInterval> | null = null;
const syntaxOptions = data.options?.syntaxes.map((lang: string) => ({
const syntaxOptions = data.options?.syntaxes?.map((lang: string) => ({
value: lang,
label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)
}));
})) ?? [];
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 600000, label: 'Expire in 10 Minutes' },
@@ -79,12 +79,12 @@
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions = data.options?.visibilities.map(
const visibilityOptions = data.options?.visibilities?.map(
(visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
})
);
) ?? [];
onMount(() => {
interval = setInterval(() => {
@@ -302,7 +302,7 @@
bind:value={editMetadata.title}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
placeholder="Untitled Paste"
maxlength={data.options.maxTitleLength ?? 500}
maxlength={data.options?.maxTitleLength ?? 500}
/>
{/if}
</h1>
@@ -398,7 +398,7 @@
{displayNames[data.paste.syntax] ??
data.paste.syntax.charAt(0).toUpperCase() + data.paste.syntax.slice(1)}
</span>
{:else if editMetadata}
{:else if editMetadata && syntaxOptions}
<Dropdown
options={syntaxOptions}
bind:value={editMetadata.syntax}
@@ -573,7 +573,6 @@
if (editContent !== null || editMetadata !== null) {
await updatePaste(editContent, editMetadata);
}
console.log(editContent, editMetadata);
}}
disabled={editLoading}
>
@@ -1,31 +1,45 @@
<script lang="ts">
import { resolve } from '$app/paths';
import type { PageData } from './$types';
import type { Pagination } from '$lib/types/pagination';
import { User, CalendarDays, ShieldUser, Ban, File, AtSign } from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip } from '$lib/utils/misc';
import type { Pagination } from '$lib/types/pagination';
import { User, CalendarDays, ShieldUser, Ban, File, AtSign, Pencil, Trash2, Clock, Hash } from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
import { roles } from '$lib/consts';
import { getToken } from '$lib/utils/auth';
import { getToken, getUserUUIDFromToken } from '$lib/utils/auth';
import Modal from '$lib/components/Modal.svelte';
export let data: PageData;
let currentPage = data.user.pagination?.page ?? 1;
let pagination: Pagination = data.user.pagination ?? {
page: 1,
pageSize: 50,
totalCount: 0,
totalPages: 1
};
page: 1,
pageSize: 50,
totalCount: 0,
totalPages: 1
};
let pastes = data.user.pastes ?? [];
let loading = false;
let isOwner = false;
let showEditModal = false;
let showDeleteModal = false;
let modalError = '';
let newDisplayName = '';
$: {
const userUUID = getUserUUIDFromToken();
isOwner = !!userUUID && userUUID === data.user.uuid;
}
async function fetchPage(pageNum: number) {
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
loading = true;
const token = getToken();
const res = await fetch(`/api/user/${data.user.username}?page=${pageNum}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
const token = getToken();
const res = await fetch(
`/api/user/${data.user.username}?page=${pageNum}`,
{
headers: token ? { Authorization: `Bearer ${token}` } : {}
}
);
if (!res.ok) {
loading = false;
return;
@@ -36,6 +50,51 @@
currentPage = pagination.page ?? pageNum;
loading = false;
}
async function handleEditDisplayName(displayName: string) {
if (!displayName.trim()) {
modalError = 'Display name cannot be empty';
return;
}
loading = true;
const token = getToken();
const res = await fetch(`/api/user/uuid/${data.user.uuid}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ displayName: displayName.trim() })
});
loading = false;
if (!res.ok) {
const err = await res.json();
modalError = err.message || 'Failed to update display name';
return;
}
showEditModal = false;
data.user.displayName = displayName;
modalError = '';
}
async function handleDeleteAccount() {
loading = true;
const token = getToken();
const res = await fetch(`/api/user/uuid/${data.user.uuid}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`
}
});
loading = false;
if (!res.ok) {
const err = await res.json();
modalError = err.message || 'Failed to delete account';
return;
}
showDeleteModal = false;
window.location.href = '/';
}
</script>
<main
@@ -75,7 +134,7 @@
<span class="text-neutral-400">{data.user.username}</span>
</div>
{/if}
<div class="mb-2 flex flex-wrap items-center justify-center gap-4">
<div class="mb-2 flex flex-wrap items-center justify-center gap-4 text-sm">
<div class="flex shrink-0 items-center">
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
<span
@@ -91,7 +150,49 @@
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
>
</div>
<div class="flex shrink-0 items-center">
<Hash class="mr-1 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400" use:tooltip={`User #${data.user.uid}`}>
{data.user.uid}
</span>
</div>
{#if isOwner && data.user.lastLogin}
<div class="flex shrink-0 items-center">
<Clock class="mr-2 h-6 w-6 text-neutral-400" />
<span
class="text-neutral-400"
use:tooltip={new Date(data.user.lastLogin).toLocaleString()}
>
Last login {dateToRelativeString(new Date(data.user.lastLogin))}
</span>
</div>
{/if}
</div>
{#if isOwner}
<div class="mt-4 flex gap-2 justify-center flex-wrap">
<button
on:click={() => {
showEditModal = true;
newDisplayName = data.user.displayName || data.user.username;
modalError = '';
}}
class="flex items-center gap-2 rounded bg-neutral-700 hover:bg-neutral-600 px-4 py-2 text-sm font-medium transition-colors"
>
<Pencil class="h-4 w-4" />
Edit Display Name
</button>
<button
on:click={() => {
showDeleteModal = true;
modalError = '';
}}
class="flex items-center gap-2 rounded bg-red-900 hover:bg-red-800 px-4 py-2 text-sm font-medium transition-colors"
>
<Trash2 class="h-4 w-4" />
Delete Account
</button>
</div>
{/if}
<div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto">
{#if pastes && pastes.length > 0}
{#each pastes.slice().sort((a, b) => b.uuid.localeCompare(a.uuid)) as paste (paste.uuid)}
@@ -108,7 +209,7 @@
</a>
{/each}
{:else}
<p class="text-center text-neutral-400">This user has not created any pastes yet.</p>
<p class="text-center text-neutral-400">{isOwner ? 'You have' : 'This user has'} not created any pastes yet.</p>
{/if}
</div>
{#if pagination.totalPages && pagination.totalPages > 1}
@@ -134,3 +235,37 @@
{/if}
</div>
</main>
<Modal
show={showEditModal}
mode="prompt"
title="Edit Display Name "
placeholder="New Display Name"
bind:error={modalError}
onConfirm={(value) => handleEditDisplayName(value as string)}
onCancel={() => {
showEditModal = false;
modalError = '';
}}
/>
<Modal
show={showDeleteModal}
mode="confirm"
title="Delete Account"
message="This action cannot be undone. All your pastes and account data will be permanently deleted."
confirmButtonText="Delete Account"
error={modalError}
onConfirm={() => handleDeleteAccount()}
onCancel={() => {
showDeleteModal = false;
modalError = '';
}}
/>
<style>
:global(body) {
margin: 0;
padding: 0;
}
</style>
@@ -71,6 +71,28 @@ namespace SharpbinV3.Server.Controllers
return Ok(new { message = "User updated successfully." });
}
[HttpDelete("uuid/{uuid}")]
[Authorize]
public async Task<IActionResult> DeleteByUUID(Guid uuid)
{
var jwtUser = HttpContext.User;
var uuidClaim = jwtUser?.FindFirst("UUID")?.Value;
if (uuidClaim == null || jwtUser == null) return Forbid();
var userRoles = jwtUser.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value));
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound();
if (!userRoles.Any(r => r == 255) && user.UUID != Guid.Parse(uuidClaim))
return Forbid();
_db.Users.Remove(user);
await _db.SaveChangesAsync();
return Ok(new { message = "User deleted successfully." });
}
private async Task<object> BuildUserResponse(User user, int page = 1)
{
var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString();
+27 -1
View File
@@ -1,8 +1,9 @@
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs
{
public class RegisterRequest
public partial class RegisterRequest
{
[Required]
[StringLength(50, MinimumLength = 3)]
@@ -16,5 +17,30 @@ namespace SharpbinV3.Server.DTOs
public string? DisplayName { get; set; }
public string? Token { get; set; }
public IEnumerable<ValidationResult> Validate()
{
var results = new List<ValidationResult>();
if (!ValidateUsername().IsMatch(Username))
results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)]));
if (DisplayName != null)
{
if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateUsername().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)]));
}
if (Email != null)
{
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email))
results.Add(new ValidationResult("Invalid email format.", [nameof(Email)]));
}
return results;
}
[GeneratedRegex("^[A-Za-z0-9_.]+$")]
private static partial Regex ValidateUsername();
}
}
+10 -9
View File
@@ -1,38 +1,39 @@
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs
{
public class UpdateUserRequest
public partial class UpdateUserRequest
{
public string? DisplayName { get; set; }
public string? Email { get; set; }
public int? Visibility { get; set; } = 0;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
public IEnumerable<ValidationResult> Validate()
{
var results = new List<ValidationResult>();
if (DisplayName != null) {
if (DisplayName != null)
{
if (DisplayName.Length < 3 || DisplayName.Length > 26)
{
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
}
if (!ValidateDisplayname().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)]));
}
if (Email != null)
{
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email))
{
results.Add(new ValidationResult("Invalid email format.", [nameof(Email)]));
}
}
if (Visibility != null)
{
if (Visibility < 0 || Visibility > 2)
{
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
}
}
return results;
}
[GeneratedRegex("^[A-Za-z0-9_.]+$")]
private static partial Regex ValidateDisplayname();
}
}
+2 -1
View File
@@ -3,10 +3,11 @@ using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(UID))]
[Index(nameof(UUID), IsUnique = true)]
public sealed class User
{
public int UID { get; set; }
public int? UID { get; set; }
[Key]
public required Guid UUID { get; set; } = Guid.CreateVersion7(); // uuid v7 includes timestamp
public required string Username { get; set; }
@@ -0,0 +1,190 @@
// <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("20260104211956_UserUIDAutoIncrement")]
partial class UserUIDAutoIncrement
{
/// <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>("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("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,34 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserUIDAutoIncrement : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""
CREATE TRIGGER Users_UID_AutoIncrement
AFTER INSERT ON Users
BEGIN
UPDATE Users
SET UID = (
SELECT IFNULL(MAX(UID), 0) + 1 FROM Users
)
WHERE rowid = NEW.rowid AND NEW.UID IS NULL;
END;
""", suppressTransaction: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("""
DROP TRIGGER IF EXISTS Users_UID_AutoIncrement;
""");
}
}
}
@@ -0,0 +1,193 @@
// <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("20260104212417_UserUIDIndex")]
partial class UserUIDIndex
{
/// <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>("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("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID")
.IsUnique();
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("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserUIDIndex : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_UID",
table: "Users");
}
}
}
@@ -0,0 +1,192 @@
// <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("20260104212733_UserUIDNonUnique")]
partial class UserUIDNonUnique
{
/// <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>("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("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,55 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserUIDNonUnique : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_UID",
table: "Users");
migrationBuilder.AlterColumn<int>(
name: "UID",
table: "Users",
type: "INTEGER",
nullable: true,
oldClrType: typeof(int),
oldType: "INTEGER");
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_UID",
table: "Users");
migrationBuilder.AlterColumn<int>(
name: "UID",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "INTEGER",
oldNullable: true);
migrationBuilder.CreateIndex(
name: "IX_Users_UID",
table: "Users",
column: "UID",
unique: true);
}
}
}
@@ -135,7 +135,7 @@ namespace SharpbinV3.Server.Migrations
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UID")
b.Property<int?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
@@ -147,6 +147,8 @@ namespace SharpbinV3.Server.Migrations
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
+13
View File
@@ -111,6 +111,19 @@ namespace SharpbinV3.Server
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();
// this is temporary since the migration doesnt seem to work properly
db.Database.ExecuteSql($"""
CREATE TRIGGER IF NOT EXISTS Users_UID_AutoIncrement
AFTER INSERT ON Users
BEGIN
UPDATE Users
SET UID = (
SELECT IFNULL(MAX(UID), 0) + 1 FROM Users
)
WHERE rowid = NEW.rowid AND NEW.UID IS NULL;
END;
""");
}
app.MapHealthChecks("/health");