about summary refs log tree commit diff
path: root/src/state/email-verification.tsx
blob: 0528d59ea1f2b203e181474f3fd8db011fa47fee (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
54
55
56
57
58
59
60
61
62
63
64
import {createContext, useContext, useMemo} from 'react'

import {BSKY_SERVICE} from '#/lib/constants'
import {getHostnameFromUrl} from '#/lib/strings/url-helpers'
import {STALE} from '#/state/queries'
import {useProfileQuery} from '#/state/queries/profile'
import {useCheckEmailConfirmed} from '#/state/service-config'
import {useSession} from '#/state/session'

type EmailVerificationContext = {
  needsEmailVerification: boolean
}

const EmailVerificationContext = createContext<EmailVerificationContext | null>(
  null,
)
EmailVerificationContext.displayName = 'EmailVerificationContext'

export function Provider({children}: {children: React.ReactNode}) {
  const {currentAccount} = useSession()

  const {data: profile} = useProfileQuery({
    did: currentAccount?.did,
    staleTime: STALE.INFINITY,
  })

  const checkEmailConfirmed = useCheckEmailConfirmed()

  // Date set for 11 AM PST on the 18th of November
  const isNewEnough =
    !!profile?.createdAt &&
    Date.parse(profile.createdAt) >= Date.parse('2024-11-18T19:00:00.000Z')

  const isSelfHost =
    currentAccount &&
    getHostnameFromUrl(currentAccount.service) !==
      getHostnameFromUrl(BSKY_SERVICE)

  const needsEmailVerification =
    !isSelfHost &&
    checkEmailConfirmed &&
    !currentAccount?.emailConfirmed &&
    isNewEnough

  const value = useMemo(
    () => ({needsEmailVerification}),
    [needsEmailVerification],
  )

  return (
    <EmailVerificationContext.Provider value={value}>
      {children}
    </EmailVerificationContext.Provider>
  )
}
Provider.displayName = 'EmailVerificationProvider'

export function useEmail() {
  const ctx = useContext(EmailVerificationContext)
  if (!ctx) {
    throw new Error('useEmail must be used within a EmailVerificationProvider')
  }
  return ctx
}