feat: align with upstream 1.5.9.9
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { db, userIdentities, eq, and, users } from '~/drizzle/db'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const { password } = body
|
||||
|
||||
if (!password) {
|
||||
throw createApiError(400, 'USER_PASSWORD_REQUIRED', '请输入密码')
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
const dbUserResult = await db.select({ password: users.password }).from(users).where(eq(users.id, user.id)).limit(1)
|
||||
const dbUser = dbUserResult[0]
|
||||
|
||||
if (!dbUser) {
|
||||
throw createApiError(404, 'USER_NOT_FOUND', '用户不存在')
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(password, dbUser.password)
|
||||
if (!isPasswordValid) {
|
||||
// 密码错误不应返回 401,否则会触发全局登出
|
||||
throw createApiError(403, 'USER_PASSWORD_INCORRECT', '密码错误')
|
||||
}
|
||||
|
||||
// 删除TOTP记录
|
||||
await db.delete(userIdentities)
|
||||
.where(and(eq(userIdentities.userId, user.id), eq(userIdentities.provider, 'totp')))
|
||||
|
||||
return { success: true }
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import otplib from 'otplib'
|
||||
const { authenticator } = otplib
|
||||
import { db, userIdentities, eq, and } from '~/drizzle/db'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
const body = await readBody(event)
|
||||
const { token, secret } = body
|
||||
|
||||
if (!token || !secret) {
|
||||
throw createApiError(400, 'USER_MISSING_CODE_OR_SECRET', '缺少验证码或密钥')
|
||||
}
|
||||
|
||||
const isValid = authenticator.check(token, secret)
|
||||
if (!isValid) {
|
||||
throw createApiError(400, 'USER_CODE_INVALID', '验证码错误')
|
||||
}
|
||||
|
||||
// 检查是否已存在
|
||||
const existing = await db.query.userIdentities.findFirst({
|
||||
where: and(eq(userIdentities.userId, user.id), eq(userIdentities.provider, 'totp'))
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
// 更新密钥
|
||||
await db.update(userIdentities)
|
||||
.set({ providerUserId: secret })
|
||||
.where(eq(userIdentities.id, existing.id))
|
||||
} else {
|
||||
// 保存到数据库
|
||||
await db.insert(userIdentities).values({
|
||||
userId: user.id,
|
||||
provider: 'totp',
|
||||
providerUserId: secret,
|
||||
createdAt: new Date()
|
||||
})
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import otplib from 'otplib'
|
||||
const { authenticator } = otplib
|
||||
import QRCode from 'qrcode'
|
||||
import { db, userIdentities, eq, and } from '~/drizzle/db'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
// 检查是否已开启2FA
|
||||
const existing = await db.query.userIdentities.findFirst({
|
||||
where: and(eq(userIdentities.userId, user.id), eq(userIdentities.provider, 'totp'))
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
throw createApiError(400, 'USER_2FA_ALREADY_ENABLED', '已开启双重认证')
|
||||
}
|
||||
|
||||
const secret = authenticator.generateSecret()
|
||||
const otpauth = authenticator.keyuri(user.username, 'VoiceHub', secret)
|
||||
|
||||
// 生成QR Code Data URL
|
||||
const qrCode = await QRCode.toDataURL(otpauth)
|
||||
|
||||
return { secret, qrCode }
|
||||
})
|
||||
@@ -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] })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { db, eq, and, users, userIdentities } from '~/drizzle/db'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
import { getIdentityAvatarUrl } from '~~/server/utils/user-avatar'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const identityId = Number(body?.identityId)
|
||||
if (!Number.isInteger(identityId) || identityId <= 0) {
|
||||
throw createApiError(400, 'COMMON_INVALID_PARAMS', '参数错误')
|
||||
}
|
||||
|
||||
const identity = await db.query.userIdentities.findFirst({
|
||||
where: and(eq(userIdentities.id, identityId), eq(userIdentities.userId, user.id)),
|
||||
columns: {
|
||||
provider: true,
|
||||
providerUserId: true,
|
||||
providerUsername: true,
|
||||
avatar: true
|
||||
}
|
||||
})
|
||||
|
||||
const avatarUrl = getIdentityAvatarUrl(identity)
|
||||
if (!identity || !avatarUrl) {
|
||||
throw createApiError(400, 'COMMON_INVALID_PARAMS', '该身份没有可用的头像')
|
||||
}
|
||||
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
avatarProvider: identity.provider,
|
||||
avatarProviderUserId: identity.providerUserId
|
||||
})
|
||||
.where(eq(users.id, user.id))
|
||||
|
||||
return { success: true, avatar: avatarUrl }
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查请求方法
|
||||
if (event.method !== 'POST') {
|
||||
throw createApiError(405, 'HTTP_METHOD_NOT_ALLOWED', '方法不被允许')
|
||||
}
|
||||
|
||||
// 检查用户认证
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await readBody(event)
|
||||
|
||||
// 验证邮箱格式
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!body.email || !emailRegex.test(body.email)) {
|
||||
throw createApiError(400, 'USER_INVALID_EMAIL', '请输入有效的邮箱地址')
|
||||
}
|
||||
|
||||
const email = body.email.trim().toLowerCase()
|
||||
|
||||
// 检查邮箱是否已被其他用户绑定
|
||||
const existingUser = await db.select().from(users).where(eq(users.email, email)).limit(1)
|
||||
|
||||
if (existingUser.length > 0 && existingUser[0].id !== user.id) {
|
||||
throw createApiError(400, 'USER_EMAIL_TAKEN', '该邮箱已被其他用户绑定')
|
||||
}
|
||||
|
||||
// 更新用户邮箱
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
email: email,
|
||||
emailVerified: false
|
||||
})
|
||||
.where(eq(users.id, user.id))
|
||||
|
||||
// 发送邮箱验证码
|
||||
try {
|
||||
const { sendEmailVerificationCode } = await import('~~/server/api/user/email/send-code.post')
|
||||
const { getClientIP } = await import('~~/server/utils/ip-utils')
|
||||
const clientIP = getClientIP(event)
|
||||
|
||||
await sendEmailVerificationCode(user.id, email, user.name, clientIP)
|
||||
} catch (emailError) {
|
||||
console.error('发送邮箱验证码失败:', emailError)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '验证码已发送,请查收邮箱并输入验证码完成验证'
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('绑定邮箱失败:', error)
|
||||
|
||||
if (error?.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createApiError(500, 'USER_EMAIL_BIND_FAILED', '绑定邮箱失败')
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { getClientIP } from '~~/server/utils/ip-utils'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查请求方法
|
||||
if (getMethod(event) !== 'POST') {
|
||||
throw createApiError(405, 'HTTP_METHOD_NOT_ALLOWED', '方法不被允许')
|
||||
}
|
||||
|
||||
// 检查用户认证
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
try {
|
||||
// 获取用户邮箱信息
|
||||
const userResult = await db.select().from(users).where(eq(users.id, user.id)).limit(1)
|
||||
|
||||
const currentUser = userResult[0]
|
||||
|
||||
if (!currentUser?.email) {
|
||||
throw createApiError(400, 'USER_BIND_EMAIL_FIRST', '请先绑定邮箱')
|
||||
}
|
||||
|
||||
if (currentUser.emailVerified) {
|
||||
throw createApiError(400, 'USER_EMAIL_ALREADY_VERIFIED', '邮箱已验证,无需重新发送')
|
||||
}
|
||||
|
||||
// 发送邮箱验证码
|
||||
try {
|
||||
const { sendEmailVerificationCode } = await import('~~/server/api/user/email/send-code.post')
|
||||
const clientIP = getClientIP(event)
|
||||
|
||||
await sendEmailVerificationCode(currentUser.id, currentUser.email, currentUser.name, clientIP)
|
||||
|
||||
return { success: true, message: '验证码已重新发送' }
|
||||
} catch (emailError) {
|
||||
console.error('发送邮箱验证码失败:', emailError)
|
||||
throw createApiError(500, 'USER_CODE_SEND_FAILED', '发送验证码失败,请稍后重试')
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('重新发送验证邮件失败:', error)
|
||||
|
||||
if (error?.statusCode) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createApiError(500, 'USER_RESEND_EMAIL_FAILED', '重新发送验证邮件失败')
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { SmtpService } from '~~/server/services/smtpService'
|
||||
import { getClientIP } from '~~/server/utils/ip-utils'
|
||||
import { getServerTimestamp } from '~~/server/utils/serverTime'
|
||||
import { delStoreIfValue, hashStateCode, setStore } from '~~/server/utils/captchaStore'
|
||||
import { randomInt } from 'node:crypto'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
function generateCode(): string {
|
||||
return randomInt(100000, 1000000).toString()
|
||||
}
|
||||
|
||||
export async function sendEmailVerificationCode(
|
||||
userId: number,
|
||||
email: string,
|
||||
name?: string,
|
||||
ipAddress?: string
|
||||
) {
|
||||
const code = generateCode()
|
||||
const expiresAt = getServerTimestamp() + 5 * 60 * 1000
|
||||
const stateKey = `email-verify:${userId}`
|
||||
const storedValue = JSON.stringify({
|
||||
email,
|
||||
codeHash: hashStateCode(stateKey, code),
|
||||
expiresAt
|
||||
})
|
||||
await setStore(stateKey, storedValue, 5 * 60)
|
||||
|
||||
const smtp = SmtpService.getInstance()
|
||||
await smtp.initializeSmtpConfig()
|
||||
let sent = false
|
||||
try {
|
||||
sent = await smtp.renderAndSend(
|
||||
email,
|
||||
'verification.code',
|
||||
{
|
||||
name: name || '用户',
|
||||
email,
|
||||
code,
|
||||
expiresInMinutes: 5
|
||||
},
|
||||
ipAddress
|
||||
)
|
||||
} catch (error) {
|
||||
await delStoreIfValue(stateKey, storedValue)
|
||||
throw error
|
||||
}
|
||||
if (!sent) {
|
||||
await delStoreIfValue(stateKey, storedValue)
|
||||
throw createApiError(500, 'USER_CODE_SEND_FAILED', '验证码发送失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
if (getMethod(event) !== 'POST') {
|
||||
throw createApiError(405, 'HTTP_METHOD_NOT_ALLOWED', '方法不被允许')
|
||||
}
|
||||
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const emailRaw = (body?.email || '').toString().trim().toLowerCase()
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
if (!emailRaw || !emailRegex.test(emailRaw)) {
|
||||
throw createApiError(400, 'USER_INVALID_EMAIL', '请输入有效的邮箱地址')
|
||||
}
|
||||
|
||||
// 确认邮箱未被其他用户占用
|
||||
const existing = await db.select().from(users).where(eq(users.email, emailRaw)).limit(1)
|
||||
const existingUser = existing[0]
|
||||
if (existingUser && existingUser.id !== user.id) {
|
||||
throw createApiError(400, 'USER_EMAIL_TAKEN', '该邮箱已被其他用户绑定')
|
||||
}
|
||||
|
||||
// 写入/更新邮箱,标记未验证
|
||||
await db.update(users).set({ email: emailRaw, emailVerified: false }).where(eq(users.id, user.id))
|
||||
|
||||
// 获取客户端IP地址
|
||||
const clientIP = getClientIP(event)
|
||||
|
||||
// 发送邮件验证码
|
||||
await sendEmailVerificationCode(user.id, emailRaw, user.name, clientIP)
|
||||
|
||||
return { success: true, message: '验证码已发送,请查收邮箱' }
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查请求方法
|
||||
if (getMethod(event) !== 'POST') {
|
||||
throw createApiError(405, 'HTTP_METHOD_NOT_ALLOWED', '方法不被允许')
|
||||
}
|
||||
|
||||
// 检查用户认证
|
||||
const user = event.context.user
|
||||
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
try {
|
||||
// 解绑邮箱
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
email: null,
|
||||
emailVerified: false,
|
||||
emailVerifiedAt: null
|
||||
})
|
||||
.where(eq(users.id, user.id))
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: '邮箱已解绑'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解绑邮箱失败:', error)
|
||||
|
||||
throw createApiError(500, 'USER_EMAIL_UNBIND_FAILED', '解绑邮箱失败')
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { db } from '~/drizzle/db'
|
||||
import { users } from '~/drizzle/schema'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { getServerTimestamp } from '~~/server/utils/serverTime'
|
||||
import {
|
||||
delStore,
|
||||
delStoreIfValue,
|
||||
getStore,
|
||||
incrStore,
|
||||
parseStoreJson,
|
||||
verifyStateCode
|
||||
} from '~~/server/utils/captchaStore'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
if (getMethod(event) !== 'POST') {
|
||||
throw createApiError(405, 'HTTP_METHOD_NOT_ALLOWED', '方法不被允许')
|
||||
}
|
||||
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const email = (body?.email || '').toString().trim().toLowerCase()
|
||||
const code = (body?.code || '').toString().trim()
|
||||
|
||||
if (!email || !code) {
|
||||
throw createApiError(400, 'USER_EMAIL_AND_CODE_REQUIRED', '邮箱与验证码不能为空')
|
||||
}
|
||||
|
||||
const stateKey = `email-verify:${user.id}`
|
||||
const recordRaw = await getStore(stateKey)
|
||||
const record = parseStoreJson<{ email: string; codeHash: string; expiresAt: number }>(recordRaw)
|
||||
if (
|
||||
!record ||
|
||||
record.email !== email ||
|
||||
typeof record.codeHash !== 'string' ||
|
||||
!Number.isFinite(record.expiresAt)
|
||||
) {
|
||||
if (recordRaw) await delStoreIfValue(stateKey, recordRaw)
|
||||
throw createApiError(400, 'USER_SEND_CODE_FIRST', '请先发送验证码')
|
||||
}
|
||||
if (getServerTimestamp() > record.expiresAt) {
|
||||
await delStoreIfValue(stateKey, recordRaw!)
|
||||
throw createApiError(400, 'USER_CODE_EXPIRED_RESEND', '验证码已过期,请重新发送')
|
||||
}
|
||||
|
||||
const remainingTtl = Math.max(1, Math.ceil((record.expiresAt - getServerTimestamp()) / 1000))
|
||||
const attemptKey = `${stateKey}:attempts:${record.codeHash}`
|
||||
const attemptCount = await incrStore(attemptKey, remainingTtl)
|
||||
|
||||
if (attemptCount > 5) {
|
||||
await delStoreIfValue(stateKey, recordRaw!)
|
||||
await delStore(attemptKey)
|
||||
throw createApiError(400, 'USER_CODE_TOO_MANY_ATTEMPTS', '验证码错误次数过多,请重新发送')
|
||||
}
|
||||
|
||||
if (!verifyStateCode(stateKey, code, record.codeHash)) {
|
||||
if (attemptCount >= 5) {
|
||||
await delStoreIfValue(stateKey, recordRaw!)
|
||||
await delStore(attemptKey)
|
||||
throw createApiError(400, 'USER_CODE_TOO_MANY_ATTEMPTS', '验证码错误次数过多,请重新发送')
|
||||
}
|
||||
throw createApiError(400, 'USER_CODE_INVALID', '验证码错误')
|
||||
}
|
||||
|
||||
if (!(await delStoreIfValue(stateKey, recordRaw!))) {
|
||||
throw createApiError(400, 'USER_CODE_ALREADY_USED', '验证码已使用,请重新发送')
|
||||
}
|
||||
await delStore(attemptKey)
|
||||
|
||||
// 验证通过:设置邮箱为已验证
|
||||
const updatedUsers = await db
|
||||
.update(users)
|
||||
.set({ emailVerified: true })
|
||||
.where(and(eq(users.id, user.id), eq(users.email, email)))
|
||||
.returning({ id: users.id })
|
||||
|
||||
if (updatedUsers.length === 0) {
|
||||
throw createApiError(409, 'USER_EMAIL_CHANGED_RESEND', '邮箱已发生变化,请重新发送验证码')
|
||||
}
|
||||
|
||||
return { success: true, message: '邮箱验证成功' }
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { defineEventHandler, getQuery } from 'h3'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
import { SERVER_ERROR_CODES } from '~~/server/config/constants'
|
||||
import {
|
||||
isAuthSessionStorageError,
|
||||
revokeAuthSession,
|
||||
revokeOtherAuthSessions
|
||||
} from '~~/server/utils/auth-session'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) throw createApiError(401, 'AUTH_SESSION_EXPIRED', '请先登录')
|
||||
|
||||
const query = getQuery(event)
|
||||
const sessionId = typeof query.id === 'string' ? query.id : ''
|
||||
try {
|
||||
if (sessionId) {
|
||||
const revoked = await revokeAuthSession(user.id, sessionId, 'logout_single')
|
||||
if (!revoked) throw createApiError(400, 'COMMON_INVALID_PARAMS', '登录会话不存在或已失效')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
await revokeOtherAuthSessions(user.id, event.context.authSessionId || null)
|
||||
} catch (error) {
|
||||
if (!isAuthSessionStorageError(error)) throw error
|
||||
throw createApiError(
|
||||
503,
|
||||
SERVER_ERROR_CODES.AUTH_DATABASE_UNAVAILABLE,
|
||||
'登录会话存储暂时不可用,请稍后重试'
|
||||
)
|
||||
}
|
||||
return { success: true }
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { defineEventHandler, getQuery } from 'h3'
|
||||
import { and, authSessions, db, desc, eq } from '~/drizzle/db'
|
||||
import { isNull } from 'drizzle-orm'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
import { SERVER_ERROR_CODES } from '~~/server/config/constants'
|
||||
import { getServerDate } from '~~/server/utils/serverTime'
|
||||
import { isAuthSessionStorageError } from '~~/server/utils/auth-session'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) throw createApiError(401, 'AUTH_SESSION_EXPIRED', '请先登录')
|
||||
|
||||
const currentSessionId = event.context.authSessionId || String(getQuery(event).current || '')
|
||||
const now = getServerDate()
|
||||
let sessions: Array<typeof authSessions.$inferSelect>
|
||||
try {
|
||||
sessions = await db.query.authSessions.findMany({
|
||||
where: and(eq(authSessions.userId, user.id), isNull(authSessions.revokedAt)),
|
||||
orderBy: desc(authSessions.lastActiveAt)
|
||||
})
|
||||
} catch (error) {
|
||||
if (!isAuthSessionStorageError(error)) throw error
|
||||
throw createApiError(
|
||||
503,
|
||||
SERVER_ERROR_CODES.AUTH_DATABASE_UNAVAILABLE,
|
||||
'登录会话存储暂时不可用,请稍后重试'
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: sessions
|
||||
.filter((session) => session.expiresAt > now)
|
||||
.map((session) => ({
|
||||
id: session.id,
|
||||
current: session.id === currentSessionId,
|
||||
createdAt: session.createdAt,
|
||||
lastActiveAt: session.lastActiveAt,
|
||||
expiresAt: session.expiresAt,
|
||||
ipAddress: session.ipAddress,
|
||||
browser: session.browser,
|
||||
operatingSystem: session.operatingSystem,
|
||||
device: session.device,
|
||||
loginMethod: session.loginMethod
|
||||
}))
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
import { createError, defineEventHandler } from 'h3'
|
||||
import { db } from '~/drizzle/db'
|
||||
import { songs, votes } from '~/drizzle/schema'
|
||||
import { and, asc, count, desc, eq, gte, lt, sql } from 'drizzle-orm'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 检查用户是否登录
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_LOGIN_REQUIRED', '请先登录')
|
||||
}
|
||||
|
||||
const userId = user.id
|
||||
|
||||
// 筛选当前年份
|
||||
const currentYear = 2025
|
||||
const startOfYear = new Date(currentYear, 0, 1)
|
||||
const endOfYear = new Date(currentYear + 1, 0, 1)
|
||||
|
||||
try {
|
||||
// 1. 总投稿数
|
||||
const totalRequestsResult = await db
|
||||
.select({ count: count() })
|
||||
.from(songs)
|
||||
.where(
|
||||
and(
|
||||
eq(songs.requesterId, userId),
|
||||
gte(songs.createdAt, startOfYear),
|
||||
lt(songs.createdAt, endOfYear)
|
||||
)
|
||||
)
|
||||
const totalRequests = Number(totalRequestsResult[0].count)
|
||||
|
||||
// 2. 已播放投稿数
|
||||
const playedRequestsResult = await db
|
||||
.select({ count: count() })
|
||||
.from(songs)
|
||||
.where(
|
||||
and(
|
||||
eq(songs.requesterId, userId),
|
||||
eq(songs.played, true),
|
||||
gte(songs.createdAt, startOfYear),
|
||||
lt(songs.createdAt, endOfYear)
|
||||
)
|
||||
)
|
||||
const playedRequests = Number(playedRequestsResult[0].count)
|
||||
|
||||
// 3. 最喜欢的歌手
|
||||
const topArtistResult = await db
|
||||
.select({
|
||||
artist: songs.artist,
|
||||
count: count(songs.id)
|
||||
})
|
||||
.from(songs)
|
||||
.where(
|
||||
and(
|
||||
eq(songs.requesterId, userId),
|
||||
gte(songs.createdAt, startOfYear),
|
||||
lt(songs.createdAt, endOfYear)
|
||||
)
|
||||
)
|
||||
.groupBy(songs.artist)
|
||||
.orderBy(desc(count(songs.id)))
|
||||
.limit(1)
|
||||
const topArtist = topArtistResult.length > 0 ? topArtistResult[0].artist : null
|
||||
|
||||
// 4. 最常用的音乐平台
|
||||
const topPlatformResult = await db
|
||||
.select({
|
||||
platform: songs.musicPlatform,
|
||||
count: count(songs.id)
|
||||
})
|
||||
.from(songs)
|
||||
.where(
|
||||
and(
|
||||
eq(songs.requesterId, userId),
|
||||
gte(songs.createdAt, startOfYear),
|
||||
lt(songs.createdAt, endOfYear)
|
||||
)
|
||||
)
|
||||
.groupBy(songs.musicPlatform)
|
||||
.orderBy(desc(count(songs.id)))
|
||||
.limit(1)
|
||||
const topPlatform = topPlatformResult.length > 0 ? topPlatformResult[0].platform : null
|
||||
|
||||
// 5. 总投票数
|
||||
const totalVotesResult = await db
|
||||
.select({ count: count() })
|
||||
.from(votes)
|
||||
.where(
|
||||
and(
|
||||
eq(votes.userId, userId),
|
||||
gte(votes.createdAt, startOfYear),
|
||||
lt(votes.createdAt, endOfYear)
|
||||
)
|
||||
)
|
||||
const totalVotes = Number(totalVotesResult[0].count)
|
||||
|
||||
// 6. 最活跃月份
|
||||
let activeMonth = null
|
||||
try {
|
||||
const activeMonthResult = await db.execute(sql`
|
||||
SELECT EXTRACT(MONTH FROM "createdAt") as month, COUNT(*) as count
|
||||
FROM "Song"
|
||||
WHERE "requesterId" = ${userId}
|
||||
AND "createdAt" >= ${startOfYear.toISOString()}
|
||||
AND "createdAt" < ${endOfYear.toISOString()}
|
||||
GROUP BY month
|
||||
ORDER BY count DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
|
||||
if (activeMonthResult.length > 0) {
|
||||
activeMonth = Number(activeMonthResult[0].month)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[YearReview] Failed to get active month:', e)
|
||||
}
|
||||
|
||||
// 7. 年度第一首歌
|
||||
const firstSongResult = await db
|
||||
.select()
|
||||
.from(songs)
|
||||
.where(
|
||||
and(
|
||||
eq(songs.requesterId, userId),
|
||||
gte(songs.createdAt, startOfYear),
|
||||
lt(songs.createdAt, endOfYear)
|
||||
)
|
||||
)
|
||||
.orderBy(asc(songs.createdAt))
|
||||
.limit(1)
|
||||
const firstSong =
|
||||
firstSongResult.length > 0
|
||||
? {
|
||||
title: firstSongResult[0].title,
|
||||
artist: firstSongResult[0].artist,
|
||||
cover: firstSongResult[0].cover,
|
||||
createdAt: firstSongResult[0].createdAt
|
||||
}
|
||||
: null
|
||||
|
||||
const resultData = {
|
||||
year: currentYear,
|
||||
totalRequests,
|
||||
playedRequests,
|
||||
topArtist,
|
||||
topPlatform,
|
||||
totalVotes,
|
||||
activeMonth,
|
||||
firstSong
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: resultData
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching year review:', error)
|
||||
throw createApiError(500, 'USER_YEAR_REVIEW_FETCH_FAILED', '获取年度总结失败')
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user