71 lines
1.7 KiB
TypeScript
71 lines
1.7 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { hashPassword } from '@/lib/auth'
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const { email, username, password, name, phone, address } = await request.json()
|
|
|
|
if (!email || !username || !password) {
|
|
return NextResponse.json(
|
|
{ message: '邮箱、用户名和密码不能为空' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 检查邮箱是否已存在
|
|
const existingUserByEmail = await prisma.user.findUnique({
|
|
where: { email }
|
|
})
|
|
|
|
if (existingUserByEmail) {
|
|
return NextResponse.json(
|
|
{ message: '该邮箱已被注册' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 检查用户名是否已存在
|
|
const existingUserByUsername = await prisma.user.findUnique({
|
|
where: { username }
|
|
})
|
|
|
|
if (existingUserByUsername) {
|
|
return NextResponse.json(
|
|
{ message: '该用户名已被使用' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 加密密码
|
|
const hashedPassword = await hashPassword(password)
|
|
|
|
// 创建用户
|
|
const user = await prisma.user.create({
|
|
data: {
|
|
email,
|
|
username,
|
|
password: hashedPassword,
|
|
name: name || null,
|
|
phone: phone || null,
|
|
address: address || null,
|
|
isAdmin: false
|
|
}
|
|
})
|
|
|
|
// 返回用户信息(不包含密码)
|
|
const { password: _, ...userWithoutPassword } = user
|
|
|
|
return NextResponse.json({
|
|
message: '注册成功',
|
|
user: userWithoutPassword
|
|
}, { status: 201 })
|
|
} catch (error) {
|
|
console.error('Register error:', error)
|
|
return NextResponse.json(
|
|
{ message: '服务器错误' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|