expo-popcore-app/hooks/use-change-password.ts

74 lines
1.9 KiB
TypeScript

import { useState } from 'react'
import { authClient } from '@/lib/auth'
import { handleError } from './use-error'
import { type ApiError } from '@/lib/types'
export interface ChangePasswordParams {
oldPassword: string
newPassword: string
confirmPassword?: string
}
export interface ChangePasswordResult {
changePassword: (params: ChangePasswordParams) => Promise<void>
loading: boolean
error: ApiError | null
}
export const useChangePassword = (): ChangePasswordResult => {
const [loading, setLoading] = useState<boolean>(false)
const [error, setError] = useState<ApiError | null>(null)
const changePassword = async (params: ChangePasswordParams) => {
const { oldPassword, newPassword, confirmPassword } = params
// 客户端验证
if (!oldPassword) {
setError({ message: '旧密码不能为空', status: 400, statusText: 'Bad Request' })
return
}
if (newPassword.length < 6) {
setError({ message: '新密码长度至少为6位', status: 400, statusText: 'Bad Request' })
return
}
if (oldPassword === newPassword) {
setError({ message: '新密码不能与当前密码相同', status: 400, statusText: 'Bad Request' })
return
}
if (confirmPassword !== undefined && newPassword !== confirmPassword) {
setError({ message: '新密码和确认密码不一致', status: 400, statusText: 'Bad Request' })
return
}
try {
setLoading(true)
setError(null)
const result = await handleError(async () => {
return await authClient.changePassword({
currentPassword: oldPassword,
newPassword,
revokeOtherSessions: true,
})
})
if (result.error) {
setError(result.error)
}
} catch (e) {
setError(e as ApiError)
} finally {
setLoading(false)
}
}
return {
changePassword,
loading,
error,
}
}