feat: align with upstream 1.5.9.9
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { apiKeyPermissions, apiKeys, db } from '~/drizzle/db'
|
||||
import { and, eq, sql } from 'drizzle-orm'
|
||||
import { z } from 'zod'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
const PERSONAL_PERMISSION = 'songs:request'
|
||||
const apiKeyIdSchema = z.string().uuid('无效的令牌 ID')
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_LOGIN_REQUIRED', '请先登录')
|
||||
}
|
||||
|
||||
const apiKeyIdRaw = getRouterParam(event, 'id')
|
||||
if (!apiKeyIdRaw) {
|
||||
throw createApiError(400, 'USER_API_KEY_ID_REQUIRED', '令牌 ID 不能为空')
|
||||
}
|
||||
|
||||
const parsedApiKeyId = apiKeyIdSchema.safeParse(apiKeyIdRaw)
|
||||
if (!parsedApiKeyId.success) {
|
||||
throw createApiError(
|
||||
400,
|
||||
'USER_API_KEY_ID_INVALID',
|
||||
parsedApiKeyId.error.issues[0]?.message || '无效的令牌 ID'
|
||||
)
|
||||
}
|
||||
|
||||
const apiKeyId = parsedApiKeyId.data
|
||||
|
||||
try {
|
||||
const existingApiKey = await db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name
|
||||
})
|
||||
.from(apiKeys)
|
||||
.innerJoin(apiKeyPermissions, eq(apiKeyPermissions.apiKeyId, apiKeys.id))
|
||||
.where(
|
||||
and(
|
||||
eq(apiKeys.id, apiKeyId),
|
||||
eq(apiKeys.createdByUserId, user.id),
|
||||
eq(apiKeyPermissions.permission, PERSONAL_PERMISSION),
|
||||
sql`NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM ${apiKeyPermissions}
|
||||
WHERE ${apiKeyPermissions.apiKeyId} = ${apiKeys.id}
|
||||
AND ${apiKeyPermissions.permission} != ${PERSONAL_PERMISSION}
|
||||
)`
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
if (existingApiKey.length === 0) {
|
||||
throw createApiError(404, 'USER_API_KEY_NOT_FOUND', '个人集成令牌不存在')
|
||||
}
|
||||
|
||||
const apiKey = existingApiKey[0]
|
||||
if (!apiKey) {
|
||||
throw createApiError(404, 'USER_API_KEY_NOT_FOUND', '个人集成令牌不存在')
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(apiKeyPermissions).where(eq(apiKeyPermissions.apiKeyId, apiKeyId))
|
||||
await tx.delete(apiKeys).where(eq(apiKeys.id, apiKeyId))
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `个人集成令牌 "${apiKey.name}" 已删除`,
|
||||
data: {
|
||||
id: apiKeyId,
|
||||
name: apiKey.name
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createApiError(500, 'USER_API_KEY_DELETE_FAILED_DETAIL', `删除个人集成令牌失败:${error.message}`, { params: [error.message] })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { apiKeyPermissions, apiKeys, apiLogs, db } from '~/drizzle/db'
|
||||
import { and, count, desc, eq, sql } from 'drizzle-orm'
|
||||
import { z } from 'zod'
|
||||
import { getBeijingTime } from '~/utils/timeUtils'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
const PERSONAL_PERMISSION = 'songs:request'
|
||||
const apiKeyIdSchema = z.string().uuid('无效的令牌 ID')
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_LOGIN_REQUIRED', '请先登录')
|
||||
}
|
||||
|
||||
const apiKeyIdRaw = getRouterParam(event, 'id')
|
||||
if (!apiKeyIdRaw) {
|
||||
throw createApiError(400, 'USER_API_KEY_ID_REQUIRED', '令牌 ID 不能为空')
|
||||
}
|
||||
|
||||
const parsedApiKeyId = apiKeyIdSchema.safeParse(apiKeyIdRaw)
|
||||
if (!parsedApiKeyId.success) {
|
||||
throw createApiError(
|
||||
400,
|
||||
'USER_API_KEY_ID_INVALID',
|
||||
parsedApiKeyId.error.issues[0]?.message || '无效的令牌 ID'
|
||||
)
|
||||
}
|
||||
|
||||
const apiKeyId = parsedApiKeyId.data
|
||||
const query = getQuery(event)
|
||||
const page = Math.max(1, parseInt(query.page as string) || 1)
|
||||
const limit = Math.min(50, Math.max(1, parseInt(query.limit as string) || 10))
|
||||
const offset = (page - 1) * limit
|
||||
|
||||
try {
|
||||
const apiKeyResult = await db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
description: apiKeys.description,
|
||||
keyPrefix: apiKeys.keyPrefix,
|
||||
isActive: apiKeys.isActive,
|
||||
expiresAt: apiKeys.expiresAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
usageCount: apiKeys.usageCount
|
||||
})
|
||||
.from(apiKeys)
|
||||
.innerJoin(apiKeyPermissions, eq(apiKeyPermissions.apiKeyId, apiKeys.id))
|
||||
.where(
|
||||
and(
|
||||
eq(apiKeys.id, apiKeyId),
|
||||
eq(apiKeys.createdByUserId, user.id),
|
||||
eq(apiKeyPermissions.permission, PERSONAL_PERMISSION),
|
||||
sql`NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM ${apiKeyPermissions}
|
||||
WHERE ${apiKeyPermissions.apiKeyId} = ${apiKeys.id}
|
||||
AND ${apiKeyPermissions.permission} != ${PERSONAL_PERMISSION}
|
||||
)`
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
|
||||
const apiKey = apiKeyResult[0]
|
||||
if (!apiKey) {
|
||||
throw createApiError(404, 'USER_API_KEY_NOT_FOUND', '个人集成令牌不存在')
|
||||
}
|
||||
|
||||
const logs = await db
|
||||
.select({
|
||||
id: apiLogs.id,
|
||||
endpoint: apiLogs.endpoint,
|
||||
method: apiLogs.method,
|
||||
ipAddress: apiLogs.ipAddress,
|
||||
userAgent: apiLogs.userAgent,
|
||||
statusCode: apiLogs.statusCode,
|
||||
responseTimeMs: apiLogs.responseTimeMs,
|
||||
errorMessage: apiLogs.errorMessage,
|
||||
createdAt: apiLogs.createdAt
|
||||
})
|
||||
.from(apiLogs)
|
||||
.where(eq(apiLogs.apiKeyId, apiKeyId))
|
||||
.orderBy(desc(apiLogs.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
|
||||
const totalResult = await db
|
||||
.select({ count: count() })
|
||||
.from(apiLogs)
|
||||
.where(eq(apiLogs.apiKeyId, apiKeyId))
|
||||
|
||||
const total = Number(totalResult[0]?.count || 0)
|
||||
const expiresAt = apiKey.expiresAt ? new Date(apiKey.expiresAt) : null
|
||||
const now = getBeijingTime()
|
||||
const status = !apiKey.isActive ? 'inactive' : expiresAt && now > expiresAt ? 'expired' : 'active'
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
apiKey: {
|
||||
...apiKey,
|
||||
status
|
||||
},
|
||||
logs,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createApiError(500, 'USER_API_KEY_LOGS_FETCH_FAILED_DETAIL', `获取个人集成令牌日志失败:${error.message}`, { params: [error.message] })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { apiKeyPermissions, apiKeys, db } from '~/drizzle/db'
|
||||
import { and, desc, eq, sql } from 'drizzle-orm'
|
||||
import { getBeijingTime } from '~/utils/timeUtils'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
const PERSONAL_PERMISSION = 'songs:request'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_LOGIN_REQUIRED', '请先登录')
|
||||
}
|
||||
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
description: apiKeys.description,
|
||||
keyPrefix: apiKeys.keyPrefix,
|
||||
isActive: apiKeys.isActive,
|
||||
expiresAt: apiKeys.expiresAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
usageCount: apiKeys.usageCount
|
||||
})
|
||||
.from(apiKeys)
|
||||
.innerJoin(apiKeyPermissions, eq(apiKeyPermissions.apiKeyId, apiKeys.id))
|
||||
.where(
|
||||
and(
|
||||
eq(apiKeys.createdByUserId, user.id),
|
||||
eq(apiKeyPermissions.permission, PERSONAL_PERMISSION),
|
||||
sql`NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM ${apiKeyPermissions}
|
||||
WHERE ${apiKeyPermissions.apiKeyId} = ${apiKeys.id}
|
||||
AND ${apiKeyPermissions.permission} != ${PERSONAL_PERMISSION}
|
||||
)`
|
||||
)
|
||||
)
|
||||
.orderBy(desc(apiKeys.createdAt))
|
||||
|
||||
const now = getBeijingTime()
|
||||
const items = rows.map((key) => {
|
||||
const expiresAt = key.expiresAt ? new Date(key.expiresAt) : null
|
||||
return {
|
||||
...key,
|
||||
status: !key.isActive ? 'inactive' : expiresAt && now > expiresAt ? 'expired' : 'active'
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: items
|
||||
}
|
||||
} catch (error: any) {
|
||||
throw createApiError(500, 'USER_API_KEY_FETCH_FAILED_DETAIL', `获取个人集成令牌失败:${error.message}`, { params: [error.message] })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { apiKeyPermissions, apiKeys, db } from '~/drizzle/db'
|
||||
import { and, eq, sql } from 'drizzle-orm'
|
||||
import { z } from 'zod'
|
||||
import { generateApiKey, hashApiKey } from '~~/server/utils/apiKeyUtils'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
const PERSONAL_PERMISSION = 'songs:request'
|
||||
|
||||
const createPersonalApiKeySchema = z.object({
|
||||
name: z.string().min(1, '令牌名称不能为空').max(100, '令牌名称不能超过100个字符').optional(),
|
||||
description: z.string().max(500, '描述不能超过500个字符').optional().nullable()
|
||||
})
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_LOGIN_REQUIRED', '请先登录')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await readBody(event)
|
||||
const validatedData = createPersonalApiKeySchema.parse(body || {})
|
||||
|
||||
const apiKey = generateApiKey()
|
||||
const keyPrefix = apiKey.substring(0, 10)
|
||||
const keyHash = await hashApiKey(apiKey)
|
||||
const name = validatedData.name?.trim() || '个人 API Key'
|
||||
const description = validatedData.description?.trim() || '用于个人集成和投稿'
|
||||
|
||||
const result = await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(${user.id}::bigint)`)
|
||||
|
||||
const existingKeys = await tx
|
||||
.select({ id: apiKeys.id })
|
||||
.from(apiKeys)
|
||||
.innerJoin(apiKeyPermissions, eq(apiKeyPermissions.apiKeyId, apiKeys.id))
|
||||
.where(
|
||||
and(
|
||||
eq(apiKeys.createdByUserId, user.id),
|
||||
eq(apiKeyPermissions.permission, PERSONAL_PERMISSION),
|
||||
sql`NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM ${apiKeyPermissions}
|
||||
WHERE ${apiKeyPermissions.apiKeyId} = ${apiKeys.id}
|
||||
AND ${apiKeyPermissions.permission} != ${PERSONAL_PERMISSION}
|
||||
)`
|
||||
)
|
||||
)
|
||||
|
||||
if (existingKeys.length >= 5) {
|
||||
throw createApiError(400, 'USER_API_KEY_LIMIT_REACHED', '每个用户最多只能创建 5 个个人集成令牌')
|
||||
}
|
||||
|
||||
const apiKeyResult = await tx
|
||||
.insert(apiKeys)
|
||||
.values({
|
||||
name,
|
||||
description,
|
||||
keyPrefix,
|
||||
keyHash,
|
||||
isActive: true,
|
||||
expiresAt: null,
|
||||
usageCount: 0,
|
||||
createdByUserId: user.id
|
||||
})
|
||||
.returning({
|
||||
id: apiKeys.id,
|
||||
createdAt: apiKeys.createdAt
|
||||
})
|
||||
|
||||
const createdApiKey = apiKeyResult[0]
|
||||
if (!createdApiKey) {
|
||||
throw createApiError(500, 'USER_API_KEY_CREATE_FAILED', '创建个人 API Key 失败')
|
||||
}
|
||||
|
||||
const apiKeyId = createdApiKey.id
|
||||
|
||||
await tx.insert(apiKeyPermissions).values({
|
||||
apiKeyId,
|
||||
permission: PERSONAL_PERMISSION
|
||||
})
|
||||
|
||||
return {
|
||||
id: apiKeyId,
|
||||
name,
|
||||
description,
|
||||
keyPrefix,
|
||||
isActive: true,
|
||||
expiresAt: null,
|
||||
createdAt: createdApiKey.createdAt,
|
||||
lastUsedAt: null,
|
||||
usageCount: 0,
|
||||
status: 'active',
|
||||
apiKey
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '个人 API Key 创建成功',
|
||||
data: result
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
if (error.name === 'ZodError') {
|
||||
const issues = error.issues || error.errors || []
|
||||
throw createApiError(400, 'USER_REQUEST_VALIDATION_FAILED', `请求参数验证失败:${issues.map((e: any) => e.message).join(', ')}`, { params: [issues.map((e: any) => e.message).join(', ')] })
|
||||
}
|
||||
|
||||
throw createApiError(500, 'USER_API_KEY_CREATE_FAILED_DETAIL', `创建个人 API Key 失败:${error.message}`, { params: [error.message] })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user