實作個人專區與資料庫整合

This commit is contained in:
2025-09-29 17:58:58 +08:00
parent a76b72274b
commit b45cad81bf
6 changed files with 659 additions and 47 deletions

View File

@@ -0,0 +1,134 @@
import { NextRequest, NextResponse } from 'next/server'
import { updateUser, findUserById } from '@/lib/database/models/user'
import { verifyPassword, hashPassword } from '@/lib/utils/password'
export async function PUT(request: NextRequest) {
try {
const body = await request.json()
const { userId, name, email, department, currentPassword, newPassword } = body
// 驗證必要欄位
if (!userId) {
return NextResponse.json(
{ success: false, error: '缺少用戶ID' },
{ status: 400 }
)
}
// 獲取當前用戶資料
const currentUser = await findUserById(userId)
if (!currentUser) {
return NextResponse.json(
{ success: false, error: '用戶不存在' },
{ status: 404 }
)
}
// 準備更新資料
const updateData: any = {}
// 更新基本資料
if (name !== undefined) updateData.name = name
if (email !== undefined) updateData.email = email
if (department !== undefined) updateData.department = department
// 如果要更新密碼,需要驗證當前密碼
if (newPassword) {
if (!currentPassword) {
return NextResponse.json(
{ success: false, error: '請提供當前密碼' },
{ status: 400 }
)
}
// 驗證當前密碼
const isCurrentPasswordValid = await verifyPassword(currentPassword, currentUser.password)
if (!isCurrentPasswordValid) {
return NextResponse.json(
{ success: false, error: '當前密碼不正確' },
{ status: 400 }
)
}
// 加密新密碼
updateData.password = await hashPassword(newPassword)
}
// 檢查是否有資料需要更新
if (Object.keys(updateData).length === 0) {
return NextResponse.json(
{ success: false, error: '沒有資料需要更新' },
{ status: 400 }
)
}
// 更新用戶資料
const updatedUser = await updateUser(userId, updateData)
if (!updatedUser) {
return NextResponse.json(
{ success: false, error: '更新用戶資料失敗' },
{ status: 500 }
)
}
// 返回更新後的用戶資料(不包含密碼)
const { password, ...userWithoutPassword } = updatedUser
return NextResponse.json({
success: true,
data: userWithoutPassword
})
} catch (error) {
console.error('更新用戶資料失敗:', error)
return NextResponse.json(
{
success: false,
error: '伺服器錯誤',
details: error instanceof Error ? error.message : '未知錯誤'
},
{ status: 500 }
)
}
}
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const userId = searchParams.get('userId')
if (!userId) {
return NextResponse.json(
{ success: false, error: '缺少用戶ID' },
{ status: 400 }
)
}
const user = await findUserById(userId)
if (!user) {
return NextResponse.json(
{ success: false, error: '用戶不存在' },
{ status: 404 }
)
}
// 返回用戶資料(不包含密碼)
const { password, ...userWithoutPassword } = user
return NextResponse.json({
success: true,
data: userWithoutPassword
})
} catch (error) {
console.error('獲取用戶資料失敗:', error)
return NextResponse.json(
{
success: false,
error: '伺服器錯誤',
details: error instanceof Error ? error.message : '未知錯誤'
},
{ status: 500 }
)
}
}

View File

@@ -61,42 +61,49 @@ function SettingsContent() {
setIsLoading(true)
try {
// Get all users
const users = JSON.parse(localStorage.getItem("hr_users") || "[]")
// Check if email is already taken by another user
const emailExists = users.some((u: any) => u.email === profileData.email && u.id !== user?.id)
if (emailExists) {
setError("該電子郵件已被其他用戶使用")
if (!user) {
setError("用戶未登入")
return
}
// Update user data
const updatedUsers = users.map((u: any) =>
u.id === user?.id
? { ...u, name: profileData.name, email: profileData.email, department: profileData.department }
: u,
)
// 更新個人資料到資料庫
const response = await fetch('/api/user/profile', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: user.id,
name: profileData.name,
email: profileData.email,
department: profileData.department,
}),
})
localStorage.setItem("hr_users", JSON.stringify(updatedUsers))
const data = await response.json()
// Update current user session
const updatedUser = {
...user!,
name: profileData.name,
email: profileData.email,
department: profileData.department,
if (data.success) {
// 更新本地用戶資料
const updatedUser = {
...user,
name: profileData.name,
email: profileData.email,
department: profileData.department,
}
localStorage.setItem("hr_current_user", JSON.stringify(updatedUser))
setMessage("個人資料已成功更新")
// 刷新頁面以更新用戶上下文
setTimeout(() => {
window.location.reload()
}, 1500)
} else {
setError(data.error || "更新個人資料失敗")
}
localStorage.setItem("hr_current_user", JSON.stringify(updatedUser))
setMessage("個人資料已成功更新")
// Refresh page to update user context
setTimeout(() => {
window.location.reload()
}, 1500)
} catch (err) {
setError("更新失敗,請稍後再試")
console.error('更新個人資料錯誤:', err)
setError("更新個人資料時發生錯誤")
} finally {
setIsLoading(false)
}
@@ -119,30 +126,40 @@ function SettingsContent() {
setIsLoading(true)
try {
// Get all users
const users = JSON.parse(localStorage.getItem("hr_users") || "[]")
// Find current user and verify current password
const currentUser = users.find((u: any) => u.id === user?.id)
if (!currentUser || currentUser.password !== passwordData.currentPassword) {
setError("目前密碼不正確")
if (!user) {
setError("用戶未登入")
return
}
// Update password
const updatedUsers = users.map((u: any) => (u.id === user?.id ? { ...u, password: passwordData.newPassword } : u))
localStorage.setItem("hr_users", JSON.stringify(updatedUsers))
setPasswordData({
currentPassword: "",
newPassword: "",
confirmPassword: "",
// 更新密碼到資料庫
const response = await fetch('/api/user/profile', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId: user.id,
currentPassword: passwordData.currentPassword,
newPassword: passwordData.newPassword,
}),
})
setMessage("密碼已成功更新")
const data = await response.json()
if (data.success) {
setPasswordData({
currentPassword: "",
newPassword: "",
confirmPassword: "",
})
setMessage("密碼已成功更新")
} else {
setError(data.error || "密碼更新失敗")
}
} catch (err) {
setError("密碼更新失敗,請稍後再試")
console.error('密碼更新錯誤:', err)
setError("密碼更新時發生錯誤")
} finally {
setIsLoading(false)
}