-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathuse-auth-modal.js
More file actions
431 lines (401 loc) · 16.8 KB
/
use-auth-modal.js
File metadata and controls
431 lines (401 loc) · 16.8 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import React, {useEffect, useState} from 'react'
import PropTypes from 'prop-types'
import {defineMessage, useIntl} from 'react-intl'
import {useForm} from 'react-hook-form'
import {
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalOverlay,
useDisclosure,
useToast
} from '@salesforce/retail-react-app/app/components/shared/ui'
import {
AuthHelpers,
useAuthHelper,
useCustomer,
useCustomerId,
useCustomerType,
useCustomerBaskets,
useShopperBasketsMutation
} from '@salesforce/commerce-sdk-react'
import LoginForm from '@salesforce/retail-react-app/app/components/login'
import ResetPasswordForm from '@salesforce/retail-react-app/app/components/reset-password'
import RegisterForm from '@salesforce/retail-react-app/app/components/register'
import PasswordlessEmailConfirmation from '@salesforce/retail-react-app/app/components/email-confirmation/index'
import OtpAuth from '@salesforce/retail-react-app/app/components/otp-auth'
import {noop} from '@salesforce/retail-react-app/app/utils/utils'
import {API_ERROR_MESSAGE} from '@salesforce/retail-react-app/app/constants'
import {
getAuthorizePasswordlessErrorMessage,
getPasswordResetErrorMessage,
getLoginPasswordlessErrorMessage
} from '@salesforce/retail-react-app/app/utils/auth-utils'
import useNavigation from '@salesforce/retail-react-app/app/hooks/use-navigation'
import {usePrevious} from '@salesforce/retail-react-app/app/hooks/use-previous'
import {usePasswordReset} from '@salesforce/retail-react-app/app/hooks/use-password-reset'
import {isServer} from '@salesforce/retail-react-app/app/utils/utils'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {usePasskeyRegistration} from '@salesforce/retail-react-app/app/hooks/use-passkey-registration'
import {usePasskeyLogin} from '@salesforce/retail-react-app/app/hooks/use-passkey-login'
import {getPasswordlessCallbackUrl} from '@salesforce/retail-react-app/app/utils/auth-utils'
import useMultiSite from '@salesforce/retail-react-app/app/hooks/use-multi-site'
export const LOGIN_VIEW = 'login'
export const REGISTER_VIEW = 'register'
export const PASSWORD_VIEW = 'password'
export const EMAIL_VIEW = 'email'
const LOGIN_ERROR = defineMessage({
defaultMessage: "Something's not right with your email or password. Try again.",
id: 'auth_modal.error.incorrect_email_or_password'
})
export const AuthModal = ({
initialView = LOGIN_VIEW,
initialEmail = '',
onLoginSuccess = noop,
onRegistrationSuccess = noop,
isOpen,
onOpen,
onClose,
isPasswordlessEnabled = false,
isSocialEnabled = false,
idps = [],
...props
}) => {
const {formatMessage} = useIntl()
const customerId = useCustomerId()
const {isRegistered, customerType} = useCustomerType()
const prevAuthType = usePrevious(customerType)
const {loginWithPasskey, abortPasskeyLogin} = usePasskeyLogin()
const customer = useCustomer(
{parameters: {customerId}},
{enabled: !!customerId && isRegistered}
)
const navigate = useNavigation()
const [currentView, setCurrentView] = useState(initialView)
const [isOtpAuthOpen, setIsOtpAuthOpen] = useState(false)
const form = useForm()
const toast = useToast()
const login = useAuthHelper(AuthHelpers.LoginRegisteredUserB2C)
const register = useAuthHelper(AuthHelpers.Register)
const {locale} = useMultiSite()
const {getPasswordResetToken} = usePasswordReset()
const authorizePasswordlessLogin = useAuthHelper(AuthHelpers.AuthorizePasswordless)
const loginPasswordless = useAuthHelper(AuthHelpers.LoginPasswordlessUser)
const passwordlessConfig = getConfig().app.login?.passwordless
const passwordlessMode = passwordlessConfig?.mode
const callbackURL = getPasswordlessCallbackUrl(passwordlessConfig?.callbackURI)
const {data: baskets} = useCustomerBaskets(
{parameters: {customerId}},
{enabled: !!customerId && !isServer, keepPreviousData: true}
)
const mergeBasket = useShopperBasketsMutation('mergeBasket')
const {showRegisterPasskeyToast} = usePasskeyRegistration()
const handlePasswordlessLogin = async (email) => {
try {
const redirectPath = window.location.pathname + (window.location.search || '')
await authorizePasswordlessLogin.mutateAsync({
userid: email,
mode: passwordlessMode,
locale: locale.id,
...(callbackURL && {callbackURI: `${callbackURL}?redirectUrl=${redirectPath}`})
})
return {success: true}
} catch (error) {
const message = formatMessage(getAuthorizePasswordlessErrorMessage(error.message))
form.setError('global', {type: 'manual', message})
return {success: false}
}
}
const handleMergeBasket = () => {
const hasBasketItem = baskets?.baskets?.[0]?.productItems?.length > 0
// we only want to merge basket when the user is logged in as a recurring user
// only recurring users trigger the login mutation, new user triggers register mutation
// this logic needs to stay in this block because this is the only place that tells if a user is a recurring user
// if you change logic here, also change it in login page
const shouldMergeBasket = hasBasketItem && prevAuthType === 'guest'
if (shouldMergeBasket) {
try {
mergeBasket.mutate({
headers: {
// This is not required since the request has no body
// but CommerceAPI throws a '419 - Unsupported Media Type' error if this header is removed.
'Content-Type': 'application/json'
},
parameters: {
createDestinationBasket: true
}
})
} catch (error) {
form.setError('global', {
type: 'manual',
message: formatMessage(API_ERROR_MESSAGE)
})
}
}
}
const submitForm = async (data, isPasswordless = false) => {
form.clearErrors()
const onLoginSuccess = () => {
navigate('/account')
}
return {
login: async (data) => {
if (isPasswordless) {
const email = data.email
const {success} = await handlePasswordlessLogin(email)
// Only close AuthModal and open OtpAuth modal if passwordless login succeeded
if (success) {
// Close AuthModal first, then open OtpAuth modal after a brief delay
onClose()
setTimeout(() => {
setIsOtpAuthOpen(true)
}, 150) // Small delay to allow AuthModal to close first
}
return
}
try {
await login.mutateAsync({
username: data.email,
password: data.password
})
} catch (error) {
const message = /Unauthorized/i.test(error.message)
? formatMessage(LOGIN_ERROR)
: formatMessage(API_ERROR_MESSAGE)
form.setError('global', {type: 'manual', message})
}
},
register: async (data) => {
try {
const body = {
customer: {
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
login: data.email
},
password: data.password
}
await register.mutateAsync(body)
onLoginSuccess()
} catch (error) {
form.setError('global', {
type: 'manual',
message: formatMessage(API_ERROR_MESSAGE)
})
}
},
password: async (data) => {
try {
await getPasswordResetToken(data.email)
} catch (e) {
const message = formatMessage(getPasswordResetErrorMessage(e.message))
form.setError('global', {type: 'manual', message})
}
},
email: async () => {
const email = form.getValues().email || initialEmail
await handlePasswordlessLogin(email)
}
}[currentView](data)
}
const handleOtpVerification = async (pwdlessLoginToken) => {
try {
await loginPasswordless.mutateAsync({pwdlessLoginToken})
return {success: true}
} catch (e) {
const errorData = await e.response?.json()
const message = formatMessage(getLoginPasswordlessErrorMessage(errorData.message))
return {success: false, error: message}
}
}
// Reset form and local state when opening the modal
useEffect(() => {
if (isOpen) {
setCurrentView(initialView)
form.reset()
// Prompt user to login without username (discoverable credentials)
loginWithPasskey().catch(() => {
form.setError('global', {type: 'manual', message: formatMessage(API_ERROR_MESSAGE)})
})
}
// Cleanup: abort passkey login when modal closes or component unmounts
return () => {
abortPasskeyLogin()
}
}, [isOpen])
// Auto-focus the first field in each form view
useEffect(() => {
const initialField = {
[LOGIN_VIEW]: 'email',
[REGISTER_VIEW]: 'firstName',
[PASSWORD_VIEW]: 'email'
}[currentView]
const fieldsRef = form.control?.fieldsRef?.current
fieldsRef?.[initialField]?.ref.focus()
}, [form.control?.fieldsRef?.current])
useEffect(() => {
// we don't want to reset the form on email view
// because we want to pass the email to PasswordlessEmailConfirmation
if (currentView !== EMAIL_VIEW) {
form.reset()
}
}, [currentView])
useEffect(() => {
// Lets determine if the user has either logged in, or registed.
const loggingIn = currentView === LOGIN_VIEW
const registering = currentView === REGISTER_VIEW
const isNowRegistered =
(isOpen || isOtpAuthOpen) && isRegistered && (loggingIn || registering)
// If the customer changed, but it's not because they logged in or registered. Do nothing.
if (!isNowRegistered) {
return
}
// We are done with the modal. Close any modals that are open.
onClose()
setIsOtpAuthOpen(false)
// Show passkey registration prompt if supported
showRegisterPasskeyToast()
// Show a toast only for those registed users returning to the site.
if (loggingIn) {
toast({
variant: 'subtle',
title: `${formatMessage(
{
defaultMessage: 'Welcome {name},',
id: 'auth_modal.info.welcome_user'
},
{
name: customer.data?.firstName || 'back'
}
)}`,
description: `${formatMessage({
defaultMessage: "You're now signed in.",
id: 'auth_modal.description.now_signed_in'
})}`,
status: 'success',
position: 'top-right',
isClosable: true
})
// Execute action to be performed on successful login
onLoginSuccess()
handleMergeBasket()
}
if (registering) {
// Execute action to be performed on successful registration
onRegistrationSuccess()
}
}, [isRegistered])
const onBackToSignInClick = () =>
initialView === PASSWORD_VIEW ? onClose() : setCurrentView(LOGIN_VIEW)
return (
<>
<Modal
size="sm"
closeOnOverlayClick={false}
data-testid="sf-auth-modal"
isOpen={isOpen}
onOpen={onOpen}
onClose={onClose}
{...props}
>
<ModalOverlay />
<ModalContent>
<ModalCloseButton
aria-label={formatMessage({
id: 'auth_modal.button.close.assistive_msg',
defaultMessage: 'Close login form'
})}
/>
<ModalBody pb={8} bg="white" paddingBottom={14} marginTop={14}>
{!form.formState.isSubmitSuccessful && currentView === LOGIN_VIEW && (
<LoginForm
form={form}
submitForm={(data) => {
const shouldUsePasswordless =
isPasswordlessEnabled && !data.password
return submitForm(data, shouldUsePasswordless)
}}
clickCreateAccount={() => setCurrentView(REGISTER_VIEW)}
//TODO: potentially remove this prop in the next major release since
// we don't need to use this props anymore
handlePasswordlessLoginClick={noop}
handleForgotPasswordClick={() => setCurrentView(PASSWORD_VIEW)}
isPasswordlessEnabled={isPasswordlessEnabled}
isSocialEnabled={isSocialEnabled}
idps={idps}
setLoginType={noop}
/>
)}
{!form.formState.isSubmitSuccessful && currentView === REGISTER_VIEW && (
<RegisterForm
form={form}
submitForm={submitForm}
clickSignIn={onBackToSignInClick}
/>
)}
{currentView === PASSWORD_VIEW && (
<ResetPasswordForm
form={form}
submitForm={submitForm}
clickSignIn={onBackToSignInClick}
/>
)}
{currentView === EMAIL_VIEW && (
<PasswordlessEmailConfirmation
form={form}
submitForm={submitForm}
email={form.getValues().email || initialEmail}
/>
)}
</ModalBody>
</ModalContent>
</Modal>
<OtpAuth
isOpen={isOtpAuthOpen}
onClose={() => setIsOtpAuthOpen(false)}
form={form}
handleSendEmailOtp={handlePasswordlessLogin}
handleOtpVerification={handleOtpVerification}
hideCheckoutAsGuestButton={true}
/>
</>
)
}
AuthModal.propTypes = {
initialView: PropTypes.oneOf([LOGIN_VIEW, REGISTER_VIEW, PASSWORD_VIEW, EMAIL_VIEW]),
initialEmail: PropTypes.string,
isOpen: PropTypes.bool.isRequired,
onOpen: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
onLoginSuccess: PropTypes.func,
onRegistrationSuccess: PropTypes.func,
isPasswordlessEnabled: PropTypes.bool,
isSocialEnabled: PropTypes.bool,
idps: PropTypes.arrayOf(PropTypes.string)
}
/**
*
* @param {('register'|'login'|'password'|'email')} initialView - the initial view for the modal
* @returns {Object} - Object props to be spread on to the AuthModal component
*/
export const useAuthModal = (initialView = LOGIN_VIEW) => {
const {isOpen, onOpen, onClose} = useDisclosure()
const {passwordless = {}, social = {}} = getConfig().app.login || {}
return {
initialView,
isOpen,
onOpen,
onClose,
isPasswordlessEnabled: !!passwordless?.enabled,
isSocialEnabled: !!social?.enabled,
idps: social?.idps
}
}