feat: implement all admin functions

This commit is contained in:
shinya
2025-07-05 18:49:35 +08:00
parent 774a5dd697
commit 5fcdcbb390
13 changed files with 1337 additions and 310 deletions

View File

@@ -7,13 +7,39 @@ import { getConfig } from '@/lib/config';
export const runtime = 'edge';
export async function GET() {
export async function GET(request: Request) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
{
error: '不支持本地存储进行管理员配置',
},
{ status: 400 }
);
}
const { searchParams } = new URL(request.url);
const username = searchParams.get('username');
try {
const config = getConfig();
const result: AdminConfigResult = {
Role: 'owner',
Config: config,
};
if (username === process.env.USERNAME) {
result.Role = 'owner';
} else {
const user = config.UserConfig.Users.find((u) => u.username === username);
if (user && user.role === 'admin') {
result.Role = 'admin';
} else {
return NextResponse.json(
{ error: '你是管理员吗你就访问?' },
{ status: 401 }
);
}
}
return NextResponse.json(result, {
headers: {
@@ -31,30 +57,3 @@ export async function GET() {
);
}
}
export async function POST(request: Request) {
try {
const updateData = await request.json();
// 在实际应用中,这里应该验证用户权限并更新配置
console.log('更新管理员配置:', updateData);
// 模拟配置更新
// 在实际应用中,这里应该将配置保存到数据库或配置文件
return NextResponse.json({
success: true,
message: '配置更新成功',
timestamp: new Date().toISOString(),
});
} catch (error) {
console.error('更新管理员配置失败:', error);
return NextResponse.json(
{
error: '更新管理员配置失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,55 @@
/* eslint-disable no-console */
import { NextResponse } from 'next/server';
import { resetConfig } from '@/lib/config';
export const runtime = 'edge';
export async function GET(request: Request) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
{
error: '不支持本地存储进行管理员配置',
},
{ status: 400 }
);
}
const { searchParams } = new URL(request.url);
const username = searchParams.get('username');
const password = searchParams.get('password');
if (!username || !password) {
return NextResponse.json(
{ error: '用户名和密码不能为空' },
{ status: 400 }
);
}
if (username !== process.env.USERNAME || password !== process.env.PASSWORD) {
return NextResponse.json({ error: '仅支持站长重置配置' }, { status: 401 });
}
try {
await resetConfig();
return NextResponse.json(
{ ok: true },
{
headers: {
'Cache-Control': 'no-store', // 管理员配置不缓存
},
}
);
} catch (error) {
return NextResponse.json(
{
error: '重置管理员配置失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,123 @@
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
import { NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { getStorage } from '@/lib/db';
export const runtime = 'edge';
export async function POST(request: Request) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
{
error: '不支持本地存储进行管理员配置',
},
{ status: 400 }
);
}
try {
const body = await request.json();
const {
username,
password,
SiteName,
Announcement,
SearchDownstreamMaxPage,
SiteInterfaceCacheTime,
SearchResultDefaultAggregate,
} = body as {
username?: string;
password?: string;
SiteName: string;
Announcement: string;
SearchDownstreamMaxPage: number;
SiteInterfaceCacheTime: number;
SearchResultDefaultAggregate: boolean;
};
// 参数校验
if (
typeof SiteName !== 'string' ||
typeof Announcement !== 'string' ||
typeof SearchDownstreamMaxPage !== 'number' ||
typeof SiteInterfaceCacheTime !== 'number' ||
typeof SearchResultDefaultAggregate !== 'boolean'
) {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
if (!username || !password) {
return NextResponse.json(
{ error: '用户名和密码不能为空' },
{ status: 400 }
);
}
const adminConfig = getConfig();
const storage = getStorage();
// 权限与密码校验
if (username === process.env.USERNAME) {
// 站长
if (password !== process.env.PASSWORD) {
return NextResponse.json({ error: '密码错误' }, { status: 401 });
}
} else {
// 管理员
const user = adminConfig.UserConfig.Users.find(
(u) => u.username === username
);
if (!user || user.role !== 'admin') {
return NextResponse.json({ error: '权限不足' }, { status: 401 });
}
if (!storage || typeof storage.verifyUser !== 'function') {
return NextResponse.json(
{ error: '存储未配置用户认证' },
{ status: 500 }
);
}
const ok = await storage.verifyUser(username, password);
if (!ok) {
return NextResponse.json({ error: '密码错误' }, { status: 401 });
}
}
// 更新缓存中的站点设置
adminConfig.SiteConfig = {
SiteName,
Announcement,
SearchDownstreamMaxPage,
SiteInterfaceCacheTime,
SearchResultDefaultAggregate,
};
// 写入数据库
if (storage && typeof (storage as any).setAdminConfig === 'function') {
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json(
{ ok: true },
{
headers: {
'Cache-Control': 'no-store', // 不缓存结果
},
}
);
} catch (error) {
console.error('更新站点配置失败:', error);
return NextResponse.json(
{
error: '更新站点配置失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,184 @@
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
import { NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { getStorage, IStorage } from '@/lib/db';
export const runtime = 'edge';
// 支持的操作类型
type Action = 'add' | 'disable' | 'enable' | 'delete' | 'sort';
interface BaseBody {
username?: string;
password?: string;
action?: Action;
}
export async function POST(request: Request) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
{
error: '不支持本地存储进行管理员配置',
},
{ status: 400 }
);
}
try {
const body = (await request.json()) as BaseBody & Record<string, any>;
const { username, password, action } = body;
// 基础校验
const ACTIONS: Action[] = ['add', 'disable', 'enable', 'delete', 'sort'];
if (!username || !password || !action || !ACTIONS.includes(action)) {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
// 获取配置与存储
const adminConfig = getConfig();
const storage: IStorage | null = getStorage();
// 权限与身份校验
if (username === process.env.USERNAME) {
if (password !== process.env.PASSWORD) {
return NextResponse.json(
{ error: '用户名或密码错误' },
{ status: 401 }
);
}
} else {
const userEntry = adminConfig.UserConfig.Users.find(
(u) => u.username === username
);
if (!userEntry || userEntry.role !== 'admin') {
return NextResponse.json({ error: '权限不足' }, { status: 401 });
}
if (!storage || typeof storage.verifyUser !== 'function') {
return NextResponse.json(
{ error: '存储未配置用户认证' },
{ status: 500 }
);
}
const pass = await storage.verifyUser(username, password);
if (!pass) {
return NextResponse.json(
{ error: '用户名或密码错误' },
{ status: 401 }
);
}
}
switch (action) {
case 'add': {
const { key, name, api, detail } = body as {
key?: string;
name?: string;
api?: string;
detail?: string;
};
if (!key || !name || !api) {
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
}
if (adminConfig.SourceConfig.some((s) => s.key === key)) {
return NextResponse.json({ error: '该源已存在' }, { status: 400 });
}
adminConfig.SourceConfig.push({
key,
name,
api,
detail,
from: 'custom',
disabled: false,
});
break;
}
case 'disable': {
const { key } = body as { key?: string };
if (!key)
return NextResponse.json({ error: '缺少 key 参数' }, { status: 400 });
const entry = adminConfig.SourceConfig.find((s) => s.key === key);
if (!entry)
return NextResponse.json({ error: '源不存在' }, { status: 404 });
entry.disabled = true;
break;
}
case 'enable': {
const { key } = body as { key?: string };
if (!key)
return NextResponse.json({ error: '缺少 key 参数' }, { status: 400 });
const entry = adminConfig.SourceConfig.find((s) => s.key === key);
if (!entry)
return NextResponse.json({ error: '源不存在' }, { status: 404 });
entry.disabled = false;
break;
}
case 'delete': {
const { key } = body as { key?: string };
if (!key)
return NextResponse.json({ error: '缺少 key 参数' }, { status: 400 });
const idx = adminConfig.SourceConfig.findIndex((s) => s.key === key);
if (idx === -1)
return NextResponse.json({ error: '源不存在' }, { status: 404 });
const entry = adminConfig.SourceConfig[idx];
if (entry.from === 'config') {
return NextResponse.json({ error: '该源不可删除' }, { status: 400 });
}
adminConfig.SourceConfig.splice(idx, 1);
break;
}
case 'sort': {
const { order } = body as { order?: string[] };
if (!Array.isArray(order)) {
return NextResponse.json(
{ error: '排序列表格式错误' },
{ status: 400 }
);
}
const map = new Map(adminConfig.SourceConfig.map((s) => [s.key, s]));
const newList: typeof adminConfig.SourceConfig = [];
order.forEach((k) => {
const item = map.get(k);
if (item) {
newList.push(item);
map.delete(k);
}
});
// 未在 order 中的保持原顺序
adminConfig.SourceConfig.forEach((item) => {
if (map.has(item.key)) newList.push(item);
});
adminConfig.SourceConfig = newList;
break;
}
default:
return NextResponse.json({ error: '未知操作' }, { status: 400 });
}
// 持久化到存储
if (storage && typeof (storage as any).setAdminConfig === 'function') {
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json(
{ ok: true },
{
headers: {
'Cache-Control': 'no-store',
},
}
);
} catch (error) {
console.error('视频源管理操作失败:', error);
return NextResponse.json(
{
error: '视频源管理操作失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,260 @@
/* eslint-disable @typescript-eslint/no-explicit-any,no-console,@typescript-eslint/no-non-null-assertion */
import { NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { getStorage, IStorage } from '@/lib/db';
export const runtime = 'edge';
// 支持的操作类型
const ACTIONS = [
'add',
'ban',
'unban',
'setAdmin',
'cancelAdmin',
'setAllowRegister',
] as const;
export async function POST(request: Request) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
{
error: '不支持本地存储进行管理员配置',
},
{ status: 400 }
);
}
try {
const body = await request.json();
const {
username, // 操作者用户名
password, // 操作者密码
targetUsername, // 目标用户名
targetPassword, // 目标用户密码(仅在添加用户时需要)
allowRegister,
action,
} = body as {
username?: string;
password?: string;
targetUsername?: string;
targetPassword?: string;
allowRegister?: boolean;
action?: (typeof ACTIONS)[number];
};
if (!username || !password || !action || !ACTIONS.includes(action)) {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
if (action !== 'setAllowRegister' && !targetUsername) {
return NextResponse.json({ error: '缺少目标用户名' }, { status: 400 });
}
if (action !== 'setAllowRegister' && username === targetUsername) {
return NextResponse.json(
{ error: '无法对自己进行此操作' },
{ status: 400 }
);
}
// 获取配置与存储
const adminConfig = getConfig();
const storage: IStorage | null = getStorage();
// 判定操作者角色
let operatorRole: 'owner' | 'admin';
if (username === process.env.USERNAME) {
operatorRole = 'owner';
if (password !== process.env.PASSWORD) {
return NextResponse.json(
{ error: '用户名或密码错误' },
{ status: 401 }
);
}
} else {
const userEntry = adminConfig.UserConfig.Users.find(
(u) => u.username === username
);
if (!userEntry || userEntry.role !== 'admin') {
return NextResponse.json({ error: '权限不足' }, { status: 401 });
}
operatorRole = 'admin';
if (!storage || typeof storage.verifyUser !== 'function') {
return NextResponse.json(
{ error: '存储未配置用户认证' },
{ status: 500 }
);
}
const ok = await storage.verifyUser(username, password);
if (!ok) {
return NextResponse.json(
{ error: '用户名或密码错误' },
{ status: 401 }
);
}
}
// 查找目标用户条目
let targetEntry = adminConfig.UserConfig.Users.find(
(u) => u.username === targetUsername
);
if (targetEntry && targetEntry.role === 'owner') {
return NextResponse.json({ error: '无法操作站长' }, { status: 400 });
}
// 权限校验逻辑
const isTargetAdmin = targetEntry?.role === 'admin';
if (action === 'setAllowRegister') {
if (typeof allowRegister !== 'boolean') {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
adminConfig.UserConfig.AllowRegister = allowRegister;
// 保存后直接返回成功(走后面的统一保存逻辑)
} else {
switch (action) {
case 'add': {
if (targetEntry) {
return NextResponse.json({ error: '用户已存在' }, { status: 400 });
}
if (!targetPassword) {
return NextResponse.json(
{ error: '缺少目标用户密码' },
{ status: 400 }
);
}
if (!storage || typeof storage.registerUser !== 'function') {
return NextResponse.json(
{ error: '存储未配置用户注册' },
{ status: 500 }
);
}
await storage.registerUser(targetUsername!, targetPassword);
// 更新配置
adminConfig.UserConfig.Users.push({
username: targetUsername!,
role: 'user',
});
targetEntry =
adminConfig.UserConfig.Users[
adminConfig.UserConfig.Users.length - 1
];
break;
}
case 'ban': {
if (!targetEntry) {
return NextResponse.json(
{ error: '目标用户不存在' },
{ status: 404 }
);
}
if (isTargetAdmin) {
// 目标是管理员
if (operatorRole !== 'owner') {
return NextResponse.json(
{ error: '仅站长可封禁管理员' },
{ status: 401 }
);
}
}
targetEntry.banned = true;
break;
}
case 'unban': {
if (!targetEntry) {
return NextResponse.json(
{ error: '目标用户不存在' },
{ status: 404 }
);
}
if (isTargetAdmin) {
if (operatorRole !== 'owner') {
return NextResponse.json(
{ error: '仅站长可操作管理员' },
{ status: 401 }
);
}
}
targetEntry.banned = false;
break;
}
case 'setAdmin': {
if (!targetEntry) {
return NextResponse.json(
{ error: '目标用户不存在' },
{ status: 404 }
);
}
if (targetEntry.role === 'admin') {
return NextResponse.json(
{ error: '该用户已是管理员' },
{ status: 400 }
);
}
if (operatorRole !== 'owner') {
return NextResponse.json(
{ error: '仅站长可设置管理员' },
{ status: 401 }
);
}
targetEntry.role = 'admin';
break;
}
case 'cancelAdmin': {
if (!targetEntry) {
return NextResponse.json(
{ error: '目标用户不存在' },
{ status: 404 }
);
}
if (targetEntry.role !== 'admin') {
return NextResponse.json(
{ error: '目标用户不是管理员' },
{ status: 400 }
);
}
if (operatorRole !== 'owner') {
return NextResponse.json(
{ error: '仅站长可取消管理员' },
{ status: 401 }
);
}
targetEntry.role = 'user';
break;
}
default:
return NextResponse.json({ error: '未知操作' }, { status: 400 });
}
}
// 将更新后的配置写入数据库
if (storage && typeof (storage as any).setAdminConfig === 'function') {
await (storage as any).setAdminConfig(adminConfig);
}
return NextResponse.json(
{ ok: true },
{
headers: {
'Cache-Control': 'no-store', // 管理员配置不缓存
},
}
);
} catch (error) {
console.error('用户管理操作失败:', error);
return NextResponse.json(
{
error: '用户管理操作失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -1,6 +1,7 @@
/* eslint-disable no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
import { db } from '@/lib/db';
export const runtime = 'edge';
@@ -44,7 +45,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: '密码不能为空' }, { status: 400 });
}
// 可能是管理员,直接读环境变量
// 可能是站长,直接读环境变量
if (
username === process.env.USERNAME &&
password === process.env.PASSWORD
@@ -52,6 +53,12 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ ok: true });
}
const config = getConfig();
const user = config.UserConfig.Users.find((u) => u.username === username);
if (user && user.banned) {
return NextResponse.json({ error: '用户被封禁' }, { status: 401 });
}
// 校验用户密码
try {
const pass = await db.verifyUser(username, password);