about summary refs log tree commit diff
path: root/src/lib/hooks/useRequireEmailVerification.tsx
blob: 2e5b339783b3ffdb01cadbe35bfb174fbcd910b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import {useCallback} from 'react'
import {Keyboard} from 'react-native'

import {useEmail} from '#/state/email-verification'
import {useRequireAuth, useSession} from '#/state/session'
import {useCloseAllActiveElements} from '#/state/util'
import {
  EmailDialogScreenID,
  type Screen,
  useEmailDialogControl,
} from '#/components/dialogs/EmailDialog'

export function useRequireEmailVerification() {
  const {currentAccount} = useSession()
  const {needsEmailVerification} = useEmail()
  const requireAuth = useRequireAuth()
  const emailDialogControl = useEmailDialogControl()
  const closeAll = useCloseAllActiveElements()

  return useCallback(
    <T extends (...args: any[]) => any>(
      cb: T,
      config: Omit<
        Extract<Screen, {id: EmailDialogScreenID.Verify}>,
        'id'
      > = {},
    ): ((...args: Parameters<T>) => ReturnType<T>) => {
      return (...args: Parameters<T>): ReturnType<T> => {
        if (!currentAccount) {
          return requireAuth(() => cb(...args)) as ReturnType<T>
        }
        if (needsEmailVerification) {
          Keyboard.dismiss()
          closeAll()
          emailDialogControl.open({
            id: EmailDialogScreenID.Verify,
            ...config,
          })
          return undefined as ReturnType<T>
        } else {
          return cb(...args)
        }
      }
    },
    [
      needsEmailVerification,
      currentAccount,
      emailDialogControl,
      closeAll,
      requireAuth,
    ],
  )
}