about summary refs log tree commit diff
path: root/src/view/com/auth/create/state.ts
blob: 62a8495b38aebafbefa36049caf39598dec51303 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import {useReducer} from 'react'
import {
  ComAtprotoServerDescribeServer,
  ComAtprotoServerCreateAccount,
} from '@atproto/api'
import {I18nContext, useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import * as EmailValidator from 'email-validator'
import {getAge} from 'lib/strings/time'
import {logger} from '#/logger'
import {createFullHandle} from '#/lib/strings/handles'
import {cleanError} from '#/lib/strings/errors'
import {DispatchContext as OnboardingDispatchContext} from '#/state/shell/onboarding'
import {ApiContext as SessionApiContext} from '#/state/session'
import {DEFAULT_SERVICE} from '#/lib/constants'

export type ServiceDescription = ComAtprotoServerDescribeServer.OutputSchema
const DEFAULT_DATE = new Date(Date.now() - 60e3 * 60 * 24 * 365 * 20) // default to 20 years ago

export type CreateAccountAction =
  | {type: 'set-step'; value: number}
  | {type: 'set-error'; value: string | undefined}
  | {type: 'set-processing'; value: boolean}
  | {type: 'set-service-url'; value: string}
  | {type: 'set-service-description'; value: ServiceDescription | undefined}
  | {type: 'set-user-domain'; value: string}
  | {type: 'set-invite-code'; value: string}
  | {type: 'set-email'; value: string}
  | {type: 'set-password'; value: string}
  | {type: 'set-handle'; value: string}
  | {type: 'set-birth-date'; value: Date}
  | {type: 'next'}
  | {type: 'back'}

export interface CreateAccountState {
  // state
  step: number
  error: string | undefined
  isProcessing: boolean
  serviceUrl: string
  serviceDescription: ServiceDescription | undefined
  userDomain: string
  inviteCode: string
  email: string
  password: string
  handle: string
  birthDate: Date

  // computed
  canBack: boolean
  canNext: boolean
  isInviteCodeRequired: boolean
}

export type CreateAccountDispatch = (action: CreateAccountAction) => void

export function useCreateAccount() {
  const {_} = useLingui()
  return useReducer(createReducer({_}), {
    step: 1,
    error: undefined,
    isProcessing: false,
    serviceUrl: DEFAULT_SERVICE,
    serviceDescription: undefined,
    userDomain: '',
    inviteCode: '',
    email: '',
    password: '',
    handle: '',
    birthDate: DEFAULT_DATE,

    canBack: false,
    canNext: false,
    isInviteCodeRequired: false,
  })
}

export async function submit({
  createAccount,
  onboardingDispatch,
  uiState,
  uiDispatch,
  _,
}: {
  createAccount: SessionApiContext['createAccount']
  onboardingDispatch: OnboardingDispatchContext
  uiState: CreateAccountState
  uiDispatch: CreateAccountDispatch
  _: I18nContext['_']
}) {
  if (!uiState.email) {
    uiDispatch({type: 'set-step', value: 2})
    return uiDispatch({
      type: 'set-error',
      value: _(msg`Please enter your email.`),
    })
  }
  if (!EmailValidator.validate(uiState.email)) {
    uiDispatch({type: 'set-step', value: 2})
    return uiDispatch({
      type: 'set-error',
      value: _(msg`Your email appears to be invalid.`),
    })
  }
  if (!uiState.password) {
    uiDispatch({type: 'set-step', value: 2})
    return uiDispatch({
      type: 'set-error',
      value: _(msg`Please choose your password.`),
    })
  }
  if (!uiState.handle) {
    uiDispatch({type: 'set-step', value: 3})
    return uiDispatch({
      type: 'set-error',
      value: _(msg`Please choose your handle.`),
    })
  }
  uiDispatch({type: 'set-error', value: ''})
  uiDispatch({type: 'set-processing', value: true})

  try {
    onboardingDispatch({type: 'start'}) // start now to avoid flashing the wrong view
    await createAccount({
      service: uiState.serviceUrl,
      email: uiState.email,
      handle: createFullHandle(uiState.handle, uiState.userDomain),
      password: uiState.password,
      inviteCode: uiState.inviteCode.trim(),
    })
  } catch (e: any) {
    onboardingDispatch({type: 'skip'}) // undo starting the onboard
    let errMsg = e.toString()
    if (e instanceof ComAtprotoServerCreateAccount.InvalidInviteCodeError) {
      errMsg = _(
        msg`Invite code not accepted. Check that you input it correctly and try again.`,
      )
    }

    if ([400, 429].includes(e.status)) {
      logger.warn('Failed to create account', {error: e})
    } else {
      logger.error(`Failed to create account (${e.status} status)`, {error: e})
    }

    uiDispatch({type: 'set-processing', value: false})
    uiDispatch({type: 'set-error', value: cleanError(errMsg)})
    throw e
  }
}

export function is13(state: CreateAccountState) {
  return getAge(state.birthDate) >= 13
}

export function is18(state: CreateAccountState) {
  return getAge(state.birthDate) >= 18
}

function createReducer({_}: {_: I18nContext['_']}) {
  return function reducer(
    state: CreateAccountState,
    action: CreateAccountAction,
  ): CreateAccountState {
    switch (action.type) {
      case 'set-step': {
        return compute({...state, step: action.value})
      }
      case 'set-error': {
        return compute({...state, error: action.value})
      }
      case 'set-processing': {
        return compute({...state, isProcessing: action.value})
      }
      case 'set-service-url': {
        return compute({
          ...state,
          serviceUrl: action.value,
          serviceDescription:
            state.serviceUrl !== action.value
              ? undefined
              : state.serviceDescription,
        })
      }
      case 'set-service-description': {
        return compute({
          ...state,
          serviceDescription: action.value,
          userDomain: action.value?.availableUserDomains[0] || '',
        })
      }
      case 'set-user-domain': {
        return compute({...state, userDomain: action.value})
      }
      case 'set-invite-code': {
        return compute({...state, inviteCode: action.value})
      }
      case 'set-email': {
        return compute({...state, email: action.value})
      }
      case 'set-password': {
        return compute({...state, password: action.value})
      }
      case 'set-handle': {
        return compute({...state, handle: action.value})
      }
      case 'set-birth-date': {
        return compute({...state, birthDate: action.value})
      }
      case 'next': {
        if (state.step === 2) {
          if (!is13(state)) {
            return compute({
              ...state,
              error: _(
                msg`Unfortunately, you do not meet the requirements to create an account.`,
              ),
            })
          }
        }
        return compute({...state, error: '', step: state.step + 1})
      }
      case 'back': {
        return compute({...state, error: '', step: state.step - 1})
      }
    }
  }
}

function compute(state: CreateAccountState): CreateAccountState {
  let canNext = true
  if (state.step === 1) {
    canNext = !!state.serviceDescription
  } else if (state.step === 2) {
    canNext =
      (!state.isInviteCodeRequired || !!state.inviteCode) &&
      !!state.email &&
      !!state.password
  } else if (state.step === 3) {
    canNext = !!state.handle
  }
  return {
    ...state,
    canBack: state.step > 1,
    canNext,
    isInviteCodeRequired: !!state.serviceDescription?.inviteCodeRequired,
  }
}