-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathindex.jsx
More file actions
234 lines (217 loc) · 9.57 KB
/
index.jsx
File metadata and controls
234 lines (217 loc) · 9.57 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
/*
* 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 {useIntl, defineMessage} from 'react-intl'
import {Box, Container} from '@salesforce/retail-react-app/app/components/shared/ui'
import {
AuthHelpers,
useAuthHelper,
useCustomerBaskets,
useCustomerId,
useCustomerType,
useShopperBasketsMutation
} from '@salesforce/commerce-sdk-react'
import useNavigation from '@salesforce/retail-react-app/app/hooks/use-navigation'
import Seo from '@salesforce/retail-react-app/app/components/seo'
import {useForm} from 'react-hook-form'
import {useRouteMatch} from 'react-router'
import {useLocation} from 'react-router-dom'
import useEinstein from '@salesforce/retail-react-app/app/hooks/use-einstein'
import LoginForm from '@salesforce/retail-react-app/app/components/login'
import PasswordlessEmailConfirmation from '@salesforce/retail-react-app/app/components/email-confirmation/index'
import {
API_ERROR_MESSAGE,
INVALID_TOKEN_ERROR_MESSAGE,
FEATURE_UNAVAILABLE_ERROR_MESSAGE,
LOGIN_TYPES,
PASSWORDLESS_LOGIN_LANDING_PATH,
PASSWORDLESS_ERROR_MESSAGES,
CREATE_ACCOUNT_FIRST_ERROR_MESSAGE
} from '@salesforce/retail-react-app/app/constants'
import {usePrevious} from '@salesforce/retail-react-app/app/hooks/use-previous'
import {isServer} from '@salesforce/retail-react-app/app/utils/utils'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
const LOGIN_ERROR_MESSAGE = defineMessage({
defaultMessage: 'Incorrect username or password, please try again.',
id: 'login_page.error.incorrect_username_or_password'
})
const LOGIN_VIEW = 'login'
const EMAIL_VIEW = 'email'
const Login = ({initialView = LOGIN_VIEW}) => {
const {formatMessage} = useIntl()
const navigate = useNavigation()
const form = useForm()
const location = useLocation()
const queryParams = new URLSearchParams(location.search)
const {path} = useRouteMatch()
const einstein = useEinstein()
const {isRegistered, customerType} = useCustomerType()
const login = useAuthHelper(AuthHelpers.LoginRegisteredUserB2C)
const loginPasswordless = useAuthHelper(AuthHelpers.LoginPasswordlessUser)
const authorizePasswordlessLogin = useAuthHelper(AuthHelpers.AuthorizePasswordless)
const {passwordless = {}, social = {}} = getConfig().app.login || {}
const isPasswordlessEnabled = !!passwordless?.enabled
const isSocialEnabled = !!social?.enabled
const idps = social?.idps
const customerId = useCustomerId()
const prevAuthType = usePrevious(customerType)
const {data: baskets, isSuccess: isSuccessCustomerBaskets} = useCustomerBaskets(
{parameters: {customerId}},
{enabled: !!customerId && !isServer, keepPreviousData: true}
)
const mergeBasket = useShopperBasketsMutation('mergeBasket')
const [currentView, setCurrentView] = useState(initialView)
const [passwordlessLoginEmail, setPasswordlessLoginEmail] = useState('')
const [loginType, setLoginType] = useState(LOGIN_TYPES.PASSWORD)
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 (e) {
form.setError('global', {
type: 'manual',
message: formatMessage(API_ERROR_MESSAGE)
})
}
}
}
const submitForm = async (data) => {
form.clearErrors()
const handlePasswordlessLogin = async (email) => {
try {
const res = await authorizePasswordlessLogin.mutateAsync({userid: email})
if (res.status !== 200) {
const errorData = await res.json()
throw new Error(`${res.status} ${errorData.message}`)
}
setCurrentView(EMAIL_VIEW)
} catch (error) {
const message = /error getting user info/i.test(error.message)
? formatMessage(CREATE_ACCOUNT_FIRST_ERROR_MESSAGE)
: PASSWORDLESS_ERROR_MESSAGES.some(msg => msg.test(error.message))
? formatMessage(FEATURE_UNAVAILABLE_ERROR_MESSAGE)
: formatMessage(API_ERROR_MESSAGE)
form.setError('global', { type: 'manual', message })
}
}
return {
login: async (data) => {
if (loginType === LOGIN_TYPES.PASSWORD) {
try {
await login.mutateAsync({username: data.email, password: data.password})
} catch (error) {
const message = /Unauthorized/i.test(error.message)
? formatMessage(LOGIN_ERROR_MESSAGE)
: formatMessage(API_ERROR_MESSAGE)
form.setError('global', {type: 'manual', message})
}
handleMergeBasket()
} else if (loginType === LOGIN_TYPES.PASSWORDLESS) {
setPasswordlessLoginEmail(data.email)
await handlePasswordlessLogin(data.email)
}
},
email: async () => {
await handlePasswordlessLogin(passwordlessLoginEmail)
}
}[currentView](data)
}
// Handles passwordless login by retrieving the 'token' from the query parameters and
// executing a passwordless login attempt using the token. The process waits for the
// customer baskets to be loaded to guarantee proper basket merging.
useEffect(() => {
if (path === PASSWORDLESS_LOGIN_LANDING_PATH) {
const token = queryParams.get('token')
const passwordlessLogin = async() => {
try {
await loginPasswordless.mutateAsync({pwdlessLoginToken: token})
} catch (e) {
const errorData = await e.response?.json()
const message = /invalid token/i.test(errorData.message)
? formatMessage(INVALID_TOKEN_ERROR_MESSAGE)
: formatMessage(API_ERROR_MESSAGE)
form.setError('global', {type: 'manual', message})
}
}
passwordlessLogin()
}
}, [path, isSuccessCustomerBaskets])
// If customer is registered push to account page and merge the basket
useEffect(() => {
if (isRegistered) {
handleMergeBasket()
if (location?.state?.directedFrom) {
navigate(location.state.directedFrom)
} else {
navigate('/account')
}
}
}, [isRegistered])
/**************** Einstein ****************/
useEffect(() => {
einstein.sendViewPage(location.pathname)
}, [])
return (
<Box data-testid="login-page" bg="gray.50" py={[8, 16]}>
<Seo title="Sign in" description="Customer sign in" />
<Container
paddingTop={16}
width={['100%', '407px']}
bg="white"
paddingBottom={14}
marginTop={8}
marginBottom={8}
borderRadius="base"
>
{!form.formState.isSubmitSuccessful && currentView === LOGIN_VIEW && (
<LoginForm
form={form}
submitForm={submitForm}
clickCreateAccount={() => navigate('/registration')}
handlePasswordlessLoginClick={() => {
setLoginType(LOGIN_TYPES.PASSWORDLESS)
}}
handleForgotPasswordClick={() => navigate('/reset-password')}
isPasswordlessEnabled={isPasswordlessEnabled}
isSocialEnabled={isSocialEnabled}
idps={idps}
setLoginType={setLoginType}
/>
)}
{form.formState.isSubmitSuccessful && currentView === EMAIL_VIEW && (
<PasswordlessEmailConfirmation
form={form}
submitForm={submitForm}
email={passwordlessLoginEmail}
/>
)}
</Container>
</Box>
)
}
Login.getTemplateName = () => 'login'
Login.propTypes = {
initialView: PropTypes.oneOf([LOGIN_VIEW, EMAIL_VIEW]),
match: PropTypes.object
}
export default Login