54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import bcrypt from 'bcryptjs'
|
|
import { UserService } from '@/lib/services/database-service'
|
|
|
|
const userService = new UserService()
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const { email, password } = await request.json()
|
|
|
|
if (!email || !password) {
|
|
return NextResponse.json(
|
|
{ error: '請提供電子郵件和密碼' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 查找用戶
|
|
const user = await userService.findByEmail(email)
|
|
if (!user) {
|
|
return NextResponse.json(
|
|
{ error: '用戶不存在' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
// 驗證密碼
|
|
const isValidPassword = await bcrypt.compare(password, user.password_hash)
|
|
if (!isValidPassword) {
|
|
return NextResponse.json(
|
|
{ error: '密碼錯誤' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
// 更新最後登入時間
|
|
await userService.updateLastLogin(user.id)
|
|
|
|
// 返回用戶信息(不包含密碼)
|
|
const { password_hash, ...userWithoutPassword } = user
|
|
return NextResponse.json({
|
|
success: true,
|
|
user: userWithoutPassword
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('登入錯誤:', error)
|
|
return NextResponse.json(
|
|
{ error: '登入過程中發生錯誤' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|