diff --git a/src/app/api/auth/set-password/route.ts b/src/app/api/auth/set-password/route.ts new file mode 100644 index 0000000..685bd90 --- /dev/null +++ b/src/app/api/auth/set-password/route.ts @@ -0,0 +1,66 @@ +import { NextRequest, NextResponse } from "next/server"; +import { auth } from "@/lib/auth"; +import { headers } from "next/headers"; + +export async function POST(request: NextRequest) { + try { + const session = await auth.api.getSession({ + headers: await headers() + }); + + if (!session?.user) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const { newPassword } = await request.json(); + + if (!newPassword || newPassword.length < 6) { + return NextResponse.json( + { error: "Password must be at least 6 characters long" }, + { status: 400 } + ); + } + + // 使用 Better Auth 的 setPassword API + try { + const result = await auth.api.setPassword({ + body: { + newPassword: newPassword + }, + headers: await headers() + }); + + console.log("Better Auth setPassword result:", result); + + return NextResponse.json({ + success: true, + message: "Password set successfully", + data: result + }); + } catch (authError: unknown) { + console.error("Better Auth setPassword error:", authError); + + const errorMessage = authError instanceof Error ? authError.message : 'Unknown auth error'; + + // 如果是因为用户已有密码,建议使用 changePassword + if (errorMessage.includes("already has a password")) { + return NextResponse.json( + { error: "User already has a password. Please use the change password functionality." }, + { status: 409 } + ); + } + + return NextResponse.json( + { error: errorMessage || "Failed to set password" }, + { status: 400 } + ); + } + + } catch (error: unknown) { + console.error("Error setting password:", error); + return NextResponse.json( + { error: "Internal server error" }, + { status: 500 } + ); + } +} \ No newline at end of file diff --git a/src/app/profile/page.tsx b/src/app/profile/page.tsx index 5bc7586..69aeaf7 100644 --- a/src/app/profile/page.tsx +++ b/src/app/profile/page.tsx @@ -3,7 +3,6 @@ import { useState, useEffect, useCallback } from 'react' import { useTranslations } from 'next-intl' import { useBetterAuth } from '@/hooks/useBetterAuth' -import { changePassword } from '@/lib/auth-client' import { Header } from '@/components/layout/Header' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -67,13 +66,11 @@ export default function ProfilePage() { username: '', email: '', bio: '', - currentPassword: '', newPassword: '', confirmPassword: '', versionLimit: 3 }) const [showPasswords, setShowPasswords] = useState({ - current: false, new: false, confirm: false }) @@ -106,7 +103,6 @@ export default function ProfilePage() { username: profileData.name || '', // 直接使用name字段 email: profileData.email, bio: profileData.bio || '', - currentPassword: '', newPassword: '', confirmPassword: '', versionLimit: profileData.versionLimit @@ -194,19 +190,40 @@ export default function ProfilePage() { setSaveStatus({ type: null, message: '' }) try { - // 使用Better Auth的changePassword方法 - const { data, error } = await changePassword({ - newPassword: formData.newPassword, - currentPassword: formData.currentPassword, - revokeOtherSessions: false, // 保持其他会话不被撤销 + // 使用自定义API来设置密码(只需要新密码) + const response = await fetch('/api/auth/set-password', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + newPassword: formData.newPassword + }) }) - if (error) { - throw new Error(error.message || 'Failed to change password') + if (!response.ok) { + let errorMessage = 'Failed to set password' + try { + const errorData = await response.json() + errorMessage = errorData.error || errorMessage + } catch { + // 如果响应不是JSON格式,使用状态码信息 + errorMessage = `HTTP ${response.status}: ${response.statusText}` + } + throw new Error(errorMessage) + } + + // 尝试解析成功响应 + try { + const result = await response.json() + console.log('Password set successfully:', result) + } catch { + // 即使解析失败,如果状态码是成功的,仍然认为操作成功 + console.log('Password set successfully (no JSON response)') } setSaveStatus({ type: 'success', message: t('passwordUpdatedSuccessfully') }) - setFormData({ ...formData, currentPassword: '', newPassword: '', confirmPassword: '' }) + setFormData({ ...formData, newPassword: '', confirmPassword: '' }) } catch (error: unknown) { setSaveStatus({ type: 'error', message: (error instanceof Error ? error.message : 'Unknown error') || t('failedToUpdatePassword') })