Files
soul-yongping/next-project/app/api/admin/route.ts
2026-02-09 14:43:35 +08:00

91 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// app/api/admin/route.ts
// 后台管理API入口登录与鉴权账号密码从环境变量读取默认 admin / admin123
import { NextRequest, NextResponse } from 'next/server'
import {
verifyAdminToken,
getAdminTokenFromRequest,
verifyAdminCredentials,
getAdminCredentials,
createAdminToken,
getAdminCookieName,
getAdminCookieOptions,
} from '@/lib/admin-auth'
function requireAdmin(req: NextRequest): boolean {
const token = getAdminTokenFromRequest(req)
return verifyAdminToken(token)
}
// GET: 获取后台概览数据(需已登录)
export async function GET(req: NextRequest) {
if (!requireAdmin(req)) {
return NextResponse.json(
{ error: '未授权访问,请先登录' },
{ status: 401 }
)
}
// 获取所有模块的概览数据
const overview = {
content: {
totalChapters: 65,
totalWords: 120000,
publishedChapters: 60,
draftChapters: 5,
lastUpdate: new Date().toISOString()
},
payment: {
totalRevenue: 12800.50,
todayRevenue: 560.00,
totalOrders: 128,
todayOrders: 12,
averagePrice: 100.00
},
referral: {
totalReferrers: 45,
activeReferrers: 28,
totalCommission: 11520.45,
paidCommission: 8500.00,
pendingCommission: 3020.45
},
users: {
totalUsers: 1200,
purchasedUsers: 128,
activeUsers: 456,
todayNewUsers: 23
}
}
return NextResponse.json(overview)
}
// POST: 管理员登录(账号密码从环境变量 ADMIN_USERNAME / ADMIN_PASSWORD 读取,默认 admin / admin123
export async function POST(req: NextRequest) {
const body = await req.json()
const { username, password } = body
if (!username || !password) {
return NextResponse.json(
{ error: '请输入用户名和密码' },
{ status: 400 }
)
}
if (!verifyAdminCredentials(String(username).trim(), String(password))) {
return NextResponse.json(
{ error: '用户名或密码错误' },
{ status: 401 }
)
}
const token = createAdminToken()
const res = NextResponse.json({
success: true,
user: { id: 'admin', username: getAdminCredentials().username, role: 'admin', name: '卡若' },
})
const opts = getAdminCookieOptions()
res.cookies.set(getAdminCookieName(), token, opts)
return res
}