feat(roles, visibility): refactor user roles to use flags and introduce visibility enum

This commit is contained in:
2026-03-10 03:21:13 -04:00
parent 0564d55396
commit 44d7ae8cd3
31 changed files with 732 additions and 175 deletions
@@ -2,7 +2,7 @@
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { page } from '$app/state'; 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 logo from '$lib/assets/favicon.svg';
import type { PageData } from '../../routes/$types'; import type { PageData } from '../../routes/$types';
import { slide } from 'svelte/transition'; import { slide } from 'svelte/transition';
@@ -50,7 +50,7 @@
</div> </div>
{#if $user} {#if $user}
<div class="ml-auto flex items-center space-x-4"> <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 <a
href={resolve('/reports')} href={resolve('/reports')}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a 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 on:click={() => (menuOpen = false)}>Recent Pastes</a
> >
{#if $user} {#if $user}
{#if $user.roles.includes(1) || $user.roles.includes(255)} {#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
<a <a
href={resolve('/reports')} 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" 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"
-7
View File
@@ -211,13 +211,6 @@ export const expiresOptions = [
{ value: 315360000000, label: 'Expire in 10 Years' } { value: 315360000000, label: 'Expire in 10 Years' }
]; ];
export const roles = {
0: 'User',
1: 'Moderator',
255: 'Administrator',
403: 'Banned'
};
export const trustedDomains = [ export const trustedDomains = [
'img.youtube.com', 'img.youtube.com',
'i.ytimg.com', 'i.ytimg.com',
+2 -1
View File
@@ -8,7 +8,8 @@ export interface User {
displayName: string | null; displayName: string | null;
email: string | null; email: string | null;
lastLogin: number | null; lastLogin: number | null;
roles: number[]; roles: number; // bitfield; 5 = User | Admin
isBanned: boolean;
visibility: 0 | 1 | 2; visibility: 0 | 1 | 2;
pastes: Paste[] | null; pastes: Paste[] | null;
pagination: Pagination | null; pagination: Pagination | null;
+13
View File
@@ -2,6 +2,14 @@ import { browser } from '$app/environment';
import type { Cookies } from '@sveltejs/kit'; import type { Cookies } from '@sveltejs/kit';
import { user } from '$lib/stores/user'; 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 TOKEN_KEY = 'token';
const REFRESH_TOKEN_KEY = 'refreshToken'; const REFRESH_TOKEN_KEY = 'refreshToken';
@@ -137,3 +145,8 @@ export function clearServerTokens(cookies: Cookies) {
cookies.delete('token', { path: '/' }); cookies.delete('token', { path: '/' });
cookies.delete('refreshToken', { 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]));
+3 -3
View File
@@ -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; if (!totpEnabled) return false;
const nextHasAdmin = nextRoles.includes(255); const nextHasAdmin = (nextRoles & 4) !== 0;
const alreadyAdmin = currentRoles.includes(255); const alreadyAdmin = (currentRoles & 4) !== 0;
return nextHasAdmin && !alreadyAdmin; return nextHasAdmin && !alreadyAdmin;
} }
+2 -2
View File
@@ -473,7 +473,7 @@
{/if} {/if}
<button <button
type="submit" 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" 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 >Create Paste</button
> >
@@ -485,7 +485,7 @@
{error} {error}
</div> </div>
{/if} {/if}
{#if $user?.roles && $user.roles.includes(403)} {#if $user?.isBanned}
<div <div
transition:fly={{ y: 40, duration: 300 }} transition:fly={{ y: 40, duration: 300 }}
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200" 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 { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '$lib/utils/encryption'; import { decryptAES, encryptAES } from '$lib/utils/encryption';
import { fade } from 'svelte/transition'; 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 { user } from '$lib/stores/user';
import Dropdown from '$lib/components/Dropdown.svelte'; import Dropdown from '$lib/components/Dropdown.svelte';
import { openModal } from '$lib/stores/modal'; import { openModal } from '$lib/stores/modal';
@@ -825,7 +825,7 @@
<span class="text-amber-300">Report</span> <span class="text-amber-300">Report</span>
</button> </button>
{/if} {/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 !editing}
{#if !isBinary} {#if !isBinary}
<button <button
@@ -4,17 +4,19 @@ import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth'; import { getServerToken } from '$lib/utils/auth';
import type { Report } from '$lib/types/report'; import type { Report } from '$lib/types/report';
function decodeJwtRoles(token?: string | null): number[] { function decodeJwtRoles(token?: string | null): number {
try { try {
if (!token) return []; if (!token) return 0;
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()); const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role; const roles = payload?.role;
if (Array.isArray(roles)) { if (typeof roles === 'number') return roles;
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r)); if (typeof roles === 'string') {
const parsed = parseInt(roles, 10);
return isNaN(parsed) ? 0 : parsed;
} }
return []; return 0;
} catch { } catch {
return []; return 0;
} }
} }
@@ -22,7 +24,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
const token = getServerToken(cookies); const token = getServerToken(cookies);
if (!token) throw error(401, 'Login required'); if (!token) throw error(401, 'Login required');
const roles = decodeJwtRoles(token); 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}`, { const res = await fetch(`${apiUrl}/api/report/${params.reportId}`, {
headers: { Authorization: `Bearer ${token}` } headers: { Authorization: `Bearer ${token}` }
@@ -5,17 +5,19 @@ import { getServerToken } from '$lib/utils/auth';
import type { ReportListResponse } from '$lib/types/report'; import type { ReportListResponse } from '$lib/types/report';
import { extractError } from '$lib/utils/misc'; import { extractError } from '$lib/utils/misc';
function decodeJwtRoles(token?: string | null): number[] { function decodeJwtRoles(token?: string | null): number {
try { try {
if (!token) return []; if (!token) return 0;
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()); const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role; const roles = payload?.role;
if (Array.isArray(roles)) { if (typeof roles === 'number') return roles;
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r)); if (typeof roles === 'string') {
const parsed = parseInt(roles, 10);
return isNaN(parsed) ? 0 : parsed;
} }
return []; return 0;
} catch { } catch {
return []; return 0;
} }
} }
@@ -29,7 +31,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
if (!token) throw error(401, 'Login required'); if (!token) throw error(401, 'Login required');
const roles = decodeJwtRoles(token); 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.'); 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 { Pagination } from '$lib/types/pagination';
import type { Report, ReportListResponse } from '$lib/types/report'; import type { Report, ReportListResponse } from '$lib/types/report';
function decodeJwtRoles(token?: string | null): number[] { function decodeJwtRoles(token?: string | null): number {
try { try {
if (!token) return []; if (!token) return 0;
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()); const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role; const roles = payload?.role;
if (Array.isArray(roles)) { if (typeof roles === 'number') return roles;
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r)); if (typeof roles === 'string') {
const parsed = parseInt(roles, 10);
return isNaN(parsed) ? 0 : parsed;
} }
return []; return 0;
} catch { } 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; const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
let reportsTarget: ReportListResponse | null = null; let reportsTarget: ReportListResponse | null = null;
let reportsSubmitted: ReportListResponse | null = null; let reportsSubmitted: ReportListResponse | null = null;
const roles = token ? decodeJwtRoles(token) : []; const roles = token ? decodeJwtRoles(token) : 0;
const canModerate = roles.includes(255) || roles.includes(1); const canModerate = (roles & 4) !== 0 || (roles & 2) !== 0;
if (isOwner && reports && reportsPagination) { if (isOwner && reports && reportsPagination) {
reportsSubmitted = { reportsSubmitted = {
@@ -27,8 +27,7 @@
dateToRelativeString, dateToRelativeString,
extractError extractError
} from '$lib/utils/misc'; } from '$lib/utils/misc';
import { roles } from '$lib/consts'; import { getToken, hasRole, roles } from '$lib/utils/auth';
import { getToken } from '$lib/utils/auth';
import { needsAdminTotp } from '$lib/utils/totp'; import { needsAdminTotp } from '$lib/utils/totp';
import { openModal } from '$lib/stores/modal'; import { openModal } from '$lib/stores/modal';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
@@ -109,7 +108,7 @@
else activeTab = 'pastes'; else activeTab = 'pastes';
break; break;
case 'settings': 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'; activeTab = 'settings';
} else activeTab = 'pastes'; } else activeTab = 'pastes';
break; break;
@@ -123,10 +122,9 @@
} }
const roleOptions = [ const roleOptions = [
{ label: 'Member', value: 0 }, { label: 'Member', value: 1 },
{ label: 'Moderator', value: 1 }, { label: 'Moderator', value: 2 },
{ label: 'Administrator', value: 255 }, { label: 'Administrator', value: 4 }
{ label: 'Banned', value: 403 }
]; ];
async function fetchPage(pageNum: number) { async function fetchPage(pageNum: number) {
@@ -147,11 +145,11 @@
loading = false; loading = false;
} }
async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) { async function handleUserUpdate(displayName?: string, selectedRoles?: number) {
loading = true; loading = true;
modalError = ''; modalError = '';
const token = getToken(); const token = getToken();
const currentRoles = data.user?.roles ?? []; const currentRoles = data.user?.roles ?? 0;
const nextRoles = selectedRoles ?? currentRoles; const nextRoles = selectedRoles ?? currentRoles;
let totpcode = ''; let totpcode = '';
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) { if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
@@ -363,15 +361,22 @@
} }
async function openEditRoles() { 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({ const value = await openModal({
mode: 'multiselect', mode: 'multiselect',
title: 'Edit User Roles', title: 'Edit User Roles',
items: roleOptions, items: roleOptions,
initialValue: data.user?.roles, initialValue: selectedValues,
cancelValue: null cancelValue: null
}); });
if (!Array.isArray(value)) return; 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() { 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"> <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"> <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 <span
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full" 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" /> <User class="h-8 w-8 text-neutral-500" />
<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)} {:else if data.user?.roles && (hasRole(data.user.roles, roles.Admin) || hasRole(data.user.roles, roles.Moderator))}
{#if data.user?.roles?.length} <span
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}> 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" /> <ShieldUser class="h-8 w-8 text-neutral-400" />
</span> </span>
{/if}
{: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" />
@@ -511,7 +520,7 @@
</div> </div>
{/if} {/if}
</div> </div>
{#if !isOwner && !$user?.roles?.some((r) => r === 403)} {#if !isOwner && !$user?.isBanned}
<!-- svelte-ignore a11y_click_events_have_key_events --> <!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div <div
@@ -531,7 +540,7 @@
</div> </div>
{/if} {/if}
<div class="mt-8 flex w-full border-b border-neutral-800"> <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 <button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab === class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'settings' 'settings'
@@ -685,7 +694,7 @@
</div> </div>
{/if} {/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="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="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start"> <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 items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col"> <div class="flex flex-col">
<span class="text-sm font-medium text-neutral-200">User Roles</span> <span class="text-sm font-medium text-neutral-200">User Roles</span>
<span class="text-xs text-neutral-500" <span class="text-xs text-neutral-500">{(() => {
>{data.user?.roles?.length ?? 0} roles assigned</span 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> </div>
<button <button
@@ -857,7 +873,7 @@
</div> </div>
{/if} {/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="col-span-2">
<div class="rounded border border-red-900/30 bg-red-900/10 p-6"> <div class="rounded border border-red-900/30 bg-red-900/10 p-6">
<div class="flex items-start"> <div class="flex items-start">
@@ -32,11 +32,10 @@ namespace SharpbinV3.Server.Authentication
new("username", apiKey.User.Username ?? ""), new("username", apiKey.User.Username ?? ""),
new("displayname", apiKey.User.DisplayName ?? ""), new("displayname", apiKey.User.DisplayName ?? ""),
new("totp_enabled", (apiKey.User.Totp != null).ToString()), new("totp_enabled", (apiKey.User.Totp != null).ToString()),
new("roles", ((int)apiKey.User.Roles).ToString()),
new("is_banned", apiKey.User.IsBanned.ToString()),
}; };
if (apiKey.User.Roles != null)
claims.AddRange(apiKey.User.Roles.Select(r => new Claim(ClaimTypes.Role, r.ToString())));
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey); var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
var principal = new ClaimsPrincipal(identity); var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey); var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
@@ -27,7 +27,7 @@ namespace SharpbinV3.Server.Authorization
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403"); var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true) if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
isBanned = true; isBanned = true;
if (!isBanned) if (!isBanned)
@@ -77,6 +77,7 @@ namespace SharpbinV3.Server.Controllers
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Email = user.Email, Email = user.Email,
Roles = user.Roles, Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility, Visibility = user.Visibility,
LastLogin = user.LastLogin, LastLogin = user.LastLogin,
}, },
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.Paste; using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report; using SharpbinV3.Server.DTOs.Report;
using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.DTOs.User;
@@ -38,7 +39,7 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> CreatePaste( public async Task<IActionResult> CreatePaste(
string title = "", string title = "",
string syntax = "plaintext", string syntax = "plaintext",
int visibility = 0, Visibility visibility = Visibility.Public,
long expiresAt = 0, long expiresAt = 0,
string? verificationToken = null string? verificationToken = null
) )
@@ -85,6 +86,7 @@ namespace SharpbinV3.Server.Controllers
Size = paste.Size, Size = paste.Size,
TrueSize = paste.TrueSize, TrueSize = paste.TrueSize,
ExpiresAt = paste.ExpiresAt, ExpiresAt = paste.ExpiresAt,
Visibility = paste.Visibility,
} }
); );
} }
@@ -100,7 +102,7 @@ namespace SharpbinV3.Server.Controllers
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser();
int? reportCount = null; int? reportCount = null;
if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255)) if (jwtUser != null && (jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator)))
{ {
var query = new ReportQuery { PastePID = paste.PID }; var query = new ReportQuery { PastePID = paste.PID };
reportCount = await _reportService.GetReportCount(query); reportCount = await _reportService.GetReportCount(query);
@@ -135,6 +137,7 @@ namespace SharpbinV3.Server.Controllers
DisplayName = paste.User.DisplayName, DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility, Visibility = paste.User.Visibility,
Roles = paste.User.Roles, Roles = paste.User.Roles,
IsBanned = paste.User.IsBanned,
} }
: null, : null,
}, },
@@ -170,11 +173,9 @@ namespace SharpbinV3.Server.Controllers
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." }); return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _pasteService.EditText(paste, content); bool result = await _pasteService.EditText(paste, content);
if (!result) if (!result)
@@ -193,12 +194,11 @@ namespace SharpbinV3.Server.Controllers
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." }); return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
if (request.Title != null) if (request.Title != null)
paste.Title = request.Title; paste.Title = request.Title;
if (request.Syntax != null) if (request.Syntax != null)
@@ -252,11 +252,9 @@ namespace SharpbinV3.Server.Controllers
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." }); return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _pasteService.Delete(paste); bool result = await _pasteService.Delete(paste);
if (!result) if (!result)
@@ -359,7 +357,7 @@ namespace SharpbinV3.Server.Controllers
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." }); return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
@@ -393,13 +391,10 @@ namespace SharpbinV3.Server.Controllers
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." }); return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _reportService.DeleteReport(report); bool result = await _reportService.DeleteReport(report);
if (!result) if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
@@ -437,6 +432,7 @@ namespace SharpbinV3.Server.Controllers
DisplayName = p.User.DisplayName, DisplayName = p.User.DisplayName,
Visibility = p.User.Visibility, Visibility = p.User.Visibility,
Roles = p.User.Roles, Roles = p.User.Roles,
IsBanned = p.User.IsBanned,
} }
: null, : null,
}) })
@@ -24,7 +24,7 @@ namespace SharpbinV3.Server.Controllers
if (report is null) if (report is null)
return NotFound(new { success = false, message = "Report not found." }); return NotFound(new { success = false, message = "Report not found." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (!hasPrivilegedRole && report.ReporterUUID != user.UUID) if (!hasPrivilegedRole && report.ReporterUUID != user.UUID)
return StatusCode(403, new { success = false, message = "You do not have permission to view this report." }); return StatusCode(403, new { success = false, message = "You do not have permission to view this report." });
@@ -59,7 +59,7 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request) public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
{ {
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255)) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
var report = await reportService.GetReportByID(reportId); var report = await reportService.GetReportByID(reportId);
@@ -127,7 +127,7 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request) public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
{ {
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255)) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." }); return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null }; var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
@@ -157,7 +157,7 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request) public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
{ {
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255)) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to view users." }); return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
var query = request with var query = request with
@@ -200,7 +200,7 @@ namespace SharpbinV3.Server.Controllers
) )
{ {
var user = HttpContext.GetJwtUser()!; var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255)) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
var query = new ReportQuery var query = new ReportQuery
+18 -13
View File
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Paste; using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report; using SharpbinV3.Server.DTOs.Report;
@@ -73,23 +74,23 @@ namespace SharpbinV3.Server.Controllers
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
if ( if (
(user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) (user.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|| (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID) || (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
) )
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." }); return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName; user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self if (jwtUser.Roles.HasFlag(Role.Admin) || user.UUID == jwtUser.UUID) // only admins or self
{ {
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 (jwtUser.Roles.Contains(255)) if (jwtUser.Roles.HasFlag(Role.Admin))
{ {
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled) if (jwtUser.TotpEnabled)
{ {
if ( if (
string.IsNullOrEmpty(updatedUser.TotpCode) string.IsNullOrEmpty(updatedUser.TotpCode)
@@ -99,7 +100,9 @@ namespace SharpbinV3.Server.Controllers
return Unauthorized(new { message = "Invalid TOTP code." }); return Unauthorized(new { message = "Invalid TOTP code." });
} }
} }
user.Roles = updatedUser.Roles ?? user.Roles; user.Roles = updatedUser.Roles ?? user.Roles;
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
} }
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -117,9 +120,9 @@ namespace SharpbinV3.Server.Controllers
if (user == null) if (user == null)
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID) if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." }); return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
if (jwtUser.TotpEnabled) if (jwtUser.TotpEnabled)
@@ -258,7 +261,7 @@ namespace SharpbinV3.Server.Controllers
if (user == null) if (user == null)
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
if (!jwtUser.Roles.Any(r => r == 1 || r == 255)) if (!jwtUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
@@ -292,7 +295,7 @@ namespace SharpbinV3.Server.Controllers
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
var isOwner = user.UUID == jwtUser.UUID; var isOwner = user.UUID == jwtUser.UUID;
var hasPrivilegedRole = jwtUser.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator);
if (!isOwner && !hasPrivilegedRole) if (!isOwner && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
@@ -323,10 +326,10 @@ namespace SharpbinV3.Server.Controllers
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID); var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser) if (!isAuthenticatedUser)
{ {
if (user.Visibility == 2) if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
return NotFound(); return NotFound();
else if (user.Visibility != 1) else if (user.Visibility != Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility == 0); pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
} }
if (page < 1) if (page < 1)
@@ -391,6 +394,7 @@ namespace SharpbinV3.Server.Controllers
EmailVerified = user.EmailVerified, EmailVerified = user.EmailVerified,
LastLogin = user.LastLogin, LastLogin = user.LastLogin,
Roles = user.Roles, Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility, Visibility = user.Visibility,
}, },
Pastes = pastes, Pastes = pastes,
@@ -418,6 +422,7 @@ namespace SharpbinV3.Server.Controllers
CreatedAt = user.CreatedAt, CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Roles = user.Roles, Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility, Visibility = user.Visibility,
}, },
Pastes = pastes, Pastes = pastes,
@@ -1,3 +1,4 @@
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.DTOs.User;
namespace SharpbinV3.Server.DTOs.Paste namespace SharpbinV3.Server.DTOs.Paste
@@ -13,7 +14,7 @@ namespace SharpbinV3.Server.DTOs.Paste
public long TrueSize { get; set; } public long TrueSize { get; set; }
public bool IsCompressed { get; set; } public bool IsCompressed { get; set; }
public int Views { get; set; } public int Views { get; set; }
public int Visibility { get; set; } public Visibility Visibility { get; set; }
public long? EditedAt { get; set; } public long? EditedAt { get; set; }
public long ExpiresAt { get; set; } public long ExpiresAt { get; set; }
public int? ReportCount { get; set; } public int? ReportCount { get; set; }
@@ -29,6 +30,7 @@ namespace SharpbinV3.Server.DTOs.Paste
public long Size { get; set; } public long Size { get; set; }
public long TrueSize { get; set; } public long TrueSize { get; set; }
public long ExpiresAt { get; set; } public long ExpiresAt { get; set; }
public Visibility Visibility { get; set;}
} }
public class PasteOptionsDto public class PasteOptionsDto
@@ -1,10 +1,12 @@
namespace SharpbinV3.Server.DTOs.Paste using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs.Paste
{ {
public class UpdatePasteDto public class UpdatePasteDto
{ {
public string? Title { get; set; } public string? Title { get; set; }
public string? Syntax { get; set; } public string? Syntax { get; set; }
public int? Visibility { get; set; } public Visibility? Visibility { get; set; }
public long? ExpiresAt { get; set; } public long? ExpiresAt { get; set; }
} }
} }
+10 -13
View File
@@ -1,5 +1,7 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs
{ {
@@ -7,8 +9,9 @@ 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 Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
public int[]? Roles { get; set; } public Role? Roles { get; set; }
public bool? IsBanned { get; set; }
public string? TotpCode { get; set; } public string? TotpCode { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
@@ -34,19 +37,13 @@ namespace SharpbinV3.Server.DTOs
} }
if (Visibility != null && Visibility.HasValue) if (Visibility != null && Visibility.HasValue)
{ {
if (Visibility < 0 || Visibility > 2) if (!Enum.IsDefined(typeof(Visibility), Visibility.Value))
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)])); results.Add(new ValidationResult($"Invalid visibility: {Visibility.Value}.", [nameof(Visibility)]));
} }
if (Roles != null && Roles.Length > 0) if (Roles != null && Roles.HasValue)
{ {
if (Roles.Length == 0) if (!Enum.IsDefined(typeof(Role), Roles.Value))
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)])); results.Add(new ValidationResult($"Invalid role: {Roles.Value}.", [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;
} }
@@ -1,3 +1,6 @@
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs.User namespace SharpbinV3.Server.DTOs.User
{ {
public class UserSimpleDto public class UserSimpleDto
@@ -7,8 +10,9 @@ namespace SharpbinV3.Server.DTOs.User
public long CreatedAt { get; set; } public long CreatedAt { get; set; }
public string Username { get; set; } = string.Empty; public string Username { get; set; } = string.Empty;
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public int[] Roles { get; set; } = []; public Role Roles { get; set; } = Role.User;
public int Visibility { get; set; } public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; }
} }
public class UserResponseDto : UserSimpleDto public class UserResponseDto : UserSimpleDto
+2 -1
View File
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities namespace SharpbinV3.Server.Data.Entities
@@ -33,7 +34,7 @@ namespace SharpbinV3.Server.Data.Entities
public int Views { get; set; } public int Views { get; set; }
public string? Syntax { get; set; } public string? Syntax { get; set; }
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private (encrypted pastes handled on frontend) public Visibility Visibility { get; set; } = Visibility.Public;
public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never
+14 -2
View File
@@ -1,8 +1,18 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities namespace SharpbinV3.Server.Data.Entities
{ {
[Flags]
public enum Role
{
User = 1,
Moderator = 2,
Admin = 4
}
[Index(nameof(UID))] [Index(nameof(UID))]
[Index(nameof(UUID), IsUnique = true)] [Index(nameof(UUID), IsUnique = true)]
public sealed class User public sealed class User
@@ -20,8 +30,10 @@ namespace SharpbinV3.Server.Data.Entities
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public long? LastLogin { get; set; } public long? LastLogin { get; set; }
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin public Role Roles { get; set; } = Role.User;
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; } = Visibility.Public;
public List<Paste> Pastes { get; set; } = []; public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = []; public List<RefreshToken> RefreshTokens { get; set; } = [];
public List<Report> Reports { get; set; } = []; public List<Report> Reports { get; set; } = [];
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Data.Enums
{
public enum Visibility
{
Public = 0,
Unlisted = 1,
Private = 2
}
}
@@ -63,8 +63,12 @@ namespace SharpbinV3.Server.Extensions
var username = claims.FirstOrDefault(c => c.Type == "username")?.Value ?? ""; var username = claims.FirstOrDefault(c => c.Type == "username")?.Value ?? "";
var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? ""; var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? "";
var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True"; var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True";
var isBanned = claims.FirstOrDefault(c => c.Type == "is_banned")?.Value == "True";
var roles = claims.Where(c => c.Type == ClaimTypes.Role).Select(c => int.TryParse(c.Value, out var r) ? r : 0).ToArray(); Role roles = claims.FirstOrDefault(c => c.Type == "roles")?.Value switch
{
string r when int.TryParse(r, out var roleInt) => (Role)roleInt,
_ => Role.User,
};
var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value; var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
var expires = var expires =
@@ -78,7 +82,8 @@ namespace SharpbinV3.Server.Extensions
Username = username, Username = username,
DisplayName = displayName, DisplayName = displayName,
TotpEnabled = totpEnabled, TotpEnabled = totpEnabled,
Roles = roles.Length > 0 ? roles : [0], Roles = roles,
IsBanned = isBanned,
Expires = expires, Expires = expires,
}; };
} }
@@ -0,0 +1,455 @@
// <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("20260310055909_FlaggedRolesEnumVisiblity")]
partial class FlaggedRolesEnumVisiblity
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.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>("CreatedAt")
.HasColumnType("INTEGER");
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("Size");
b.HasIndex("Syntax");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<int?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
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.Enums.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Enums.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class FlaggedRolesEnumVisiblity : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "Roles",
table: "Users",
type: "INTEGER",
nullable: false,
oldClrType: typeof(string),
oldType: "TEXT");
migrationBuilder.AddColumn<bool>(
name: "IsBanned",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsBanned",
table: "Users");
migrationBuilder.AlterColumn<string>(
name: "Roles",
table: "Users",
type: "TEXT",
nullable: false,
oldClrType: typeof(int),
oldType: "INTEGER");
}
}
}
@@ -15,9 +15,9 @@ namespace SharpbinV3.Server.Migrations
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.ApiKey", b =>
{ {
b.Property<Guid>("UUID") b.Property<Guid>("UUID")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -47,7 +47,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("ApiKeys"); b.ToTable("ApiKeys");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
{ {
b.Property<Guid>("UUID") b.Property<Guid>("UUID")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -79,7 +79,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("EmailVerificationTokens"); b.ToTable("EmailVerificationTokens");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{ {
b.Property<int>("PID") b.Property<int>("PID")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -154,7 +154,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Pastes"); b.ToTable("Pastes");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -179,7 +179,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("PasteViews"); b.ToTable("PasteViews");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -225,7 +225,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("RefreshTokens"); b.ToTable("RefreshTokens");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
{ {
b.Property<int>("ReportID") b.Property<int>("ReportID")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -275,7 +275,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Reports"); b.ToTable("Reports");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{ {
b.Property<Guid>("UUID") b.Property<Guid>("UUID")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -293,6 +293,9 @@ namespace SharpbinV3.Server.Migrations
b.Property<bool>("EmailVerified") b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin") b.Property<long?>("LastLogin")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -300,9 +303,8 @@ namespace SharpbinV3.Server.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles") b.Property<int>("Roles")
.IsRequired() .HasColumnType("INTEGER");
.HasColumnType("TEXT");
b.Property<int?>("UID") b.Property<int?>("UID")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -324,7 +326,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Users"); b.ToTable("Users");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
{ {
b.Property<Guid>("UserUUID") b.Property<Guid>("UserUUID")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -341,9 +343,9 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("UserTotps"); b.ToTable("UserTotps");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.ApiKey", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("ApiKeys") .WithMany("ApiKeys")
.HasForeignKey("UserUUID") .HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -352,9 +354,9 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("EmailVerificationTokens") .WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID") .HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -363,9 +365,9 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Pastes") .WithMany("Pastes")
.HasForeignKey("AuthorUUID") .HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
@@ -373,9 +375,9 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
.WithMany("PasteViews") .WithMany("PasteViews")
.HasForeignKey("PastePID") .HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -384,9 +386,9 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("Paste"); b.Navigation("Paste");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("RefreshTokens") .WithMany("RefreshTokens")
.HasForeignKey("UserUUID") .HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -395,14 +397,14 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
.WithMany("Reports") .WithMany("Reports")
.HasForeignKey("PastePID") .HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Reports") .WithMany("Reports")
.HasForeignKey("UserUUID") .HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
@@ -412,25 +414,25 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithOne("Totp") .WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") .HasForeignKey("SharpbinV3.Server.Data.Enums.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{ {
b.Navigation("PasteViews"); b.Navigation("PasteViews");
b.Navigation("Reports"); b.Navigation("Reports");
}); });
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{ {
b.Navigation("ApiKeys"); b.Navigation("ApiKeys");
+5 -12
View File
@@ -19,7 +19,8 @@ namespace SharpbinV3.Server.Services
public string Username { get; set; } = string.Empty; public string Username { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty;
public bool TotpEnabled { get; set; } public bool TotpEnabled { get; set; }
public int[] Roles { get; set; } = []; public Role Roles { get; set; }
public bool IsBanned { get; set; }
public DateTime Expires { get; set; } public DateTime Expires { get; set; }
} }
@@ -54,7 +55,7 @@ namespace SharpbinV3.Server.Services
}; };
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync()) if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
user.Roles = [0, 1, 255]; user.Roles = Role.User | Role.Admin;
_db.Users.Add(user); _db.Users.Add(user);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -73,19 +74,11 @@ namespace SharpbinV3.Server.Services
new("username", user.Username), new("username", user.Username),
new("displayname", user.DisplayName ?? ""), new("displayname", user.DisplayName ?? ""),
new("totp_enabled", totpEnabled.ToString()), new("totp_enabled", totpEnabled.ToString()),
new("roles", ((int)user.Roles).ToString()),
new("is_banned", user.IsBanned.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().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 var descriptor = new SecurityTokenDescriptor
{ {
Subject = new ClaimsIdentity(claims), Subject = new ClaimsIdentity(claims),
+4 -3
View File
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
@@ -23,7 +24,7 @@ namespace SharpbinV3.Server.Services
string content, string content,
string title, string title,
string syntax, string syntax,
int visibility, Visibility visibility,
long expiresAt, long expiresAt,
bool shouldCompress bool shouldCompress
) )
@@ -198,9 +199,9 @@ namespace SharpbinV3.Server.Services
return title.Length <= _pasteSettings.MaxTitleLength; return title.Length <= _pasteSettings.MaxTitleLength;
} }
public bool ValidateVisibility(int visibility) public bool ValidateVisibility(Visibility visibility)
{ {
return visibility >= 0 && visibility <= 2; return Enum.IsDefined(typeof(Visibility), visibility);
} }
public bool ValidateExpiresAt(long expiresAt) public bool ValidateExpiresAt(long expiresAt)
@@ -8,8 +8,7 @@
} }
}, },
"AuthSettings": { "AuthSettings": {
"CF_Turnstile_SiteKey": "3x00000000000000000000FF", "First_User_Admin": true,
"CF_Turnstile_SecretKey": "1x0000000000000000000000000000000AA",
"Admins_Require_2FA": false "Admins_Require_2FA": false
}, },
"JwtSettings": { "JwtSettings": {