Files
ai-showcase-platform/app/api/auth/register/route.ts

70 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import { v4 as uuidv4 } from 'uuid'
import { UserService } from '@/lib/services/database-service'
const userService = new UserService()
export async function POST(request: NextRequest) {
try {
const { name, email, password, department, role = 'user' } = await request.json()
if (!name || !email || !password || !department) {
return NextResponse.json(
{ error: '請填寫所有必填欄位' },
{ status: 400 }
)
}
if (password.length < 6) {
return NextResponse.json(
{ error: '密碼長度至少需要 6 個字符' },
{ status: 400 }
)
}
// 檢查用戶是否已存在
const existingUser = await userService.findByEmail(email)
if (existingUser) {
return NextResponse.json(
{ error: '該電子郵件已被註冊' },
{ status: 409 }
)
}
// 加密密碼
const saltRounds = 12
const password_hash = await bcrypt.hash(password, saltRounds)
// 創建新用戶
const newUser = {
id: uuidv4(),
name,
email,
password_hash,
department,
role: role as 'user' | 'developer' | 'admin',
join_date: new Date().toISOString().split('T')[0],
total_likes: 0,
total_views: 0,
is_active: true
}
const createdUser = await userService.create(newUser)
// 返回用戶信息(不包含密碼)
const { password_hash: _, ...userWithoutPassword } = createdUser
return NextResponse.json({
success: true,
user: userWithoutPassword
})
} catch (error) {
console.error('註冊錯誤:', error)
return NextResponse.json(
{ error: '註冊過程中發生錯誤' },
{ status: 500 }
)
}
}