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 { 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"
-7
View File
@@ -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',
+2 -1
View File
@@ -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;
+13
View File
@@ -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]));
+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;
const nextHasAdmin = nextRoles.includes(255);
const alreadyAdmin = currentRoles.includes(255);
const nextHasAdmin = (nextRoles & 4) !== 0;
const alreadyAdmin = (currentRoles & 4) !== 0;
return nextHasAdmin && !alreadyAdmin;
}
+2 -2
View File
@@ -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">
@@ -32,11 +32,10 @@ namespace SharpbinV3.Server.Authentication
new("username", apiKey.User.Username ?? ""),
new("displayname", apiKey.User.DisplayName ?? ""),
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 principal = new ClaimsPrincipal(identity);
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");
if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true)
if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
isBanned = true;
if (!isBanned)
@@ -77,6 +77,7 @@ namespace SharpbinV3.Server.Controllers
DisplayName = user.DisplayName,
Email = user.Email,
Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility,
LastLogin = user.LastLogin,
},
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report;
using SharpbinV3.Server.DTOs.User;
@@ -38,7 +39,7 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> CreatePaste(
string title = "",
string syntax = "plaintext",
int visibility = 0,
Visibility visibility = Visibility.Public,
long expiresAt = 0,
string? verificationToken = null
)
@@ -85,6 +86,7 @@ namespace SharpbinV3.Server.Controllers
Size = paste.Size,
TrueSize = paste.TrueSize,
ExpiresAt = paste.ExpiresAt,
Visibility = paste.Visibility,
}
);
}
@@ -100,7 +102,7 @@ namespace SharpbinV3.Server.Controllers
var jwtUser = HttpContext.GetJwtUser();
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 };
reportCount = await _reportService.GetReportCount(query);
@@ -135,6 +137,7 @@ namespace SharpbinV3.Server.Controllers
DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility,
Roles = paste.User.Roles,
IsBanned = paste.User.IsBanned,
}
: null,
},
@@ -170,11 +173,9 @@ namespace SharpbinV3.Server.Controllers
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)
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);
if (!result)
@@ -193,12 +194,11 @@ namespace SharpbinV3.Server.Controllers
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)
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)
paste.Title = request.Title;
if (request.Syntax != null)
@@ -252,11 +252,9 @@ namespace SharpbinV3.Server.Controllers
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)
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);
if (!result)
@@ -359,7 +357,7 @@ namespace SharpbinV3.Server.Controllers
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)
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 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)
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);
if (!result)
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,
Visibility = p.User.Visibility,
Roles = p.User.Roles,
IsBanned = p.User.IsBanned,
}
: null,
})
@@ -24,7 +24,7 @@ namespace SharpbinV3.Server.Controllers
if (report is null)
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)
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)
{
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." });
var report = await reportService.GetReportByID(reportId);
@@ -127,7 +127,7 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
{
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." });
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)
{
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." });
var query = request with
@@ -200,7 +200,7 @@ namespace SharpbinV3.Server.Controllers
)
{
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." });
var query = new ReportQuery
+18 -13
View File
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report;
@@ -73,23 +74,23 @@ namespace SharpbinV3.Server.Controllers
return NotFound(new { success = false, message = "User not found." });
if (
(user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|| (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)
(user.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|| (!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." });
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." });
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.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 (
string.IsNullOrEmpty(updatedUser.TotpCode)
@@ -99,7 +100,9 @@ namespace SharpbinV3.Server.Controllers
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
user.Roles = updatedUser.Roles ?? user.Roles;
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
}
await _db.SaveChangesAsync();
@@ -117,9 +120,9 @@ namespace SharpbinV3.Server.Controllers
if (user == null)
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." });
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." });
if (jwtUser.TotpEnabled)
@@ -258,7 +261,7 @@ namespace SharpbinV3.Server.Controllers
if (user == null)
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." });
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." });
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)
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);
if (!isAuthenticatedUser)
{
if (user.Visibility == 2)
if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
return NotFound();
else if (user.Visibility != 1)
pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
else if (user.Visibility != Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
}
if (page < 1)
@@ -391,6 +394,7 @@ namespace SharpbinV3.Server.Controllers
EmailVerified = user.EmailVerified,
LastLogin = user.LastLogin,
Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility,
},
Pastes = pastes,
@@ -418,6 +422,7 @@ namespace SharpbinV3.Server.Controllers
CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName,
Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility,
},
Pastes = pastes,
@@ -1,3 +1,4 @@
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.User;
namespace SharpbinV3.Server.DTOs.Paste
@@ -13,7 +14,7 @@ namespace SharpbinV3.Server.DTOs.Paste
public long TrueSize { get; set; }
public bool IsCompressed { get; set; }
public int Views { get; set; }
public int Visibility { get; set; }
public Visibility Visibility { get; set; }
public long? EditedAt { get; set; }
public long ExpiresAt { get; set; }
public int? ReportCount { get; set; }
@@ -29,6 +30,7 @@ namespace SharpbinV3.Server.DTOs.Paste
public long Size { get; set; }
public long TrueSize { get; set; }
public long ExpiresAt { get; set; }
public Visibility Visibility { get; set;}
}
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 string? Title { get; set; }
public string? Syntax { get; set; }
public int? Visibility { get; set; }
public Visibility? Visibility { get; set; }
public long? ExpiresAt { get; set; }
}
}
+10 -13
View File
@@ -1,5 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs
{
@@ -7,8 +9,9 @@ namespace SharpbinV3.Server.DTOs
{
public string? DisplayName { get; set; }
public string? Email { get; set; }
public int? Visibility { get; set; } = 0;
public int[]? Roles { get; set; }
public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
public Role? Roles { get; set; }
public bool? IsBanned { get; set; }
public string? TotpCode { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
@@ -34,19 +37,13 @@ namespace SharpbinV3.Server.DTOs
}
if (Visibility != null && Visibility.HasValue)
{
if (Visibility < 0 || Visibility > 2)
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
if (!Enum.IsDefined(typeof(Visibility), Visibility.Value))
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)
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)]));
}
if (!Enum.IsDefined(typeof(Role), Roles.Value))
results.Add(new ValidationResult($"Invalid role: {Roles.Value}.", [nameof(Roles)]));
}
return results;
}
@@ -1,3 +1,6 @@
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs.User
{
public class UserSimpleDto
@@ -7,8 +10,9 @@ namespace SharpbinV3.Server.DTOs.User
public long CreatedAt { get; set; }
public string Username { get; set; } = string.Empty;
public string? DisplayName { get; set; }
public int[] Roles { get; set; } = [];
public int Visibility { get; set; }
public Role Roles { get; set; } = Role.User;
public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; }
}
public class UserResponseDto : UserSimpleDto
+2 -1
View File
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
@@ -33,7 +34,7 @@ namespace SharpbinV3.Server.Data.Entities
public int Views { 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
+14 -2
View File
@@ -1,8 +1,18 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
[Flags]
public enum Role
{
User = 1,
Moderator = 2,
Admin = 4
}
[Index(nameof(UID))]
[Index(nameof(UUID), IsUnique = true)]
public sealed class User
@@ -20,8 +30,10 @@ namespace SharpbinV3.Server.Data.Entities
public string? DisplayName { get; set; }
public long? LastLogin { get; set; }
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public Role Roles { get; set; } = Role.User;
public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; } = Visibility.Public;
public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { 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 displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? "";
var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True";
var roles = claims.Where(c => c.Type == ClaimTypes.Role).Select(c => int.TryParse(c.Value, out var r) ? r : 0).ToArray();
var isBanned = claims.FirstOrDefault(c => c.Type == "is_banned")?.Value == "True";
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 expires =
@@ -78,7 +82,8 @@ namespace SharpbinV3.Server.Extensions
Username = username,
DisplayName = displayName,
TotpEnabled = totpEnabled,
Roles = roles.Length > 0 ? roles : [0],
Roles = roles,
IsBanned = isBanned,
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)
{
#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")
.ValueGeneratedOnAdd()
@@ -47,7 +47,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
@@ -79,7 +79,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
@@ -154,7 +154,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -179,7 +179,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@@ -225,7 +225,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
@@ -275,7 +275,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
@@ -293,6 +293,9 @@ namespace SharpbinV3.Server.Migrations
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
@@ -300,9 +303,8 @@ namespace SharpbinV3.Server.Migrations
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<int?>("UID")
.HasColumnType("INTEGER");
@@ -324,7 +326,7 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
@@ -341,9 +343,9 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
@@ -352,9 +354,9 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
@@ -363,9 +365,9 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
@@ -373,9 +375,9 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
@@ -384,9 +386,9 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
@@ -395,14 +397,14 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
@@ -412,25 +414,25 @@ namespace SharpbinV3.Server.Migrations
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")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.HasForeignKey("SharpbinV3.Server.Data.Enums.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{
b.Navigation("ApiKeys");
+5 -12
View File
@@ -19,7 +19,8 @@ namespace SharpbinV3.Server.Services
public string Username { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty;
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; }
}
@@ -54,7 +55,7 @@ namespace SharpbinV3.Server.Services
};
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
user.Roles = [0, 1, 255];
user.Roles = Role.User | Role.Admin;
_db.Users.Add(user);
await _db.SaveChangesAsync();
@@ -73,19 +74,11 @@ namespace SharpbinV3.Server.Services
new("username", user.Username),
new("displayname", user.DisplayName ?? ""),
new("totp_enabled", totpEnabled.ToString()),
new("roles", ((int)user.Roles).ToString()),
new("is_banned", user.IsBanned.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
if (user.Roles != null)
{
foreach (var role in user.Roles)
claims.Add(new Claim(ClaimTypes.Role, role.ToString()));
}
else
{
claims.Add(new Claim(ClaimTypes.Role, "0"));
}
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
+4 -3
View File
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings;
@@ -23,7 +24,7 @@ namespace SharpbinV3.Server.Services
string content,
string title,
string syntax,
int visibility,
Visibility visibility,
long expiresAt,
bool shouldCompress
)
@@ -198,9 +199,9 @@ namespace SharpbinV3.Server.Services
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)
@@ -8,8 +8,7 @@
}
},
"AuthSettings": {
"CF_Turnstile_SiteKey": "3x00000000000000000000FF",
"CF_Turnstile_SecretKey": "1x0000000000000000000000000000000AA",
"First_User_Admin": true,
"Admins_Require_2FA": false
},
"JwtSettings": {