feat: admins can change user's roles

refactor: banned role has priority over all other roles when displaying
chore: npm run format
This commit is contained in:
2026-01-06 14:07:55 -05:00
parent fe54ff15ce
commit 99feb2795a
8 changed files with 188 additions and 112 deletions
@@ -1,19 +1,26 @@
<script lang="ts"> <script lang="ts">
export let show = false; export let show = false;
export let mode: 'decrypt' | 'encrypt' | 'confirm' | 'prompt' = 'decrypt'; export let mode: 'decrypt' | 'encrypt' | 'confirm' | 'prompt' | 'multiselect' = 'decrypt';
export let title = ''; export let title = '';
export let message = ''; export let message = '';
export let error = ''; export let error = '';
export let placeholder = ''; export let placeholder = '';
export let inputType = 'text'; export let inputType = 'text';
export let onConfirm: (value: string | boolean) => void; export let items: { label: string; value: any }[] = [];
export let initialValue: any = null;
export let onConfirm: (value: any) => void;
export let onCancel: () => void; export let onCancel: () => void;
export let confirmButtonText = ''; export let confirmButtonText = '';
let inputValue = ''; let inputValue: any = '';
$: if (!show) { $: if (!show) {
inputValue = ''; inputValue =
initialValue !== null
? JSON.parse(JSON.stringify(initialValue))
: mode === 'multiselect'
? []
: '';
} }
function handleSubmit() { function handleSubmit() {
@@ -32,15 +39,20 @@
? 'Enter password to encrypt' ? 'Enter password to encrypt'
: mode === 'confirm' : mode === 'confirm'
? 'Confirm action' ? 'Confirm action'
: mode === 'multiselect'
? 'Select items'
: 'Enter value'); : 'Enter value');
$: confirmLabel = $: confirmLabel =
confirmButtonText || confirmButtonText ||
(mode === 'decrypt' ? 'Decrypt' : (mode === 'decrypt'
mode === 'encrypt' ? 'Encrypt' : ? 'Decrypt'
mode === 'confirm' ? 'Delete' : : mode === 'encrypt'
'Confirm'); ? 'Encrypt'
$: shouldShowInput = mode !== 'confirm'; : mode === 'confirm'
? 'Delete'
: 'Confirm');
$: shouldShowInput = mode !== 'confirm' && mode !== 'multiselect';
</script> </script>
{#if show} {#if show}
@@ -68,6 +80,26 @@
/> />
{/if} {/if}
{#if mode === 'multiselect'}
<div
class="mb-4 max-h-60 overflow-y-auto rounded border border-neutral-700 bg-neutral-800 p-2"
>
{#each items as item}
<label
class="flex cursor-pointer items-center gap-2 rounded p-2 text-white hover:bg-neutral-700"
>
<input
type="checkbox"
bind:group={inputValue}
value={item.value}
class="h-4 w-4 rounded border-neutral-600 bg-neutral-700 text-neutral-500"
/>
<span>{item.label}</span>
</label>
{/each}
</div>
{/if}
{#if error} {#if error}
<div class="mb-3 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"> <div class="mb-3 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{error} {error}
@@ -78,7 +110,9 @@
<button <button
type="submit" type="submit"
class={`flex-1 cursor-pointer rounded px-4 py-2 font-semibold text-white transition-colors ${ 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' mode === 'confirm'
? 'bg-red-900 hover:bg-red-800'
: 'bg-neutral-700 hover:bg-neutral-800'
}`} }`}
> >
{confirmLabel} {confirmLabel}
-12
View File
@@ -98,15 +98,3 @@ export function clearServerTokens(cookies: Cookies) {
cookies.delete('token', { path: '/' }); cookies.delete('token', { path: '/' });
cookies.delete('refreshToken', { 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;
}
}
+6 -6
View File
@@ -17,7 +17,8 @@
let selectedVisibility = data.options?.visibilities?.[0]?.value; let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = ''; let password = '';
const syntaxOptions = data.options?.syntaxes?.map((lang: string) => ({ const syntaxOptions =
data.options?.syntaxes?.map((lang: string) => ({
value: lang, value: lang,
label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1) label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? []; })) ?? [];
@@ -38,12 +39,11 @@
{ value: 315360000000, label: 'Expire in 10 Years' } { value: 315360000000, label: 'Expire in 10 Years' }
]; ];
const visibilityOptions = data.options?.visibilities?.map( const visibilityOptions =
(visibility: { value: number; displayName: string }) => ({ data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value, value: visibility.value,
label: visibility.displayName label: visibility.displayName
}) })) ?? [];
) ?? [];
async function handleSubmit(event: Event) { async function handleSubmit(event: Event) {
event.preventDefault(); event.preventDefault();
@@ -143,7 +143,7 @@
{/if} {/if}
<button <button
type="submit" type="submit"
class="w-full rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 cursor-pointer" class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900"
>Create Paste</button >Create Paste</button
> >
{#if error} {#if error}
+8 -10
View File
@@ -60,7 +60,8 @@
: false; : false;
let interval: ReturnType<typeof setInterval> | null = null; 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, value: lang,
label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1) label: displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? []; })) ?? [];
@@ -79,12 +80,11 @@
{ value: 157680000000, label: 'Expire in 5 Years' }, { value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' } { value: 315360000000, label: 'Expire in 10 Years' }
]; ];
const visibilityOptions = data.options?.visibilities?.map( const visibilityOptions =
(visibility: { value: number; displayName: string }) => ({ data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value, value: visibility.value,
label: visibility.displayName label: visibility.displayName
}) })) ?? [];
) ?? [];
onMount(() => { onMount(() => {
interval = setInterval(() => { interval = setInterval(() => {
@@ -559,7 +559,7 @@
alert('Failed to delete paste.'); alert('Failed to delete paste.');
} }
} }
}) });
}} }}
> >
<Trash2 class="mr-1 h-5 w-5 text-red-400" /> <Trash2 class="mr-1 h-5 w-5 text-red-400" />
@@ -647,13 +647,11 @@
modalResolve = null; modalResolve = null;
} }
}} }}
title={ title={modalMode === 'decrypt'
modalMode === 'decrypt'
? 'Decrypt Paste' ? 'Decrypt Paste'
: modalMode === 'encrypt' : modalMode === 'encrypt'
? 'Encrypt Paste' ? 'Encrypt Paste'
: 'Are you sure you want to delete this paste?' : 'Are you sure you want to delete this paste?'}
}
/> />
<style> <style>
@@ -2,11 +2,23 @@
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import type { PageData } from './$types'; import type { PageData } from './$types';
import type { Pagination } from '$lib/types/pagination'; import type { Pagination } from '$lib/types/pagination';
import { User, CalendarDays, ShieldUser, Ban, File, AtSign, Pencil, Trash2, Clock, Hash } from '@lucide/svelte'; import {
User,
CalendarDays,
ShieldUser,
Ban,
File,
AtSign,
Pencil,
Trash2,
Clock,
Hash
} from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc'; import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
import { roles } from '$lib/consts'; import { roles } from '$lib/consts';
import { getToken, getUserUUIDFromToken } from '$lib/utils/auth'; import { getToken } from '$lib/utils/auth';
import Modal from '$lib/components/Modal.svelte'; import Modal from '$lib/components/Modal.svelte';
import { user } from '$lib/stores/user';
export let data: PageData; export let data: PageData;
@@ -22,24 +34,26 @@
let isOwner = false; let isOwner = false;
let showEditModal = false; let showEditModal = false;
let showDeleteModal = false; let showDeleteModal = false;
let showRoleModal = false;
let modalError = ''; let modalError = '';
let newDisplayName = ''; let newDisplayName = '';
$: { $: isOwner = data.user && $user ? data.user.uuid === $user.uuid : false;
const userUUID = getUserUUIDFromToken();
isOwner = !!userUUID && userUUID === data.user.uuid; const roleOptions = [
} { label: 'Member', value: 0 },
{ label: 'Moderator', value: 1 },
{ label: 'Administrator', value: 255 },
{ label: 'Banned', value: 403 }
];
async function fetchPage(pageNum: number) { async function fetchPage(pageNum: number) {
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return; if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
loading = true; loading = true;
const token = getToken(); const token = getToken();
const res = await fetch( const res = await fetch(`/api/user/${data.user.username}?page=${pageNum}`, {
`/api/user/${data.user.username}?page=${pageNum}`,
{
headers: token ? { Authorization: `Bearer ${token}` } : {} headers: token ? { Authorization: `Bearer ${token}` } : {}
} });
);
if (!res.ok) { if (!res.ok) {
loading = false; loading = false;
return; return;
@@ -51,11 +65,7 @@
loading = false; loading = false;
} }
async function handleEditDisplayName(displayName: string) { async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) {
if (!displayName.trim()) {
modalError = 'Display name cannot be empty';
return;
}
loading = true; loading = true;
const token = getToken(); const token = getToken();
const res = await fetch(`/api/user/uuid/${data.user.uuid}`, { const res = await fetch(`/api/user/uuid/${data.user.uuid}`, {
@@ -64,7 +74,10 @@
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${token}` Authorization: `Bearer ${token}`
}, },
body: JSON.stringify({ displayName: displayName.trim() }) body: JSON.stringify({
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
...(selectedRoles !== undefined ? { roles: selectedRoles } : {})
})
}); });
loading = false; loading = false;
if (!res.ok) { if (!res.ok) {
@@ -73,7 +86,11 @@
return; return;
} }
showEditModal = false; showEditModal = false;
data.user.displayName = displayName; showRoleModal = false;
data.user.displayName = displayName || data.user.displayName;
if (selectedRoles !== undefined) {
data.user.roles = selectedRoles;
}
modalError = ''; modalError = '';
} }
@@ -102,25 +119,18 @@
> >
<div class="w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6"> <div class="w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="flex items-center justify-center gap-4 text-center text-4xl font-bold"> <h1 class="flex items-center justify-center gap-4 text-center text-4xl font-bold">
{#if data.user.roles.includes(1) || data.user.roles.includes(255)} {#if data.user.roles.includes(403)}
{#if Math.max(...data.user.roles.filter((r) => r !== 403)) !== -Infinity}
<span <span
use:tooltip={roles[ class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
Math.max(...data.user.roles.filter((r) => r !== 403)) as keyof typeof roles use:tooltip={roles[403]}
]}
> >
<ShieldUser class="h-8 w-8 text-neutral-400" /> <User class="h-8 w-8 text-neutral-500" />
</span>
{:else}
<span use:tooltip={'User'}>
<User class="h-8 w-8 text-neutral-400" />
</span>
{/if}
{:else if data.user.roles.includes(403)}
<span class="relative flex items-center justify-center" use:tooltip={roles[403]}>
<User class="h-8 w-8 text-neutral-500 opacity-90" />
<Ban class="absolute h-7 w-7 text-red-500" /> <Ban class="absolute h-7 w-7 text-red-500" />
</span> </span>
{:else if data.user.roles.includes(1) || data.user.roles.includes(255)}
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
<ShieldUser class="h-8 w-8 text-neutral-400" />
</span>
{:else} {:else}
<span use:tooltip={'User'}> <span use:tooltip={'User'}>
<User class="h-8 w-8 text-neutral-400" /> <User class="h-8 w-8 text-neutral-400" />
@@ -168,29 +178,43 @@
</div> </div>
{/if} {/if}
</div> </div>
{#if isOwner} {#if isOwner || $user?.roles.some((r) => r === 255 || r === 1)}
<div class="mt-4 flex gap-2 justify-center flex-wrap"> <div class="mt-4 flex flex-wrap justify-center gap-2">
<button <button
on:click={() => { on:click={() => {
showEditModal = true; showEditModal = true;
newDisplayName = data.user.displayName || data.user.username; newDisplayName = data.user.displayName || data.user.username;
modalError = ''; 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" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
<Pencil class="h-4 w-4" /> <Pencil class="h-4 w-4" />
Edit Display Name Edit Display Name
</button> </button>
{#if $user?.roles.some((r) => r === 255)}
<button
on:click={() => {
showRoleModal = true;
modalError = '';
}}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<ShieldUser class="h-4 w-4" />
Edit Roles
</button>
{/if}
{#if isOwner || $user?.roles.some((r) => r === 255)}
<button <button
on:click={() => { on:click={() => {
showDeleteModal = true; showDeleteModal = true;
modalError = ''; 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" class="flex items-center gap-2 rounded bg-red-900 px-4 py-2 text-sm font-medium transition-colors hover:bg-red-800"
> >
<Trash2 class="h-4 w-4" /> <Trash2 class="h-4 w-4" />
Delete Account Delete Account
</button> </button>
{/if}
</div> </div>
{/if} {/if}
<div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto"> <div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto">
@@ -209,7 +233,9 @@
</a> </a>
{/each} {/each}
{:else} {:else}
<p class="text-center text-neutral-400">{isOwner ? 'You have' : '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} {/if}
</div> </div>
{#if pagination.totalPages && pagination.totalPages > 1} {#if pagination.totalPages && pagination.totalPages > 1}
@@ -242,7 +268,7 @@
title="Edit Display Name " title="Edit Display Name "
placeholder="New Display Name" placeholder="New Display Name"
bind:error={modalError} bind:error={modalError}
onConfirm={(value) => handleEditDisplayName(value as string)} onConfirm={(value) => handleUserUpdate(value as string)}
onCancel={() => { onCancel={() => {
showEditModal = false; showEditModal = false;
modalError = ''; modalError = '';
@@ -253,7 +279,7 @@
show={showDeleteModal} show={showDeleteModal}
mode="confirm" mode="confirm"
title="Delete Account" title="Delete Account"
message="This action cannot be undone. All your pastes and account data will be permanently deleted." message={`This action cannot be undone. ${isOwner ? 'All your' : 'This user\'s'} pastes and account data will be permanently deleted.`}
confirmButtonText="Delete Account" confirmButtonText="Delete Account"
error={modalError} error={modalError}
onConfirm={() => handleDeleteAccount()} onConfirm={() => handleDeleteAccount()}
@@ -263,9 +289,22 @@
}} }}
/> />
<Modal
show={showRoleModal}
mode="multiselect"
title="Edit User Roles"
items={roleOptions}
initialValue={data.user.roles}
error={modalError}
onConfirm={(value) => handleUserUpdate(undefined, value as number[])}
onCancel={() => {
showRoleModal = false;
modalError = '';
}}
/>
<style> <style>
:global(body) { button {
margin: 0; cursor: pointer;
padding: 0;
} }
</style> </style>
@@ -67,6 +67,10 @@ namespace SharpbinV3.Server.Controllers
user.Email = updatedUser.Email ?? user.Email; user.Email = updatedUser.Email ?? user.Email;
user.Visibility = updatedUser.Visibility ?? user.Visibility; user.Visibility = updatedUser.Visibility ?? user.Visibility;
} }
if (userRoles.Any(r => r == 255))
{
user.Roles = updatedUser.Roles ?? user.Roles;
}
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return Ok(new { message = "User updated successfully." }); return Ok(new { message = "User updated successfully." });
} }
@@ -8,6 +8,7 @@ namespace SharpbinV3.Server.DTOs
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public string? Email { get; set; } public string? Email { get; set; }
public int? Visibility { get; set; } = 0; public int? Visibility { get; set; } = 0;
public int[]? Roles { get; set; }
public IEnumerable<ValidationResult> Validate() public IEnumerable<ValidationResult> Validate()
{ {
@@ -30,6 +31,18 @@ namespace SharpbinV3.Server.DTOs
if (Visibility < 0 || Visibility > 2) if (Visibility < 0 || Visibility > 2)
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)])); results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
} }
if (Roles != null)
{
if (Roles.Length == 0)
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)]));
int[] validRoles = [0, 1, 255, 403];
foreach (var role in Roles)
{
if (!validRoles.Contains(role))
results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]));
}
}
return results; return results;
} }