mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
feat(roles, visibility): refactor user roles to use flags and introduce visibility enum
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
import { user } from '$lib/stores/user';
|
||||
import { resolve } from '$app/paths';
|
||||
import { page } from '$app/state';
|
||||
import { clearTokens } from '$lib/utils/auth';
|
||||
import { clearTokens, hasRole } from '$lib/utils/auth';
|
||||
import logo from '$lib/assets/favicon.svg';
|
||||
import type { PageData } from '../../routes/$types';
|
||||
import { slide } from 'svelte/transition';
|
||||
@@ -50,7 +50,7 @@
|
||||
</div>
|
||||
{#if $user}
|
||||
<div class="ml-auto flex items-center space-x-4">
|
||||
{#if $user.roles.includes(1) || $user.roles.includes(255)}
|
||||
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||
<a
|
||||
href={resolve('/reports')}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a
|
||||
@@ -116,7 +116,7 @@
|
||||
on:click={() => (menuOpen = false)}>Recent Pastes</a
|
||||
>
|
||||
{#if $user}
|
||||
{#if $user.roles.includes(1) || $user.roles.includes(255)}
|
||||
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||
<a
|
||||
href={resolve('/reports')}
|
||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
|
||||
@@ -211,13 +211,6 @@ export const expiresOptions = [
|
||||
{ value: 315360000000, label: 'Expire in 10 Years' }
|
||||
];
|
||||
|
||||
export const roles = {
|
||||
0: 'User',
|
||||
1: 'Moderator',
|
||||
255: 'Administrator',
|
||||
403: 'Banned'
|
||||
};
|
||||
|
||||
export const trustedDomains = [
|
||||
'img.youtube.com',
|
||||
'i.ytimg.com',
|
||||
@@ -249,4 +242,4 @@ export const trustedDomains = [
|
||||
'cloudflare-ipfs.com',
|
||||
|
||||
'upload.wikimedia.org'
|
||||
];
|
||||
];
|
||||
@@ -8,7 +8,8 @@ export interface User {
|
||||
displayName: string | null;
|
||||
email: string | null;
|
||||
lastLogin: number | null;
|
||||
roles: number[];
|
||||
roles: number; // bitfield; 5 = User | Admin
|
||||
isBanned: boolean;
|
||||
visibility: 0 | 1 | 2;
|
||||
pastes: Paste[] | null;
|
||||
pagination: Pagination | null;
|
||||
|
||||
@@ -2,6 +2,14 @@ import { browser } from '$app/environment';
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import { user } from '$lib/stores/user';
|
||||
|
||||
export const roles = {
|
||||
User: 1,
|
||||
Moderator: 2,
|
||||
Admin: 4
|
||||
} as const;
|
||||
|
||||
export type Role = keyof typeof roles;
|
||||
|
||||
const TOKEN_KEY = 'token';
|
||||
const REFRESH_TOKEN_KEY = 'refreshToken';
|
||||
|
||||
@@ -137,3 +145,8 @@ export function clearServerTokens(cookies: Cookies) {
|
||||
cookies.delete('token', { path: '/' });
|
||||
cookies.delete('refreshToken', { path: '/' });
|
||||
}
|
||||
|
||||
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
|
||||
|
||||
export const getUserRoles = (userRoles: number): Role[] =>
|
||||
(Object.keys(roles) as Role[]).filter((role) => hasRole(userRoles, roles[role]));
|
||||
|
||||
@@ -10,9 +10,9 @@ export function parseTotpEnabled(tokenValue: string | null) {
|
||||
}
|
||||
}
|
||||
|
||||
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) {
|
||||
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number, nextRoles: number) {
|
||||
if (!totpEnabled) return false;
|
||||
const nextHasAdmin = nextRoles.includes(255);
|
||||
const alreadyAdmin = currentRoles.includes(255);
|
||||
const nextHasAdmin = (nextRoles & 4) !== 0;
|
||||
const alreadyAdmin = (currentRoles & 4) !== 0;
|
||||
return nextHasAdmin && !alreadyAdmin;
|
||||
}
|
||||
|
||||
@@ -473,7 +473,7 @@
|
||||
{/if}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={$user?.roles && $user.roles.includes(403)}
|
||||
disabled={$user?.isBanned}
|
||||
class="mb-2 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 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
|
||||
>Create Paste</button
|
||||
>
|
||||
@@ -485,7 +485,7 @@
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
{#if $user?.roles && $user.roles.includes(403)}
|
||||
{#if $user?.isBanned}
|
||||
<div
|
||||
transition:fly={{ y: 40, duration: 300 }}
|
||||
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
import { resolve } from '$app/paths';
|
||||
import { decryptAES, encryptAES } from '$lib/utils/encryption';
|
||||
import { fade } from 'svelte/transition';
|
||||
import { getToken } from '$lib/utils/auth';
|
||||
import { getToken, hasRole } from '$lib/utils/auth';
|
||||
import { user } from '$lib/stores/user';
|
||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
@@ -825,7 +825,7 @@
|
||||
<span class="text-amber-300">Report</span>
|
||||
</button>
|
||||
{/if}
|
||||
{#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))}
|
||||
{#if $user && ($user.uuid === data.paste?.author?.uuid || hasRole($user.roles, 2) || hasRole($user.roles, 4))}
|
||||
{#if !editing}
|
||||
{#if !isBinary}
|
||||
<button
|
||||
|
||||
@@ -4,17 +4,19 @@ import { apiUrl } from '$lib/server/api';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import type { Report } from '$lib/types/report';
|
||||
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
function decodeJwtRoles(token?: string | null): number {
|
||||
try {
|
||||
if (!token) return [];
|
||||
if (!token) return 0;
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const roles = payload?.role;
|
||||
if (Array.isArray(roles)) {
|
||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
||||
if (typeof roles === 'number') return roles;
|
||||
if (typeof roles === 'string') {
|
||||
const parsed = parseInt(roles, 10);
|
||||
return isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
return [];
|
||||
return 0;
|
||||
} catch {
|
||||
return [];
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +24,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
|
||||
const token = getServerToken(cookies);
|
||||
if (!token) throw error(401, 'Login required');
|
||||
const roles = decodeJwtRoles(token);
|
||||
const canEdit = roles.includes(1) || roles.includes(255);
|
||||
const canEdit = (roles & 2) !== 0 || (roles & 4) !== 0;
|
||||
|
||||
const res = await fetch(`${apiUrl}/api/report/${params.reportId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
|
||||
@@ -5,17 +5,19 @@ import { getServerToken } from '$lib/utils/auth';
|
||||
import type { ReportListResponse } from '$lib/types/report';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
function decodeJwtRoles(token?: string | null): number {
|
||||
try {
|
||||
if (!token) return [];
|
||||
if (!token) return 0;
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const roles = payload?.role;
|
||||
if (Array.isArray(roles)) {
|
||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
||||
if (typeof roles === 'number') return roles;
|
||||
if (typeof roles === 'string') {
|
||||
const parsed = parseInt(roles, 10);
|
||||
return isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
return [];
|
||||
return 0;
|
||||
} catch {
|
||||
return [];
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +31,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
||||
if (!token) throw error(401, 'Login required');
|
||||
|
||||
const roles = decodeJwtRoles(token);
|
||||
if (!roles.includes(1) && !roles.includes(255)) {
|
||||
if ((roles & 2) === 0 && (roles & 4) === 0) {
|
||||
throw error(403, 'You do not have permission to view reports.');
|
||||
}
|
||||
|
||||
|
||||
@@ -7,17 +7,19 @@ import type { Paste } from '$lib/types/paste';
|
||||
import type { Pagination } from '$lib/types/pagination';
|
||||
import type { Report, ReportListResponse } from '$lib/types/report';
|
||||
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
function decodeJwtRoles(token?: string | null): number {
|
||||
try {
|
||||
if (!token) return [];
|
||||
if (!token) return 0;
|
||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||
const roles = payload?.role;
|
||||
if (Array.isArray(roles)) {
|
||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
||||
if (typeof roles === 'number') return roles;
|
||||
if (typeof roles === 'string') {
|
||||
const parsed = parseInt(roles, 10);
|
||||
return isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
return [];
|
||||
return 0;
|
||||
} catch {
|
||||
return [];
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,8 +60,8 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
|
||||
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
|
||||
let reportsTarget: ReportListResponse | null = null;
|
||||
let reportsSubmitted: ReportListResponse | null = null;
|
||||
const roles = token ? decodeJwtRoles(token) : [];
|
||||
const canModerate = roles.includes(255) || roles.includes(1);
|
||||
const roles = token ? decodeJwtRoles(token) : 0;
|
||||
const canModerate = (roles & 4) !== 0 || (roles & 2) !== 0;
|
||||
|
||||
if (isOwner && reports && reportsPagination) {
|
||||
reportsSubmitted = {
|
||||
|
||||
@@ -27,8 +27,7 @@
|
||||
dateToRelativeString,
|
||||
extractError
|
||||
} from '$lib/utils/misc';
|
||||
import { roles } from '$lib/consts';
|
||||
import { getToken } from '$lib/utils/auth';
|
||||
import { getToken, hasRole, roles } from '$lib/utils/auth';
|
||||
import { needsAdminTotp } from '$lib/utils/totp';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
import { user } from '$lib/stores/user';
|
||||
@@ -109,7 +108,7 @@
|
||||
else activeTab = 'pastes';
|
||||
break;
|
||||
case 'settings':
|
||||
if (isOwner || $user?.roles?.some((r) => r === 255 || r === 1)) {
|
||||
if (isOwner || ($user?.roles && (hasRole($user.roles, 2) || hasRole($user.roles, 4)))) {
|
||||
activeTab = 'settings';
|
||||
} else activeTab = 'pastes';
|
||||
break;
|
||||
@@ -123,10 +122,9 @@
|
||||
}
|
||||
|
||||
const roleOptions = [
|
||||
{ label: 'Member', value: 0 },
|
||||
{ label: 'Moderator', value: 1 },
|
||||
{ label: 'Administrator', value: 255 },
|
||||
{ label: 'Banned', value: 403 }
|
||||
{ label: 'Member', value: 1 },
|
||||
{ label: 'Moderator', value: 2 },
|
||||
{ label: 'Administrator', value: 4 }
|
||||
];
|
||||
|
||||
async function fetchPage(pageNum: number) {
|
||||
@@ -147,11 +145,11 @@
|
||||
loading = false;
|
||||
}
|
||||
|
||||
async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) {
|
||||
async function handleUserUpdate(displayName?: string, selectedRoles?: number) {
|
||||
loading = true;
|
||||
modalError = '';
|
||||
const token = getToken();
|
||||
const currentRoles = data.user?.roles ?? [];
|
||||
const currentRoles = data.user?.roles ?? 0;
|
||||
const nextRoles = selectedRoles ?? currentRoles;
|
||||
let totpcode = '';
|
||||
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
|
||||
@@ -363,15 +361,22 @@
|
||||
}
|
||||
|
||||
async function openEditRoles() {
|
||||
const currentRoleBitfield = data.user?.roles ?? 0;
|
||||
const selectedValues: number[] = [];
|
||||
if (hasRole(currentRoleBitfield, roles.User)) selectedValues.push(roles.User);
|
||||
if (hasRole(currentRoleBitfield, roles.Moderator)) selectedValues.push(roles.Moderator);
|
||||
if (hasRole(currentRoleBitfield, roles.Admin)) selectedValues.push(roles.Admin);
|
||||
|
||||
const value = await openModal({
|
||||
mode: 'multiselect',
|
||||
title: 'Edit User Roles',
|
||||
items: roleOptions,
|
||||
initialValue: data.user?.roles,
|
||||
initialValue: selectedValues,
|
||||
cancelValue: null
|
||||
});
|
||||
if (!Array.isArray(value)) return;
|
||||
await handleUserUpdate(undefined, value as number[]);
|
||||
const bitfield = value.reduce((acc, val) => acc | val, 0);
|
||||
await handleUserUpdate(undefined, bitfield);
|
||||
}
|
||||
|
||||
async function openDeleteAccount() {
|
||||
@@ -450,20 +455,24 @@
|
||||
>
|
||||
<div class="relative w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||
<h1 class="flex flex-wrap items-center justify-center gap-4 text-center text-4xl font-bold">
|
||||
{#if data.user?.roles?.includes(403)}
|
||||
{#if data.user?.isBanned}
|
||||
<span
|
||||
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
|
||||
use:tooltip={roles[403]}
|
||||
use:tooltip={'Banned'}
|
||||
>
|
||||
<User class="h-8 w-8 text-neutral-500" />
|
||||
<Ban class="absolute h-7 w-7 text-red-500" />
|
||||
</span>
|
||||
{:else if data.user?.roles?.includes(1) || data.user?.roles?.includes(255)}
|
||||
{#if data.user?.roles?.length}
|
||||
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
|
||||
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
||||
</span>
|
||||
{/if}
|
||||
{:else if data.user?.roles && (hasRole(data.user.roles, roles.Admin) || hasRole(data.user.roles, roles.Moderator))}
|
||||
<span
|
||||
use:tooltip={hasRole(data.user.roles, roles.Admin)
|
||||
? 'Admin'
|
||||
: hasRole(data.user.roles, roles.Moderator)
|
||||
? 'Moderator'
|
||||
: 'User'}
|
||||
>
|
||||
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
||||
</span>
|
||||
{:else}
|
||||
<span use:tooltip={'User'}>
|
||||
<User class="h-8 w-8 text-neutral-400" />
|
||||
@@ -511,7 +520,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if !isOwner && !$user?.roles?.some((r) => r === 403)}
|
||||
{#if !isOwner && !$user?.isBanned}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
@@ -531,7 +540,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
<div class="mt-8 flex w-full border-b border-neutral-800">
|
||||
{#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)}
|
||||
{#if isOwner || ($user?.roles && (hasRole($user.roles, roles.Admin) || hasRole($user.roles, roles.Moderator)))}
|
||||
<button
|
||||
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
|
||||
'settings'
|
||||
@@ -685,7 +694,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if $user?.roles?.some((r) => r === 255)}
|
||||
{#if $user?.roles && hasRole($user.roles, roles.Admin)}
|
||||
<div class="col-span-2 {isOwner ? 'md:col-span-1' : ''}">
|
||||
<div class="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
|
||||
<div class="mb-6 flex items-start">
|
||||
@@ -698,8 +707,15 @@
|
||||
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
|
||||
<div class="flex flex-col">
|
||||
<span class="text-sm font-medium text-neutral-200">User Roles</span>
|
||||
<span class="text-xs text-neutral-500"
|
||||
>{data.user?.roles?.length ?? 0} roles assigned</span
|
||||
<span class="text-xs text-neutral-500">{(() => {
|
||||
let count = 0;
|
||||
if (data.user?.roles) {
|
||||
if (hasRole(data.user.roles, roles.User)) count++;
|
||||
if (hasRole(data.user.roles, roles.Moderator)) count++;
|
||||
if (hasRole(data.user.roles, roles.Admin)) count++;
|
||||
}
|
||||
return count;
|
||||
})()} roles assigned</span
|
||||
>
|
||||
</div>
|
||||
<button
|
||||
@@ -857,7 +873,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if isOwner || $user?.roles?.some((r) => r === 255)}
|
||||
{#if isOwner || ($user?.roles && hasRole($user.roles, roles.Admin))}
|
||||
<div class="col-span-2">
|
||||
<div class="rounded border border-red-900/30 bg-red-900/10 p-6">
|
||||
<div class="flex items-start">
|
||||
|
||||
Reference in New Issue
Block a user