mirror of
https://github.com/kikootwo/ReadMeABook.git
synced 2026-06-03 04:40:09 +00:00
Add request approval system and audiobook path template
Implements admin approval workflow for user requests with global and per-user auto-approve controls. Adds new request statuses ('awaiting_approval', 'denied'), related API endpoints, and UI for pending approvals. Introduces configurable audiobook organization path template with validation and preview in settings, updates database schema and migrations for new fields.
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* Component: Admin Request Approval API
|
||||
* Documentation: documentation/admin-features/request-approval.md
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { requireAuth, requireAdmin, AuthenticatedRequest } from '@/lib/middleware/auth';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { getJobQueueService } from '@/lib/services/job-queue.service';
|
||||
import { RMABLogger } from '@/lib/utils/logger';
|
||||
import { z } from 'zod';
|
||||
|
||||
const logger = RMABLogger.create('API.Admin.Requests.Approve');
|
||||
|
||||
const ApprovalActionSchema = z.object({
|
||||
action: z.enum(['approve', 'deny']),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/admin/requests/[id]/approve
|
||||
* Approve or deny a request in 'awaiting_approval' status
|
||||
*/
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
||||
return requireAdmin(req, async () => {
|
||||
try {
|
||||
if (!req.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized', message: 'User not authenticated' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
|
||||
// Validate action
|
||||
const { action } = ApprovalActionSchema.parse(body);
|
||||
|
||||
// Fetch the request
|
||||
const existingRequest = await prisma.request.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
audiobook: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
plexUsername: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!existingRequest) {
|
||||
return NextResponse.json(
|
||||
{ error: 'NotFound', message: 'Request not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate request is in 'awaiting_approval' status
|
||||
if (existingRequest.status !== 'awaiting_approval') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'InvalidStatus',
|
||||
message: `Request is not awaiting approval (current status: ${existingRequest.status})`,
|
||||
currentStatus: existingRequest.status,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update request based on action
|
||||
if (action === 'approve') {
|
||||
// Approve: Change status to 'pending' and trigger search job
|
||||
const updatedRequest = await prisma.request.update({
|
||||
where: { id },
|
||||
data: { status: 'pending' },
|
||||
include: {
|
||||
audiobook: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
plexUsername: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Trigger search job
|
||||
const jobQueue = getJobQueueService();
|
||||
await jobQueue.addSearchJob(updatedRequest.id, {
|
||||
id: updatedRequest.audiobook.id,
|
||||
title: updatedRequest.audiobook.title,
|
||||
author: updatedRequest.audiobook.author,
|
||||
asin: updatedRequest.audiobook.audibleAsin || undefined,
|
||||
});
|
||||
|
||||
logger.info(`Request ${id} approved by admin ${req.user.sub}`, {
|
||||
requestId: id,
|
||||
userId: updatedRequest.userId,
|
||||
audiobookTitle: updatedRequest.audiobook.title,
|
||||
adminId: req.user.sub,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Request approved and search job triggered',
|
||||
request: updatedRequest,
|
||||
});
|
||||
} else {
|
||||
// Deny: Change status to 'denied'
|
||||
const updatedRequest = await prisma.request.update({
|
||||
where: { id },
|
||||
data: { status: 'denied' },
|
||||
include: {
|
||||
audiobook: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
plexUsername: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(`Request ${id} denied by admin ${req.user.sub}`, {
|
||||
requestId: id,
|
||||
userId: updatedRequest.userId,
|
||||
audiobookTitle: updatedRequest.audiobook.title,
|
||||
adminId: req.user.sub,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Request denied',
|
||||
request: updatedRequest,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to process approval action', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'ValidationError',
|
||||
message: 'Invalid action. Must be "approve" or "deny"',
|
||||
details: error.errors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'ApprovalError',
|
||||
message: 'Failed to process approval action',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Component: Admin Pending Approval Requests API
|
||||
* Documentation: documentation/admin-features/request-approval.md
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { requireAuth, requireAdmin, AuthenticatedRequest } from '@/lib/middleware/auth';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { RMABLogger } from '@/lib/utils/logger';
|
||||
|
||||
const logger = RMABLogger.create('API.Admin.Requests.PendingApproval');
|
||||
|
||||
/**
|
||||
* GET /api/admin/requests/pending-approval
|
||||
* Get all requests with status 'awaiting_approval'
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
||||
return requireAdmin(req, async () => {
|
||||
try {
|
||||
const requests = await prisma.request.findMany({
|
||||
where: {
|
||||
status: 'awaiting_approval',
|
||||
deletedAt: null,
|
||||
},
|
||||
include: {
|
||||
audiobook: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
plexUsername: true,
|
||||
avatarUrl: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
requests,
|
||||
count: requests.length,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch pending approval requests', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'FetchError',
|
||||
message: 'Failed to fetch pending approval requests',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Component: Admin Auto-Approve Settings API
|
||||
* Documentation: documentation/settings-pages.md
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { requireAuth, requireAdmin, AuthenticatedRequest } from '@/lib/middleware/auth';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { RMABLogger } from '@/lib/utils/logger';
|
||||
|
||||
const logger = RMABLogger.create('API.Admin.Settings.AutoApprove');
|
||||
|
||||
/**
|
||||
* GET /api/admin/settings/auto-approve
|
||||
* Get current global auto-approve setting
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
||||
return requireAdmin(req, async () => {
|
||||
try {
|
||||
const config = await prisma.configuration.findUnique({
|
||||
where: { key: 'auto_approve_requests' },
|
||||
});
|
||||
|
||||
// Default to true if not configured (backward compatibility)
|
||||
const autoApproveRequests = config === null ? true : config.value === 'true';
|
||||
|
||||
return NextResponse.json({ autoApproveRequests });
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch auto-approve setting', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch auto-approve setting' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH /api/admin/settings/auto-approve
|
||||
* Update global auto-approve setting
|
||||
*/
|
||||
export async function PATCH(request: NextRequest) {
|
||||
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
||||
return requireAdmin(req, async () => {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { autoApproveRequests } = body;
|
||||
|
||||
// Validate input
|
||||
if (typeof autoApproveRequests !== 'boolean') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid input. autoApproveRequests must be a boolean' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update configuration
|
||||
await prisma.configuration.upsert({
|
||||
where: { key: 'auto_approve_requests' },
|
||||
create: {
|
||||
key: 'auto_approve_requests',
|
||||
value: autoApproveRequests.toString(),
|
||||
},
|
||||
update: {
|
||||
value: autoApproveRequests.toString(),
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(`Auto-approve setting updated to: ${autoApproveRequests}`, {
|
||||
userId: req.user?.sub,
|
||||
});
|
||||
|
||||
return NextResponse.json({ autoApproveRequests });
|
||||
} catch (error) {
|
||||
logger.error('Failed to update auto-approve setting', {
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to update auto-approve setting' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -14,7 +14,7 @@ export async function PUT(request: NextRequest) {
|
||||
return requireAuth(request, async (req: AuthenticatedRequest) => {
|
||||
return requireAdmin(req, async () => {
|
||||
try {
|
||||
const { downloadDir, mediaDir, metadataTaggingEnabled, chapterMergingEnabled } = await request.json();
|
||||
const { downloadDir, mediaDir, audiobookPathTemplate, metadataTaggingEnabled, chapterMergingEnabled } = await request.json();
|
||||
|
||||
if (!downloadDir || !mediaDir) {
|
||||
return NextResponse.json(
|
||||
@@ -44,6 +44,20 @@ export async function PUT(request: NextRequest) {
|
||||
create: { key: 'media_dir', value: mediaDir },
|
||||
});
|
||||
|
||||
// Update audiobook path template
|
||||
if (audiobookPathTemplate !== undefined) {
|
||||
await prisma.configuration.upsert({
|
||||
where: { key: 'audiobook_path_template' },
|
||||
update: { value: audiobookPathTemplate },
|
||||
create: {
|
||||
key: 'audiobook_path_template',
|
||||
value: audiobookPathTemplate,
|
||||
category: 'automation',
|
||||
description: 'Template for organizing audiobook files in media directory',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Update metadata tagging setting
|
||||
await prisma.configuration.upsert({
|
||||
where: { key: 'metadata_tagging_enabled' },
|
||||
|
||||
@@ -86,6 +86,7 @@ export async function GET(request: NextRequest) {
|
||||
paths: {
|
||||
downloadDir: configMap.get('download_dir') || '/downloads',
|
||||
mediaDir: configMap.get('media_dir') || '/media/audiobooks',
|
||||
audiobookPathTemplate: configMap.get('audiobook_path_template') || '{author}/{title} {asin}',
|
||||
metadataTaggingEnabled: configMap.get('metadata_tagging_enabled') === 'true',
|
||||
chapterMergingEnabled: configMap.get('chapter_merging_enabled') === 'true',
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ export async function PUT(
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const { role } = body;
|
||||
const { role, autoApproveRequests } = body;
|
||||
|
||||
// Validate role
|
||||
if (!role || (role !== 'user' && role !== 'admin')) {
|
||||
@@ -29,6 +29,14 @@ export async function PUT(
|
||||
);
|
||||
}
|
||||
|
||||
// Validate autoApproveRequests (optional)
|
||||
if (autoApproveRequests !== undefined && autoApproveRequests !== null && typeof autoApproveRequests !== 'boolean') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid autoApproveRequests. Must be a boolean or null' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent user from demoting themselves
|
||||
if (req.user && id === req.user.sub) {
|
||||
return NextResponse.json(
|
||||
@@ -45,6 +53,7 @@ export async function PUT(
|
||||
authProvider: true,
|
||||
plexUsername: true,
|
||||
deletedAt: true,
|
||||
role: true, // Need current role to detect role changes
|
||||
},
|
||||
});
|
||||
|
||||
@@ -63,30 +72,48 @@ export async function PUT(
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent changing setup admin role
|
||||
if (targetUser.isSetupAdmin && role !== 'admin') {
|
||||
// Detect if role is being changed
|
||||
const isRoleChange = targetUser.role !== role;
|
||||
|
||||
// Prevent changing setup admin role (only if role is actually being changed)
|
||||
if (targetUser.isSetupAdmin && isRoleChange && role !== 'admin') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cannot change the setup admin role. This account must always remain an admin.' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent changing OIDC user roles (managed by identity provider)
|
||||
if (targetUser.authProvider === 'oidc') {
|
||||
// Prevent changing OIDC user roles (only if role is actually being changed)
|
||||
if (targetUser.authProvider === 'oidc' && isRoleChange) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cannot change OIDC user roles. Use admin role mapping in OIDC settings instead.' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update user role
|
||||
// Validate that admins cannot have autoApproveRequests set to false
|
||||
if (role === 'admin' && autoApproveRequests === false) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Admins must always auto-approve requests. Cannot set autoApproveRequests to false for admin users.' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Prepare update data
|
||||
const updateData: { role: string; autoApproveRequests?: boolean | null } = { role };
|
||||
if (autoApproveRequests !== undefined) {
|
||||
updateData.autoApproveRequests = autoApproveRequests;
|
||||
}
|
||||
|
||||
// Update user role and autoApproveRequests
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id },
|
||||
data: { role },
|
||||
data: updateData,
|
||||
select: {
|
||||
id: true,
|
||||
plexUsername: true,
|
||||
role: true,
|
||||
autoApproveRequests: true,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ export async function GET(request: NextRequest) {
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
lastLoginAt: true,
|
||||
autoApproveRequests: true,
|
||||
_count: {
|
||||
select: {
|
||||
requests: true,
|
||||
|
||||
Reference in New Issue
Block a user