fix set password

This commit is contained in:
songtianlun 2025-09-01 23:39:32 +08:00
parent fb2fb08eae
commit 21bf7add36
2 changed files with 95 additions and 12 deletions

View File

@ -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 }
);
}
}

View File

@ -3,7 +3,6 @@
import { useState, useEffect, useCallback } from 'react' import { useState, useEffect, useCallback } from 'react'
import { useTranslations } from 'next-intl' import { useTranslations } from 'next-intl'
import { useBetterAuth } from '@/hooks/useBetterAuth' import { useBetterAuth } from '@/hooks/useBetterAuth'
import { changePassword } from '@/lib/auth-client'
import { Header } from '@/components/layout/Header' import { Header } from '@/components/layout/Header'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
@ -67,13 +66,11 @@ export default function ProfilePage() {
username: '', username: '',
email: '', email: '',
bio: '', bio: '',
currentPassword: '',
newPassword: '', newPassword: '',
confirmPassword: '', confirmPassword: '',
versionLimit: 3 versionLimit: 3
}) })
const [showPasswords, setShowPasswords] = useState({ const [showPasswords, setShowPasswords] = useState({
current: false,
new: false, new: false,
confirm: false confirm: false
}) })
@ -106,7 +103,6 @@ export default function ProfilePage() {
username: profileData.name || '', // 直接使用name字段 username: profileData.name || '', // 直接使用name字段
email: profileData.email, email: profileData.email,
bio: profileData.bio || '', bio: profileData.bio || '',
currentPassword: '',
newPassword: '', newPassword: '',
confirmPassword: '', confirmPassword: '',
versionLimit: profileData.versionLimit versionLimit: profileData.versionLimit
@ -194,19 +190,40 @@ export default function ProfilePage() {
setSaveStatus({ type: null, message: '' }) setSaveStatus({ type: null, message: '' })
try { try {
// 使用Better Auth的changePassword方法 // 使用自定义API来设置密码只需要新密码
const { data, error } = await changePassword({ const response = await fetch('/api/auth/set-password', {
newPassword: formData.newPassword, method: 'POST',
currentPassword: formData.currentPassword, headers: {
revokeOtherSessions: false, // 保持其他会话不被撤销 'Content-Type': 'application/json',
},
body: JSON.stringify({
newPassword: formData.newPassword
})
}) })
if (error) { if (!response.ok) {
throw new Error(error.message || 'Failed to change password') 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') }) setSaveStatus({ type: 'success', message: t('passwordUpdatedSuccessfully') })
setFormData({ ...formData, currentPassword: '', newPassword: '', confirmPassword: '' }) setFormData({ ...formData, newPassword: '', confirmPassword: '' })
} catch (error: unknown) { } catch (error: unknown) {
setSaveStatus({ type: 'error', message: (error instanceof Error ? error.message : 'Unknown error') || t('failedToUpdatePassword') }) setSaveStatus({ type: 'error', message: (error instanceof Error ? error.message : 'Unknown error') || t('failedToUpdatePassword') })