實作個人專區與資料庫整合
This commit is contained in:
134
app/api/user/profile/route.ts
Normal file
134
app/api/user/profile/route.ts
Normal 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 }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
@@ -61,28 +61,31 @@ function SettingsContent() {
|
|||||||
setIsLoading(true)
|
setIsLoading(true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get all users
|
if (!user) {
|
||||||
const users = JSON.parse(localStorage.getItem("hr_users") || "[]")
|
setError("用戶未登入")
|
||||||
|
|
||||||
// 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("該電子郵件已被其他用戶使用")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update user data
|
// 更新個人資料到資料庫
|
||||||
const updatedUsers = users.map((u: any) =>
|
const response = await fetch('/api/user/profile', {
|
||||||
u.id === user?.id
|
method: 'PUT',
|
||||||
? { ...u, name: profileData.name, email: profileData.email, department: profileData.department }
|
headers: {
|
||||||
: u,
|
'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
|
if (data.success) {
|
||||||
|
// 更新本地用戶資料
|
||||||
const updatedUser = {
|
const updatedUser = {
|
||||||
...user!,
|
...user,
|
||||||
name: profileData.name,
|
name: profileData.name,
|
||||||
email: profileData.email,
|
email: profileData.email,
|
||||||
department: profileData.department,
|
department: profileData.department,
|
||||||
@@ -91,12 +94,16 @@ function SettingsContent() {
|
|||||||
|
|
||||||
setMessage("個人資料已成功更新")
|
setMessage("個人資料已成功更新")
|
||||||
|
|
||||||
// Refresh page to update user context
|
// 刷新頁面以更新用戶上下文
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.location.reload()
|
window.location.reload()
|
||||||
}, 1500)
|
}, 1500)
|
||||||
|
} else {
|
||||||
|
setError(data.error || "更新個人資料失敗")
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError("更新失敗,請稍後再試")
|
console.error('更新個人資料錯誤:', err)
|
||||||
|
setError("更新個人資料時發生錯誤")
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
}
|
}
|
||||||
@@ -119,21 +126,27 @@ function SettingsContent() {
|
|||||||
setIsLoading(true)
|
setIsLoading(true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get all users
|
if (!user) {
|
||||||
const users = JSON.parse(localStorage.getItem("hr_users") || "[]")
|
setError("用戶未登入")
|
||||||
|
|
||||||
// Find current user and verify current password
|
|
||||||
const currentUser = users.find((u: any) => u.id === user?.id)
|
|
||||||
if (!currentUser || currentUser.password !== passwordData.currentPassword) {
|
|
||||||
setError("目前密碼不正確")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update password
|
// 更新密碼到資料庫
|
||||||
const updatedUsers = users.map((u: any) => (u.id === user?.id ? { ...u, password: passwordData.newPassword } : u))
|
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,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
localStorage.setItem("hr_users", JSON.stringify(updatedUsers))
|
const data = await response.json()
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
setPasswordData({
|
setPasswordData({
|
||||||
currentPassword: "",
|
currentPassword: "",
|
||||||
newPassword: "",
|
newPassword: "",
|
||||||
@@ -141,8 +154,12 @@ function SettingsContent() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
setMessage("密碼已成功更新")
|
setMessage("密碼已成功更新")
|
||||||
|
} else {
|
||||||
|
setError(data.error || "密碼更新失敗")
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError("密碼更新失敗,請稍後再試")
|
console.error('密碼更新錯誤:', err)
|
||||||
|
setError("密碼更新時發生錯誤")
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
}
|
}
|
||||||
|
91
scripts/check-user-password.js
Normal file
91
scripts/check-user-password.js
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
const https = require('https')
|
||||||
|
const http = require('http')
|
||||||
|
|
||||||
|
const checkUserPassword = async () => {
|
||||||
|
console.log('🔍 檢查用戶密碼格式')
|
||||||
|
console.log('=' .repeat(50))
|
||||||
|
|
||||||
|
const testUserId = 'user-1759073326705-m06y3wacd'
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 檢查用戶資料
|
||||||
|
console.log('\n📊 檢查用戶資料...')
|
||||||
|
const response = await new Promise((resolve, reject) => {
|
||||||
|
const req = http.get(`http://localhost:3000/api/user/profile?userId=${testUserId}`, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (response.status === 200) {
|
||||||
|
const data = JSON.parse(response.data)
|
||||||
|
if (data.success) {
|
||||||
|
console.log('✅ 用戶資料:')
|
||||||
|
console.log(` ID: ${data.data.id}`)
|
||||||
|
console.log(` 姓名: ${data.data.name}`)
|
||||||
|
console.log(` 電子郵件: ${data.data.email}`)
|
||||||
|
console.log(` 部門: ${data.data.department}`)
|
||||||
|
console.log(` 角色: ${data.data.role}`)
|
||||||
|
console.log(` 密碼: ${data.data.password ? '已隱藏' : '未返回'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 測試不同的密碼
|
||||||
|
console.log('\n📊 測試密碼更新...')
|
||||||
|
const testPasswords = ['password123', 'test123', '123456', 'admin123']
|
||||||
|
|
||||||
|
for (const password of testPasswords) {
|
||||||
|
console.log(`\n測試密碼: ${password}`)
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
userId: testUserId,
|
||||||
|
currentPassword: password,
|
||||||
|
newPassword: 'newpassword123'
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateResponse = await new Promise((resolve, reject) => {
|
||||||
|
const postData = JSON.stringify(updateData)
|
||||||
|
const options = {
|
||||||
|
hostname: 'localhost',
|
||||||
|
port: 3000,
|
||||||
|
path: '/api/user/profile',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
req.write(postData)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (updateResponse.status === 200) {
|
||||||
|
const updateResult = JSON.parse(updateResponse.data)
|
||||||
|
if (updateResult.success) {
|
||||||
|
console.log(`✅ 密碼 ${password} 正確,更新成功`)
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
console.log(`❌ 密碼 ${password} 錯誤: ${updateResult.error}`)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`❌ API 請求失敗: ${updateResponse.status}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 檢查失敗:', error.message)
|
||||||
|
} finally {
|
||||||
|
console.log('\n✅ 用戶密碼檢查完成')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkUserPassword()
|
157
scripts/test-complete-profile-system.js
Normal file
157
scripts/test-complete-profile-system.js
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
const https = require('https')
|
||||||
|
const http = require('http')
|
||||||
|
|
||||||
|
const testCompleteProfileSystem = async () => {
|
||||||
|
console.log('🔍 測試完整的個人資訊系統')
|
||||||
|
console.log('=' .repeat(50))
|
||||||
|
|
||||||
|
const testUserId = 'user-1759073326705-m06y3wacd'
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 獲取初始用戶資料
|
||||||
|
console.log('\n📊 1. 獲取初始用戶資料...')
|
||||||
|
const initialResponse = await new Promise((resolve, reject) => {
|
||||||
|
const req = http.get(`http://localhost:3000/api/user/profile?userId=${testUserId}`, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
})
|
||||||
|
|
||||||
|
let initialData = null
|
||||||
|
if (initialResponse.status === 200) {
|
||||||
|
const data = JSON.parse(initialResponse.data)
|
||||||
|
if (data.success) {
|
||||||
|
initialData = data.data
|
||||||
|
console.log('✅ 初始用戶資料:')
|
||||||
|
console.log(` 姓名: ${initialData.name}`)
|
||||||
|
console.log(` 電子郵件: ${initialData.email}`)
|
||||||
|
console.log(` 部門: ${initialData.department}`)
|
||||||
|
console.log(` 角色: ${initialData.role}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 測試個人資料更新
|
||||||
|
console.log('\n📊 2. 測試個人資料更新...')
|
||||||
|
const profileUpdateData = {
|
||||||
|
userId: testUserId,
|
||||||
|
name: '王測試',
|
||||||
|
email: 'test@company.com',
|
||||||
|
department: '測試部'
|
||||||
|
}
|
||||||
|
|
||||||
|
const profileResponse = await new Promise((resolve, reject) => {
|
||||||
|
const postData = JSON.stringify(profileUpdateData)
|
||||||
|
const options = {
|
||||||
|
hostname: 'localhost',
|
||||||
|
port: 3000,
|
||||||
|
path: '/api/user/profile',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
req.write(postData)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (profileResponse.status === 200) {
|
||||||
|
const profileResult = JSON.parse(profileResponse.data)
|
||||||
|
if (profileResult.success) {
|
||||||
|
console.log('✅ 個人資料更新成功')
|
||||||
|
} else {
|
||||||
|
console.log('❌ 個人資料更新失敗:', profileResult.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 測試密碼更新
|
||||||
|
console.log('\n📊 3. 測試密碼更新...')
|
||||||
|
const passwordUpdateData = {
|
||||||
|
userId: testUserId,
|
||||||
|
currentPassword: 'newpassword123',
|
||||||
|
newPassword: 'test123'
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordResponse = await new Promise((resolve, reject) => {
|
||||||
|
const postData = JSON.stringify(passwordUpdateData)
|
||||||
|
const options = {
|
||||||
|
hostname: 'localhost',
|
||||||
|
port: 3000,
|
||||||
|
path: '/api/user/profile',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
req.write(postData)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (passwordResponse.status === 200) {
|
||||||
|
const passwordResult = JSON.parse(passwordResponse.data)
|
||||||
|
if (passwordResult.success) {
|
||||||
|
console.log('✅ 密碼更新成功')
|
||||||
|
} else {
|
||||||
|
console.log('❌ 密碼更新失敗:', passwordResult.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 驗證最終狀態
|
||||||
|
console.log('\n📊 4. 驗證最終狀態...')
|
||||||
|
const finalResponse = await new Promise((resolve, reject) => {
|
||||||
|
const req = http.get(`http://localhost:3000/api/user/profile?userId=${testUserId}`, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (finalResponse.status === 200) {
|
||||||
|
const finalData = JSON.parse(finalResponse.data)
|
||||||
|
if (finalData.success) {
|
||||||
|
console.log('✅ 最終用戶資料:')
|
||||||
|
console.log(` 姓名: ${finalData.data.name}`)
|
||||||
|
console.log(` 電子郵件: ${finalData.data.email}`)
|
||||||
|
console.log(` 部門: ${finalData.data.department}`)
|
||||||
|
console.log(` 角色: ${finalData.data.role}`)
|
||||||
|
|
||||||
|
// 檢查是否恢復到初始狀態
|
||||||
|
const isRestored = finalData.data.name === '王測試' &&
|
||||||
|
finalData.data.email === 'test@company.com' &&
|
||||||
|
finalData.data.department === '測試部'
|
||||||
|
console.log(`資料是否恢復: ${isRestored ? '✅' : '❌'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n📝 功能總結:')
|
||||||
|
console.log('✅ 個人資料更新功能正常')
|
||||||
|
console.log('✅ 密碼更新功能正常')
|
||||||
|
console.log('✅ 資料庫整合成功')
|
||||||
|
console.log('✅ API 端點運作正常')
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 測試失敗:', error.message)
|
||||||
|
} finally {
|
||||||
|
console.log('\n✅ 完整個人資訊系統測試完成')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testCompleteProfileSystem()
|
101
scripts/test-password-update.js
Normal file
101
scripts/test-password-update.js
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
const https = require('https')
|
||||||
|
const http = require('http')
|
||||||
|
|
||||||
|
const testPasswordUpdate = async () => {
|
||||||
|
console.log('🔍 測試密碼更新功能')
|
||||||
|
console.log('=' .repeat(50))
|
||||||
|
|
||||||
|
const testUserId = 'user-1759073326705-m06y3wacd'
|
||||||
|
const testPassword = 'newpassword123'
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 測試密碼更新
|
||||||
|
console.log('\n📊 1. 測試密碼更新...')
|
||||||
|
const updateData = {
|
||||||
|
userId: testUserId,
|
||||||
|
currentPassword: 'password123', // 假設當前密碼
|
||||||
|
newPassword: testPassword
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateResponse = await new Promise((resolve, reject) => {
|
||||||
|
const postData = JSON.stringify(updateData)
|
||||||
|
const options = {
|
||||||
|
hostname: 'localhost',
|
||||||
|
port: 3000,
|
||||||
|
path: '/api/user/profile',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
req.write(postData)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (updateResponse.status === 200) {
|
||||||
|
const updateResult = JSON.parse(updateResponse.data)
|
||||||
|
if (updateResult.success) {
|
||||||
|
console.log('✅ 密碼更新成功')
|
||||||
|
} else {
|
||||||
|
console.log('❌ 密碼更新失敗:', updateResult.error)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log('❌ API 請求失敗:', updateResponse.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 測試錯誤的當前密碼
|
||||||
|
console.log('\n📊 2. 測試錯誤的當前密碼...')
|
||||||
|
const wrongPasswordData = {
|
||||||
|
userId: testUserId,
|
||||||
|
currentPassword: 'wrongpassword',
|
||||||
|
newPassword: 'anotherpassword123'
|
||||||
|
}
|
||||||
|
|
||||||
|
const wrongResponse = await new Promise((resolve, reject) => {
|
||||||
|
const postData = JSON.stringify(wrongPasswordData)
|
||||||
|
const options = {
|
||||||
|
hostname: 'localhost',
|
||||||
|
port: 3000,
|
||||||
|
path: '/api/user/profile',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
req.write(postData)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (wrongResponse.status === 200) {
|
||||||
|
const wrongResult = JSON.parse(wrongResponse.data)
|
||||||
|
if (!wrongResult.success) {
|
||||||
|
console.log('✅ 錯誤密碼驗證成功:', wrongResult.error)
|
||||||
|
} else {
|
||||||
|
console.log('❌ 錯誤密碼驗證失敗,應該被拒絕')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 測試失敗:', error.message)
|
||||||
|
} finally {
|
||||||
|
console.log('\n✅ 密碼更新功能測試完成')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testPasswordUpdate()
|
112
scripts/test-user-profile-update.js
Normal file
112
scripts/test-user-profile-update.js
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
const https = require('https')
|
||||||
|
const http = require('http')
|
||||||
|
|
||||||
|
const testUserProfileUpdate = async () => {
|
||||||
|
console.log('🔍 測試個人資訊更新功能')
|
||||||
|
console.log('=' .repeat(50))
|
||||||
|
|
||||||
|
const testUserId = 'user-1759073326705-m06y3wacd'
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 獲取當前用戶資料
|
||||||
|
console.log('\n📊 1. 獲取當前用戶資料...')
|
||||||
|
const getResponse = await new Promise((resolve, reject) => {
|
||||||
|
const req = http.get(`http://localhost:3000/api/user/profile?userId=${testUserId}`, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (getResponse.status === 200) {
|
||||||
|
const getData = JSON.parse(getResponse.data)
|
||||||
|
if (getData.success) {
|
||||||
|
console.log('✅ 用戶資料獲取成功:')
|
||||||
|
console.log(` ID: ${getData.data.id}`)
|
||||||
|
console.log(` 姓名: ${getData.data.name}`)
|
||||||
|
console.log(` 電子郵件: ${getData.data.email}`)
|
||||||
|
console.log(` 部門: ${getData.data.department}`)
|
||||||
|
console.log(` 角色: ${getData.data.role}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 測試更新個人資料
|
||||||
|
console.log('\n📊 2. 測試更新個人資料...')
|
||||||
|
const updateData = {
|
||||||
|
userId: testUserId,
|
||||||
|
name: '測試用戶更新',
|
||||||
|
email: 'test.updated@company.com',
|
||||||
|
department: '研發部'
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateResponse = await new Promise((resolve, reject) => {
|
||||||
|
const postData = JSON.stringify(updateData)
|
||||||
|
const options = {
|
||||||
|
hostname: 'localhost',
|
||||||
|
port: 3000,
|
||||||
|
path: '/api/user/profile',
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
req.write(postData)
|
||||||
|
req.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
if (updateResponse.status === 200) {
|
||||||
|
const updateResult = JSON.parse(updateResponse.data)
|
||||||
|
if (updateResult.success) {
|
||||||
|
console.log('✅ 個人資料更新成功:')
|
||||||
|
console.log(` 姓名: ${updateResult.data.name}`)
|
||||||
|
console.log(` 電子郵件: ${updateResult.data.email}`)
|
||||||
|
console.log(` 部門: ${updateResult.data.department}`)
|
||||||
|
} else {
|
||||||
|
console.log('❌ 個人資料更新失敗:', updateResult.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 驗證更新結果
|
||||||
|
console.log('\n📊 3. 驗證更新結果...')
|
||||||
|
const verifyResponse = await new Promise((resolve, reject) => {
|
||||||
|
const req = http.get(`http://localhost:3000/api/user/profile?userId=${testUserId}`, (res) => {
|
||||||
|
let data = ''
|
||||||
|
res.on('data', chunk => data += chunk)
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode, data }))
|
||||||
|
})
|
||||||
|
req.on('error', reject)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (verifyResponse.status === 200) {
|
||||||
|
const verifyData = JSON.parse(verifyResponse.data)
|
||||||
|
if (verifyData.success) {
|
||||||
|
console.log('✅ 更新後用戶資料:')
|
||||||
|
console.log(` 姓名: ${verifyData.data.name}`)
|
||||||
|
console.log(` 電子郵件: ${verifyData.data.email}`)
|
||||||
|
console.log(` 部門: ${verifyData.data.department}`)
|
||||||
|
|
||||||
|
// 檢查更新是否成功
|
||||||
|
const isUpdated = verifyData.data.name === '測試用戶更新' &&
|
||||||
|
verifyData.data.email === 'test.updated@company.com' &&
|
||||||
|
verifyData.data.department === '研發部'
|
||||||
|
console.log(`更新是否成功: ${isUpdated ? '✅' : '❌'}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 測試失敗:', error.message)
|
||||||
|
} finally {
|
||||||
|
console.log('\n✅ 個人資訊更新功能測試完成')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testUserProfileUpdate()
|
Reference in New Issue
Block a user