Line data Source code
1 : import { FirebaseError } from 'firebase/app'
2 : import { AuthErrorCodes } from 'firebase/auth'
3 :
4 : import { useToast } from '@/components/ui/toast/toastStore'
5 : import { useAuthActions } from '@/composables/auth/useAuthActions'
6 : import { useErrorHandling } from '@/composables/useErrorHandling'
7 : import type { ErrorRecoveryStrategy } from '@/composables/useErrorHandling'
8 : import { t } from '@/i18n'
9 : import { useDialogService } from '@/services/dialogService'
10 : import { useAuthStore } from '@/stores/authStore'
11 :
12 : /**
13 : * Password update with recovery from Firebase auth/requires-recent-login:
14 : * the user is asked to confirm, signed out, sent through `requestSignIn`,
15 : * and the update is retried after a successful sign-in.
16 : */
17 1 : export function useUpdatePassword(requestSignIn: () => Promise<boolean>) {
18 1 : const authStore = useAuthStore()
19 1 : const toast = useToast()
20 1 : const dialogService = useDialogService()
21 1 : const { wrapWithErrorHandlingAsync } = useErrorHandling()
22 1 : const { reportError } = useAuthActions()
23 :
24 : const reauthenticationRecovery: ErrorRecoveryStrategy<[string], void> = {
25 : shouldHandle: (error: unknown) =>
26 : error instanceof FirebaseError &&
27 : error.code === AuthErrorCodes.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,
28 :
29 : recover: async (_error, retry, args) => {
30 : const confirmed = await dialogService.confirm({
31 : title: t('auth.reauthRequired.title'),
32 : message: t('auth.reauthRequired.message'),
33 : type: 'default'
34 : })
35 :
36 0 : if (!confirmed) {
37 0 : return
38 : }
39 :
40 0 : await authStore.logout()
41 :
42 0 : if (await requestSignIn()) {
43 0 : await retry(...args)
44 : }
45 : }
46 : }
47 :
48 1 : return wrapWithErrorHandlingAsync(
49 : async (newPassword: string) => {
50 1 : await authStore.updatePassword(newPassword)
51 0 : toast.success(t('auth.passwordUpdate.success'), {
52 : description: t('auth.passwordUpdate.successDetail'),
53 : duration: 5000
54 : })
55 : },
56 : reportError,
57 : undefined,
58 : [reauthenticationRecovery]
59 : )
60 : }
|