整合資料庫、完成登入註冊忘記密碼功能

This commit is contained in:
2025-09-09 12:00:22 +08:00
parent af88c0f037
commit 32b19e9a0f
85 changed files with 11672 additions and 2350 deletions

View File

@@ -0,0 +1,103 @@
import { NextRequest, NextResponse } from 'next/server'
import { UserService } from '@/lib/services/database-service'
const userService = new UserService()
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const user = await userService.findById(params.id)
if (!user) {
return NextResponse.json(
{ error: '用戶不存在' },
{ status: 404 }
)
}
// 獲取用戶統計
const stats = await userService.getUserStatistics(params.id)
return NextResponse.json({
success: true,
data: {
user,
stats
}
})
} catch (error) {
console.error('獲取用戶詳情錯誤:', error)
return NextResponse.json(
{ error: '獲取用戶詳情時發生錯誤' },
{ status: 500 }
)
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const updates = await request.json()
// 移除不允許更新的欄位
delete updates.id
delete updates.created_at
delete updates.password_hash
const updatedUser = await userService.update(params.id, updates)
if (!updatedUser) {
return NextResponse.json(
{ error: '用戶不存在或更新失敗' },
{ status: 404 }
)
}
return NextResponse.json({
success: true,
message: '用戶資料已更新',
data: updatedUser
})
} catch (error) {
console.error('更新用戶錯誤:', error)
return NextResponse.json(
{ error: '更新用戶時發生錯誤' },
{ status: 500 }
)
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
// 軟刪除:將 is_active 設為 false
const result = await userService.update(params.id, { is_active: false })
if (!result) {
return NextResponse.json(
{ error: '用戶不存在或刪除失敗' },
{ status: 404 }
)
}
return NextResponse.json({
success: true,
message: '用戶已刪除'
})
} catch (error) {
console.error('刪除用戶錯誤:', error)
return NextResponse.json(
{ error: '刪除用戶時發生錯誤' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,134 @@
import { NextRequest, NextResponse } from 'next/server'
import { UserService } from '@/lib/services/database-service'
const userService = new UserService()
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const page = parseInt(searchParams.get('page') || '1')
const limit = parseInt(searchParams.get('limit') || '10')
const search = searchParams.get('search') || ''
const department = searchParams.get('department') || ''
const role = searchParams.get('role') || ''
const status = searchParams.get('status') || ''
// 構建查詢條件
let whereConditions = ['is_active = TRUE']
let params: any[] = []
if (search) {
whereConditions.push('(name LIKE ? OR email LIKE ?)')
params.push(`%${search}%`, `%${search}%`)
}
if (department && department !== 'all') {
whereConditions.push('department = ?')
params.push(department)
}
if (role && role !== 'all') {
whereConditions.push('role = ?')
params.push(role)
}
if (status && status !== 'all') {
if (status === 'active') {
whereConditions.push('last_login IS NOT NULL AND last_login >= DATE_SUB(NOW(), INTERVAL 30 DAY)')
} else if (status === 'inactive') {
whereConditions.push('last_login IS NULL OR last_login < DATE_SUB(NOW(), INTERVAL 30 DAY)')
}
}
const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : ''
// 使用 UserService 的方法
const { users, total } = await userService.findAll({
search,
department,
role,
status,
page,
limit
})
const stats = await userService.getUserStats()
return NextResponse.json({
success: true,
data: {
users,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit)
},
stats: {
totalUsers: stats?.total_users || 0,
activeUsers: stats?.active_users || 0,
adminCount: stats?.admin_count || 0,
developerCount: stats?.developer_count || 0,
inactiveUsers: stats?.inactive_users || 0,
newThisMonth: stats?.new_this_month || 0
}
}
})
} catch (error) {
console.error('獲取用戶列表錯誤:', error)
return NextResponse.json(
{ error: '獲取用戶列表時發生錯誤' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const { email, role } = await request.json()
if (!email || !role) {
return NextResponse.json(
{ error: '請提供電子郵件和角色' },
{ status: 400 }
)
}
// 檢查郵箱是否已存在
const existingUser = await userService.findByEmail(email)
if (existingUser) {
return NextResponse.json(
{ error: '該電子郵件地址已被使用' },
{ status: 400 }
)
}
// 生成邀請 token
const { v4: uuidv4 } = require('uuid')
const invitationToken = uuidv4()
// 創建邀請記錄(這裡可以存儲到邀請表或臨時表)
// 暫時返回邀請連結
const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
const invitationLink = `${baseUrl}/register?token=${invitationToken}&email=${encodeURIComponent(email)}&role=${encodeURIComponent(role)}`
return NextResponse.json({
success: true,
message: '用戶邀請已創建',
data: {
invitationLink,
token: invitationToken,
email,
role
}
})
} catch (error) {
console.error('創建用戶邀請錯誤:', error)
return NextResponse.json(
{ error: '創建用戶邀請時發生錯誤' },
{ status: 500 }
)
}
}