feat: admin api cookie

This commit is contained in:
shinya
2025-07-09 22:42:53 +08:00
parent 7edc673c9f
commit 2bbb67ac9c
16 changed files with 215 additions and 384 deletions

View File

@@ -1,7 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any,no-console,@typescript-eslint/no-non-null-assertion */
import { NextResponse } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { getStorage } from '@/lib/db';
import { IStorage } from '@/lib/types';
@@ -18,7 +19,7 @@ const ACTIONS = [
'setAllowRegister',
] as const;
export async function POST(request: Request) {
export async function POST(request: NextRequest) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
@@ -32,23 +33,25 @@ export async function POST(request: Request) {
try {
const body = await request.json();
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const username = authInfo.username;
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)) {
if (!action || !ACTIONS.includes(action)) {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
@@ -71,12 +74,6 @@ export async function POST(request: Request) {
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
@@ -85,20 +82,6 @@ export async function POST(request: Request) {
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 }
);
}
}
// 查找目标用户条目