@graphcommerce/magento-customer 11.0.0-canary.66 → 11.0.0-canary.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Change Log
|
|
2
2
|
|
|
3
|
+
## 11.0.0-canary.68
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#2727](https://github.com/graphcommerce-org/graphcommerce/pull/2727) [`4e14aa6`](https://github.com/graphcommerce-org/graphcommerce/commit/4e14aa6c9e2b7d94ac2ce789580ae486e2c995bc) - Each request that needs the customer during an expired customer session waits for one sign-in: a rejected mutation, a private query with `loggedIn`, and a query that fails without the token. A rejected guest query, such as the reCAPTCHA config of the sign-in form, is sent again at once without the token. After the sign-in, `customerLink` sends the waiting requests with the new token. After a dismiss, they return "You must be signed in to continue". A customer token that an earlier page saved with `valid: false` is sent again, so the sign-in opens on the first request. ([@Giovanni-Schroevers](https://github.com/Giovanni-Schroevers))
|
|
8
|
+
|
|
9
|
+
## 11.0.0-canary.67
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#2728](https://github.com/graphcommerce-org/graphcommerce/pull/2728) [`33d9161`](https://github.com/graphcommerce-org/graphcommerce/commit/33d9161379214ebbf80b5e170add5316773ab5d5) - Revert "Treat an expired customer token as signed out": `loggedIn` is true while a customer token exists. During an open sign-in, `customerLink` makes the requests that need the customer wait. ([@Giovanni-Schroevers](https://github.com/Giovanni-Schroevers))
|
|
14
|
+
|
|
3
15
|
## 11.0.0-canary.66
|
|
4
16
|
|
|
5
17
|
## 11.0.0-canary.65
|
|
@@ -16,8 +16,7 @@ export function useCustomerSession(_: UseCustomerSessionOptions = {}) {
|
|
|
16
16
|
|
|
17
17
|
return {
|
|
18
18
|
...tokenData,
|
|
19
|
-
|
|
20
|
-
loggedIn: Boolean(tokenData?.token) && tokenData?.valid !== false,
|
|
19
|
+
loggedIn: Boolean(tokenData?.token),
|
|
21
20
|
query,
|
|
22
21
|
}
|
|
23
22
|
}
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
import type { TypedDocumentNode } from '@graphcommerce/graphql/apollo'
|
|
3
|
+
import {
|
|
4
|
+
ApolloClient,
|
|
5
|
+
ApolloLink,
|
|
6
|
+
CombinedGraphQLErrors,
|
|
7
|
+
gql,
|
|
8
|
+
InMemoryCache,
|
|
9
|
+
} from '@graphcommerce/graphql/apollo'
|
|
10
|
+
import { Observable } from '@graphcommerce/graphql/rxjs'
|
|
11
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
12
|
+
import { CustomerTokenDocument } from '../hooks/CustomerToken.gql'
|
|
13
|
+
import { customerTypePolicies } from '../typePolicies'
|
|
14
|
+
import type { PushRouter } from './customerLink'
|
|
15
|
+
import { customerLink } from './customerLink'
|
|
16
|
+
|
|
17
|
+
vi.mock(import('@graphcommerce/next-config/config'), async (importOriginal) => ({
|
|
18
|
+
...(await importOriginal()),
|
|
19
|
+
magentoVersion: 248,
|
|
20
|
+
}))
|
|
21
|
+
vi.mock('@lingui/core/macro', () => ({ t: (strings: TemplateStringsArray) => strings.join('') }))
|
|
22
|
+
|
|
23
|
+
const CustomerOrders = gql`
|
|
24
|
+
query CustomerOrders {
|
|
25
|
+
customer {
|
|
26
|
+
email
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
` as TypedDocumentNode<Record<string, unknown>>
|
|
30
|
+
|
|
31
|
+
const AddProductsToCart = gql`
|
|
32
|
+
mutation AddProductsToCart($cartId: String!, $cartItems: [CartItemInput!]!) {
|
|
33
|
+
addProductsToCart(cartId: $cartId, cartItems: $cartItems) {
|
|
34
|
+
cart {
|
|
35
|
+
id
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
` as TypedDocumentNode<Record<string, unknown>>
|
|
40
|
+
|
|
41
|
+
const ProductPrices = gql`
|
|
42
|
+
query ProductPrices($context: PrivateContext) {
|
|
43
|
+
products(search: "a") @privateContext(context: $context) {
|
|
44
|
+
total_count
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
` as TypedDocumentNode<{ products: { total_count: number } }>
|
|
48
|
+
|
|
49
|
+
const RecaptchaV3Config = gql`
|
|
50
|
+
query RecaptchaV3Config {
|
|
51
|
+
recaptchaV3Config {
|
|
52
|
+
website_key
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
` as TypedDocumentNode<{ recaptchaV3Config: { website_key: string } }>
|
|
56
|
+
|
|
57
|
+
const SignIn = gql`
|
|
58
|
+
mutation SignIn($email: String!, $password: String!) {
|
|
59
|
+
generateCustomerToken(email: $email, password: $password) {
|
|
60
|
+
token
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
` as TypedDocumentNode<Record<string, unknown>>
|
|
64
|
+
|
|
65
|
+
/** Responds like Magento 2.4.8+ for the customer with the token `new-token`. */
|
|
66
|
+
function setup(valid = true) {
|
|
67
|
+
const requests: { operationName: string; authorization?: string }[] = []
|
|
68
|
+
const listeners = new Set<(url: string) => void>()
|
|
69
|
+
const router: PushRouter = {
|
|
70
|
+
locale: undefined,
|
|
71
|
+
push: vi.fn(async () => true),
|
|
72
|
+
events: {
|
|
73
|
+
on: (_event: string, handler: (url: string) => void) => listeners.add(handler),
|
|
74
|
+
off: (_event: string, handler: (url: string) => void) => listeners.delete(handler),
|
|
75
|
+
emit: () => {},
|
|
76
|
+
},
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const magento = new ApolloLink((operation) => {
|
|
80
|
+
const { authorization } = operation.getContext().headers ?? {}
|
|
81
|
+
const { operationName = '' } = operation
|
|
82
|
+
requests.push({ operationName, authorization })
|
|
83
|
+
|
|
84
|
+
return new Observable((observer) => {
|
|
85
|
+
if (authorization === 'Bearer expired-token') {
|
|
86
|
+
observer.next({
|
|
87
|
+
errors: [
|
|
88
|
+
{
|
|
89
|
+
message: 'User token has been revoked',
|
|
90
|
+
extensions: { category: 'graphql-authentication' },
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
})
|
|
94
|
+
} else if (operationName === 'SignIn') {
|
|
95
|
+
observer.next({
|
|
96
|
+
errors: [
|
|
97
|
+
{
|
|
98
|
+
message: 'The account sign-in was incorrect',
|
|
99
|
+
extensions: { category: 'graphql-authentication' },
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
})
|
|
103
|
+
} else if (operationName === 'RecaptchaV3Config') {
|
|
104
|
+
observer.next({
|
|
105
|
+
data: { recaptchaV3Config: { __typename: 'ReCaptchaConfigOutput', website_key: 'key' } },
|
|
106
|
+
})
|
|
107
|
+
} else if (operationName === 'ProductPrices') {
|
|
108
|
+
const total_count = authorization ? 2 : 1
|
|
109
|
+
observer.next({ data: { products: { __typename: 'Products', total_count } } })
|
|
110
|
+
} else if (!authorization) {
|
|
111
|
+
observer.next({
|
|
112
|
+
errors: [
|
|
113
|
+
{
|
|
114
|
+
message: "The current customer isn't authorized.",
|
|
115
|
+
extensions: { category: 'graphql-authorization' },
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
})
|
|
119
|
+
} else if (operationName === 'CustomerOrders') {
|
|
120
|
+
observer.next({ data: { customer: { __typename: 'Customer', email: 'a@b.c' } } })
|
|
121
|
+
} else {
|
|
122
|
+
observer.next({ data: { addProductsToCart: { cart: { __typename: 'Cart', id: '1' } } } })
|
|
123
|
+
}
|
|
124
|
+
observer.complete()
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
const client = new ApolloClient({
|
|
129
|
+
cache: new InMemoryCache({ typePolicies: customerTypePolicies }),
|
|
130
|
+
link: ApolloLink.from([customerLink(router), magento]),
|
|
131
|
+
})
|
|
132
|
+
client.writeQuery({
|
|
133
|
+
query: CustomerTokenDocument,
|
|
134
|
+
data: {
|
|
135
|
+
customerToken: {
|
|
136
|
+
__typename: 'CustomerToken',
|
|
137
|
+
token: 'expired-token',
|
|
138
|
+
createdAt: null,
|
|
139
|
+
valid,
|
|
140
|
+
xMagentoCacheId: null,
|
|
141
|
+
email: 'a@b.c',
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
const navigate = (url: string) => listeners.forEach((listener) => listener(url))
|
|
147
|
+
const signIn = () => {
|
|
148
|
+
client.writeQuery({
|
|
149
|
+
query: CustomerTokenDocument,
|
|
150
|
+
data: {
|
|
151
|
+
customerToken: {
|
|
152
|
+
__typename: 'CustomerToken',
|
|
153
|
+
token: 'new-token',
|
|
154
|
+
createdAt: null,
|
|
155
|
+
valid: true,
|
|
156
|
+
xMagentoCacheId: null,
|
|
157
|
+
email: 'a@b.c',
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
const query = () =>
|
|
163
|
+
client.query({ query: CustomerOrders, fetchPolicy: 'network-only', errorPolicy: 'all' })
|
|
164
|
+
const addToCart = () =>
|
|
165
|
+
client.mutate({
|
|
166
|
+
mutation: AddProductsToCart,
|
|
167
|
+
variables: { cartId: '1', cartItems: [{ sku: 'a', quantity: 1 }] },
|
|
168
|
+
errorPolicy: 'all',
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
const privateQuery = () =>
|
|
172
|
+
client.query({
|
|
173
|
+
query: ProductPrices,
|
|
174
|
+
variables: { context: { loggedIn: true } },
|
|
175
|
+
fetchPolicy: 'network-only',
|
|
176
|
+
errorPolicy: 'all',
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
return { client, router, requests, navigate, signIn, query, addToCart, privateQuery }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
describe('customerLink when Magento rejects the customer token', () => {
|
|
183
|
+
it('opens the sign-in page one time for requests that fail at the same time', async () => {
|
|
184
|
+
const { router, navigate, signIn, query, addToCart } = setup()
|
|
185
|
+
|
|
186
|
+
const results = Promise.all([query(), addToCart()])
|
|
187
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
188
|
+
navigate('/account/signin')
|
|
189
|
+
signIn()
|
|
190
|
+
navigate('/p/product')
|
|
191
|
+
await results
|
|
192
|
+
|
|
193
|
+
expect(router.push).toHaveBeenCalledTimes(1)
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
it('sends a request that started during the sign-in again with the new token', async () => {
|
|
197
|
+
const { router, requests, navigate, signIn, query, addToCart } = setup()
|
|
198
|
+
|
|
199
|
+
const first = query()
|
|
200
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
201
|
+
navigate('/account/signin')
|
|
202
|
+
const added = addToCart()
|
|
203
|
+
await vi.waitFor(() =>
|
|
204
|
+
expect(requests).toContainEqual({
|
|
205
|
+
operationName: 'AddProductsToCart',
|
|
206
|
+
authorization: undefined,
|
|
207
|
+
}),
|
|
208
|
+
)
|
|
209
|
+
signIn()
|
|
210
|
+
navigate('/p/product')
|
|
211
|
+
|
|
212
|
+
expect((await added).error).toBeUndefined()
|
|
213
|
+
expect((await first).error).toBeUndefined()
|
|
214
|
+
expect(requests).toContainEqual({
|
|
215
|
+
operationName: 'AddProductsToCart',
|
|
216
|
+
authorization: 'Bearer new-token',
|
|
217
|
+
})
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
it('returns one sign-in error to each request after a dismiss and does not send them again', async () => {
|
|
221
|
+
const { client, router, requests, navigate, query, addToCart } = setup()
|
|
222
|
+
|
|
223
|
+
const first = query()
|
|
224
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
225
|
+
navigate('/account/signin')
|
|
226
|
+
const added = addToCart()
|
|
227
|
+
await vi.waitFor(() =>
|
|
228
|
+
expect(requests.map((r) => r.operationName)).toContain('AddProductsToCart'),
|
|
229
|
+
)
|
|
230
|
+
await new Promise((resolve) => {
|
|
231
|
+
setTimeout(resolve, 10)
|
|
232
|
+
})
|
|
233
|
+
const sent = requests.length
|
|
234
|
+
navigate('/p/product')
|
|
235
|
+
|
|
236
|
+
for (const { error } of await Promise.all([first, added])) {
|
|
237
|
+
expect(CombinedGraphQLErrors.is(error)).toBe(true)
|
|
238
|
+
if (!CombinedGraphQLErrors.is(error)) continue
|
|
239
|
+
expect(error.errors.map((err) => err.extensions?.category)).toEqual(['graphql-authorization'])
|
|
240
|
+
expect(error.errors[0].message).toBe('You must be signed in to continue')
|
|
241
|
+
}
|
|
242
|
+
expect(requests).toHaveLength(sent)
|
|
243
|
+
expect(client.cache.readQuery({ query: CustomerTokenDocument })?.customerToken).toBeFalsy()
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
it('returns the error of a wrong password in the sign-in form', async () => {
|
|
247
|
+
const { client, router, query } = setup()
|
|
248
|
+
|
|
249
|
+
void query()
|
|
250
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
251
|
+
const { error } = await client.mutate({
|
|
252
|
+
mutation: SignIn,
|
|
253
|
+
variables: { email: 'a@b.c', password: 'wrong' },
|
|
254
|
+
errorPolicy: 'all',
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
expect(CombinedGraphQLErrors.is(error) && error.errors[0].message).toBe(
|
|
258
|
+
'The account sign-in was incorrect',
|
|
259
|
+
)
|
|
260
|
+
expect(router.push).toHaveBeenCalledTimes(1)
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
it('holds a private query during the sign-in and sends it with the new token', async () => {
|
|
264
|
+
const { router, requests, navigate, signIn, query, privateQuery } = setup()
|
|
265
|
+
|
|
266
|
+
const first = query()
|
|
267
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
268
|
+
navigate('/account/signin')
|
|
269
|
+
const prices = privateQuery()
|
|
270
|
+
await new Promise((resolve) => {
|
|
271
|
+
setTimeout(resolve, 10)
|
|
272
|
+
})
|
|
273
|
+
signIn()
|
|
274
|
+
navigate('/p/product')
|
|
275
|
+
|
|
276
|
+
expect((await prices).data?.products.total_count).toBe(2)
|
|
277
|
+
expect(requests.filter((request) => request.operationName === 'ProductPrices')).toEqual([
|
|
278
|
+
{ operationName: 'ProductPrices', authorization: 'Bearer new-token' },
|
|
279
|
+
])
|
|
280
|
+
await first
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
it('returns the sign-in error to a held private query after a dismiss', async () => {
|
|
284
|
+
const { router, requests, navigate, query, privateQuery } = setup()
|
|
285
|
+
|
|
286
|
+
void query()
|
|
287
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
288
|
+
navigate('/account/signin')
|
|
289
|
+
const prices = privateQuery()
|
|
290
|
+
navigate('/p/product')
|
|
291
|
+
const { error } = await prices
|
|
292
|
+
|
|
293
|
+
expect(CombinedGraphQLErrors.is(error) && error.errors[0].message).toBe(
|
|
294
|
+
'You must be signed in to continue',
|
|
295
|
+
)
|
|
296
|
+
expect(requests.map((request) => request.operationName)).not.toContain('ProductPrices')
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
it('sends a token that an earlier page saved with valid: false', async () => {
|
|
300
|
+
const { router, requests, query } = setup(false)
|
|
301
|
+
|
|
302
|
+
void query()
|
|
303
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
304
|
+
|
|
305
|
+
expect(requests[0]).toEqual({
|
|
306
|
+
operationName: 'CustomerOrders',
|
|
307
|
+
authorization: 'Bearer expired-token',
|
|
308
|
+
})
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
it('sends a rejected guest query again without the token', async () => {
|
|
312
|
+
const { client, router, requests } = setup()
|
|
313
|
+
|
|
314
|
+
const result = client.query({
|
|
315
|
+
query: RecaptchaV3Config,
|
|
316
|
+
fetchPolicy: 'network-only',
|
|
317
|
+
errorPolicy: 'all',
|
|
318
|
+
})
|
|
319
|
+
await vi.waitFor(() =>
|
|
320
|
+
expect(requests).toContainEqual({
|
|
321
|
+
operationName: 'RecaptchaV3Config',
|
|
322
|
+
authorization: undefined,
|
|
323
|
+
}),
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
expect((await result).data?.recaptchaV3Config.website_key).toBe('key')
|
|
327
|
+
expect(router.push).toHaveBeenCalledTimes(1)
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
it('does not send a rejected mutation as a guest', async () => {
|
|
331
|
+
const { router, requests, navigate, signIn, addToCart } = setup()
|
|
332
|
+
|
|
333
|
+
const added = addToCart()
|
|
334
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
335
|
+
await new Promise((resolve) => {
|
|
336
|
+
setTimeout(resolve, 10)
|
|
337
|
+
})
|
|
338
|
+
expect(requests).toEqual([
|
|
339
|
+
{ operationName: 'AddProductsToCart', authorization: 'Bearer expired-token' },
|
|
340
|
+
])
|
|
341
|
+
navigate('/account/signin')
|
|
342
|
+
signIn()
|
|
343
|
+
navigate('/p/product')
|
|
344
|
+
|
|
345
|
+
expect((await added).error).toBeUndefined()
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
it('sends the new token as soon as the sign-in succeeds', async () => {
|
|
349
|
+
const { router, requests, navigate, signIn, query, addToCart } = setup()
|
|
350
|
+
|
|
351
|
+
const first = query()
|
|
352
|
+
await vi.waitFor(() => expect(router.push).toHaveBeenCalled())
|
|
353
|
+
navigate('/account/signin')
|
|
354
|
+
signIn()
|
|
355
|
+
const added = addToCart()
|
|
356
|
+
|
|
357
|
+
await vi.waitFor(() =>
|
|
358
|
+
expect(requests.at(-1)).toEqual({
|
|
359
|
+
operationName: 'AddProductsToCart',
|
|
360
|
+
authorization: 'Bearer new-token',
|
|
361
|
+
}),
|
|
362
|
+
)
|
|
363
|
+
navigate('/p/product')
|
|
364
|
+
await Promise.all([first, added])
|
|
365
|
+
})
|
|
366
|
+
})
|
package/link/customerLink.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
import type { ApolloClient } from '@graphcommerce/graphql/apollo'
|
|
1
2
|
import {
|
|
2
3
|
ApolloLink,
|
|
3
4
|
CombinedGraphQLErrors,
|
|
4
5
|
ErrorLink,
|
|
5
6
|
SetContextLink,
|
|
6
7
|
} from '@graphcommerce/graphql/apollo'
|
|
7
|
-
import { from, switchMap } from '@graphcommerce/graphql/rxjs'
|
|
8
|
+
import { from, of, switchMap } from '@graphcommerce/graphql/rxjs'
|
|
8
9
|
import { magentoVersion } from '@graphcommerce/next-config/config'
|
|
9
|
-
import
|
|
10
|
+
import { t } from '@lingui/core/macro'
|
|
11
|
+
import { GraphQLError, OperationTypeNode } from 'graphql'
|
|
10
12
|
import type { NextRouter } from 'next/router'
|
|
11
13
|
import { signOut } from '../components/SignOutForm/signOut'
|
|
12
14
|
import { CustomerTokenDocument } from '../hooks'
|
|
@@ -48,15 +50,37 @@ export async function pushWithPromise(router: Pick<NextRouter, 'push' | 'events'
|
|
|
48
50
|
})
|
|
49
51
|
}
|
|
50
52
|
|
|
53
|
+
/** One sign-in for each client. It resolves to the new token, or to null after a dismiss. */
|
|
54
|
+
const signIns = new WeakMap<ApolloClient, Promise<string | null>>()
|
|
55
|
+
|
|
56
|
+
const signInRequired = () =>
|
|
57
|
+
of({
|
|
58
|
+
data: null,
|
|
59
|
+
errors: [
|
|
60
|
+
new GraphQLError(t`You must be signed in to continue`, {
|
|
61
|
+
extensions: { category: 'graphql-authorization' },
|
|
62
|
+
}),
|
|
63
|
+
],
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
/** Without the token, Magento returns guest data for a private query of a customer. */
|
|
67
|
+
const waitForSignIn = new ApolloLink((operation, forward) => {
|
|
68
|
+
const signIn = signIns.get(operation.client)
|
|
69
|
+
if (!signIn || !operation.variables.context?.loggedIn) return forward(operation)
|
|
70
|
+
return from(signIn).pipe(switchMap((token) => (token ? forward(operation) : signInRequired())))
|
|
71
|
+
})
|
|
72
|
+
|
|
51
73
|
const addTokenHeader = new SetContextLink((prevContext, operation) => {
|
|
52
74
|
const headers: Record<string, string> = { ...prevContext.headers }
|
|
53
75
|
|
|
54
76
|
try {
|
|
55
|
-
const
|
|
77
|
+
const customerToken = operation.client.cache.readQuery({
|
|
78
|
+
query: CustomerTokenDocument,
|
|
79
|
+
})?.customerToken
|
|
56
80
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
81
|
+
// Until the sign-in succeeds, Magento 2.4.8+ rejects each request with the expired token.
|
|
82
|
+
if (customerToken?.token && (customerToken.valid || !signIns.has(operation.client)))
|
|
83
|
+
headers.authorization = `Bearer ${customerToken.token}`
|
|
60
84
|
return { headers }
|
|
61
85
|
} catch {
|
|
62
86
|
return { headers }
|
|
@@ -65,65 +89,76 @@ const addTokenHeader = new SetContextLink((prevContext, operation) => {
|
|
|
65
89
|
|
|
66
90
|
const customerErrorLink = (router: PushRouter) =>
|
|
67
91
|
new ErrorLink(({ error, operation, forward }) => {
|
|
68
|
-
const { client } = operation
|
|
69
|
-
|
|
70
|
-
// Check if this is a GraphQL error
|
|
71
92
|
if (!CombinedGraphQLErrors.is(error)) return undefined
|
|
72
93
|
|
|
94
|
+
const { client } = operation
|
|
73
95
|
const oldHeaders = operation.getContext().headers
|
|
96
|
+
const customerToken = client.cache.readQuery({ query: CustomerTokenDocument })?.customerToken
|
|
97
|
+
const categories = error.errors.map((err) => err.extensions?.category)
|
|
98
|
+
|
|
99
|
+
const tokenRejected =
|
|
100
|
+
!!oldHeaders?.authorization &&
|
|
101
|
+
categories.includes(
|
|
102
|
+
magentoVersion >= 248 ? 'graphql-authentication' : 'graphql-authorization',
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
// `addTokenHeader` sent the request without the expired token.
|
|
106
|
+
const customerRequired =
|
|
107
|
+
!oldHeaders?.authorization &&
|
|
108
|
+
signIns.has(client) &&
|
|
109
|
+
categories.includes('graphql-authorization')
|
|
110
|
+
|
|
111
|
+
if (!tokenRejected && !customerRequired) return undefined
|
|
112
|
+
|
|
113
|
+
if (tokenRejected) {
|
|
114
|
+
if (!customerToken) throw Error('We currently do not have a customer token in the cache.')
|
|
115
|
+
client.writeQuery({
|
|
116
|
+
query: CustomerTokenDocument,
|
|
117
|
+
data: { customerToken: { ...customerToken, valid: false } },
|
|
118
|
+
})
|
|
119
|
+
}
|
|
74
120
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
(
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
// console.error(
|
|
86
|
-
// 'No authorization header found in request, but an authorization error was returned, this is a bug. This is the operation:',
|
|
87
|
-
// operation,
|
|
88
|
-
// )
|
|
89
|
-
return undefined
|
|
121
|
+
let signIn = signIns.get(client)
|
|
122
|
+
if (!signIn) {
|
|
123
|
+
signIn = pushWithPromise(router, '/account/signin').then(() => {
|
|
124
|
+
signIns.delete(client)
|
|
125
|
+
const token = client.cache.readQuery({ query: CustomerTokenDocument })?.customerToken
|
|
126
|
+
if (token?.valid && token.token) return token.token
|
|
127
|
+
signOut(client)
|
|
128
|
+
return null
|
|
129
|
+
})
|
|
130
|
+
signIns.set(client, signIn)
|
|
90
131
|
}
|
|
91
132
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
})
|
|
98
|
-
|
|
99
|
-
// After submission of the signIn form, navigate back to the current route.
|
|
100
|
-
// Resolve the promomise.
|
|
101
|
-
// Dependending on the result, either retry the request or clean up the cache.
|
|
102
|
-
|
|
103
|
-
const signInAgainPromise = pushWithPromise(router, '/account/signin')
|
|
104
|
-
|
|
105
|
-
return from(signInAgainPromise).pipe(
|
|
106
|
-
switchMap(() => {
|
|
107
|
-
const tokenQuery = client.cache.readQuery({ query: CustomerTokenDocument })
|
|
108
|
-
|
|
109
|
-
if (tokenQuery?.customerToken?.valid) {
|
|
110
|
-
// Customer is reauthenticated, retrying request.
|
|
111
|
-
operation.setContext({
|
|
112
|
-
headers: {
|
|
113
|
-
...oldHeaders,
|
|
114
|
-
authorization: `Bearer ${tokenQuery?.customerToken?.token}`,
|
|
115
|
-
},
|
|
116
|
-
})
|
|
117
|
-
} else {
|
|
118
|
-
// Customer has not reauthenticated, clearing all customer data.
|
|
119
|
-
signOut(client)
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// retry the request, returning the new observable
|
|
133
|
+
// Magento did not run a request that it rejected, so it is safe to send it again.
|
|
134
|
+
const afterSignIn = from(signIn).pipe(
|
|
135
|
+
switchMap((token) => {
|
|
136
|
+
if (!token) return signInRequired()
|
|
137
|
+
operation.setContext({ headers: { ...oldHeaders, authorization: `Bearer ${token}` } })
|
|
123
138
|
return forward(operation)
|
|
124
139
|
}),
|
|
125
140
|
)
|
|
141
|
+
|
|
142
|
+
// A guest query, such as the reCAPTCHA config of the sign-in form, must not wait for the sign-in.
|
|
143
|
+
if (
|
|
144
|
+
tokenRejected &&
|
|
145
|
+
operation.operationType === OperationTypeNode.QUERY &&
|
|
146
|
+
!operation.variables.context?.loggedIn
|
|
147
|
+
) {
|
|
148
|
+
const guestHeaders = { ...oldHeaders }
|
|
149
|
+
delete guestHeaders.authorization
|
|
150
|
+
operation.setContext({ headers: guestHeaders })
|
|
151
|
+
return forward(operation).pipe(
|
|
152
|
+
switchMap((result) =>
|
|
153
|
+
result.errors?.some((err) => err.extensions?.category === 'graphql-authorization')
|
|
154
|
+
? afterSignIn
|
|
155
|
+
: of(result),
|
|
156
|
+
),
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return afterSignIn
|
|
126
161
|
})
|
|
127
162
|
|
|
128
163
|
export const customerLink = (router: PushRouter) =>
|
|
129
|
-
ApolloLink.from([addTokenHeader, customerErrorLink(router)])
|
|
164
|
+
ApolloLink.from([waitForSignIn, addTokenHeader, customerErrorLink(router)])
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@graphcommerce/magento-customer",
|
|
3
3
|
"homepage": "https://www.graphcommerce.org/",
|
|
4
4
|
"repository": "github:graphcommerce-org/graphcommerce",
|
|
5
|
-
"version": "11.0.0-canary.
|
|
5
|
+
"version": "11.0.0-canary.68",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"prettier": "@graphcommerce/prettier-config-pwa",
|
|
8
8
|
"eslintConfig": {
|
|
@@ -21,20 +21,20 @@
|
|
|
21
21
|
"./plugins/magentoCustomerPrivateQueryContext": "./plugins/magentoCustomerPrivateQueryContext.ts"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"@graphcommerce/ecommerce-ui": "^11.0.0-canary.
|
|
25
|
-
"@graphcommerce/eslint-config-pwa": "^11.0.0-canary.
|
|
26
|
-
"@graphcommerce/framer-next-pages": "^11.0.0-canary.
|
|
27
|
-
"@graphcommerce/framer-utils": "^11.0.0-canary.
|
|
28
|
-
"@graphcommerce/graphql": "^11.0.0-canary.
|
|
29
|
-
"@graphcommerce/graphql-mesh": "^11.0.0-canary.
|
|
30
|
-
"@graphcommerce/image": "^11.0.0-canary.
|
|
31
|
-
"@graphcommerce/magento-graphql": "^11.0.0-canary.
|
|
32
|
-
"@graphcommerce/magento-store": "^11.0.0-canary.
|
|
33
|
-
"@graphcommerce/next-config": "^11.0.0-canary.
|
|
34
|
-
"@graphcommerce/next-ui": "^11.0.0-canary.
|
|
35
|
-
"@graphcommerce/prettier-config-pwa": "^11.0.0-canary.
|
|
36
|
-
"@graphcommerce/react-hook-form": "^11.0.0-canary.
|
|
37
|
-
"@graphcommerce/typescript-config-pwa": "^11.0.0-canary.
|
|
24
|
+
"@graphcommerce/ecommerce-ui": "^11.0.0-canary.68",
|
|
25
|
+
"@graphcommerce/eslint-config-pwa": "^11.0.0-canary.68",
|
|
26
|
+
"@graphcommerce/framer-next-pages": "^11.0.0-canary.68",
|
|
27
|
+
"@graphcommerce/framer-utils": "^11.0.0-canary.68",
|
|
28
|
+
"@graphcommerce/graphql": "^11.0.0-canary.68",
|
|
29
|
+
"@graphcommerce/graphql-mesh": "^11.0.0-canary.68",
|
|
30
|
+
"@graphcommerce/image": "^11.0.0-canary.68",
|
|
31
|
+
"@graphcommerce/magento-graphql": "^11.0.0-canary.68",
|
|
32
|
+
"@graphcommerce/magento-store": "^11.0.0-canary.68",
|
|
33
|
+
"@graphcommerce/next-config": "^11.0.0-canary.68",
|
|
34
|
+
"@graphcommerce/next-ui": "^11.0.0-canary.68",
|
|
35
|
+
"@graphcommerce/prettier-config-pwa": "^11.0.0-canary.68",
|
|
36
|
+
"@graphcommerce/react-hook-form": "^11.0.0-canary.68",
|
|
37
|
+
"@graphcommerce/typescript-config-pwa": "^11.0.0-canary.68",
|
|
38
38
|
"@lingui/core": "^6",
|
|
39
39
|
"@lingui/react": "^6",
|
|
40
40
|
"@mui/material": "^7.0.0",
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useApolloClient,
|
|
3
|
-
type ApolloClient,
|
|
4
3
|
type getPrivateQueryContextMesh as getPrivateQueryContextMeshType,
|
|
5
4
|
type getPrivateQueryContext as getPrivateQueryContextType,
|
|
6
5
|
type usePrivateQueryContext as usePrivateQueryContextType,
|
|
@@ -24,17 +23,11 @@ function useIsLoggedIn() {
|
|
|
24
23
|
)
|
|
25
24
|
return useSyncExternalStore(
|
|
26
25
|
subscribe,
|
|
27
|
-
() =>
|
|
26
|
+
() => !!cache.readQuery({ query: CustomerTokenDocument })?.customerToken?.token,
|
|
28
27
|
() => false,
|
|
29
28
|
)
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
/** `customerLink` does not send a token with `valid: false`. */
|
|
33
|
-
function isLoggedIn(cache: ApolloClient['cache']) {
|
|
34
|
-
const customerToken = cache.readQuery({ query: CustomerTokenDocument })?.customerToken
|
|
35
|
-
return !!customerToken?.token && customerToken.valid !== false
|
|
36
|
-
}
|
|
37
|
-
|
|
38
31
|
export const config: PluginConfig = {
|
|
39
32
|
type: 'function',
|
|
40
33
|
module: '@graphcommerce/graphql',
|
|
@@ -55,7 +48,7 @@ export const getPrivateQueryContext: FunctionPlugin<typeof getPrivateQueryContex
|
|
|
55
48
|
client,
|
|
56
49
|
...args
|
|
57
50
|
) => {
|
|
58
|
-
const loggedIn =
|
|
51
|
+
const loggedIn = !!client.cache.readQuery({ query: CustomerTokenDocument })?.customerToken?.token
|
|
59
52
|
const res = prev(client, ...args)
|
|
60
53
|
if (!loggedIn) return res
|
|
61
54
|
return { ...res, loggedIn: true }
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
// @vitest-environment happy-dom
|
|
2
|
-
import { ApolloClient, ApolloLink, ApolloProvider, InMemoryCache } from '@graphcommerce/graphql'
|
|
3
|
-
import { renderHook } from '@testing-library/react'
|
|
4
|
-
import { describe, expect, it } from 'vitest'
|
|
5
|
-
import {
|
|
6
|
-
getPrivateQueryContext,
|
|
7
|
-
usePrivateQueryContext,
|
|
8
|
-
} from '../plugins/magentoCustomerPrivateQueryContext'
|
|
9
|
-
import { customerTypePolicies } from '../typePolicies'
|
|
10
|
-
import { CustomerTokenDocument } from './CustomerToken.gql'
|
|
11
|
-
import { useCustomerSession } from './useCustomerSession'
|
|
12
|
-
|
|
13
|
-
function renderWithToken<T>(valid: boolean, hook: (client: ApolloClient) => T) {
|
|
14
|
-
const client = new ApolloClient({
|
|
15
|
-
cache: new InMemoryCache({ typePolicies: customerTypePolicies }),
|
|
16
|
-
link: ApolloLink.empty(),
|
|
17
|
-
})
|
|
18
|
-
client.writeQuery({
|
|
19
|
-
query: CustomerTokenDocument,
|
|
20
|
-
data: {
|
|
21
|
-
customerToken: {
|
|
22
|
-
__typename: 'CustomerToken',
|
|
23
|
-
token: 'test-token',
|
|
24
|
-
createdAt: null,
|
|
25
|
-
valid,
|
|
26
|
-
xMagentoCacheId: null,
|
|
27
|
-
},
|
|
28
|
-
},
|
|
29
|
-
})
|
|
30
|
-
return renderHook(() => hook(client), {
|
|
31
|
-
wrapper: ({ children }) => <ApolloProvider client={client}>{children}</ApolloProvider>,
|
|
32
|
-
}).result.current
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
describe.each([
|
|
36
|
-
{ valid: true, loggedIn: true },
|
|
37
|
-
{ valid: false, loggedIn: false },
|
|
38
|
-
])('a customer token with valid: $valid', ({ valid, loggedIn }) => {
|
|
39
|
-
it(`sets loggedIn of useCustomerSession to ${loggedIn}`, () => {
|
|
40
|
-
expect(renderWithToken(valid, () => useCustomerSession()).loggedIn).toBe(loggedIn)
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
it(`sets loggedIn of the private query context to ${loggedIn}`, () => {
|
|
44
|
-
const contexts = renderWithToken(valid, (client) => [
|
|
45
|
-
getPrivateQueryContext(() => null, client),
|
|
46
|
-
usePrivateQueryContext(() => null),
|
|
47
|
-
])
|
|
48
|
-
expect(contexts.map((context) => context?.loggedIn ?? false)).toEqual([loggedIn, loggedIn])
|
|
49
|
-
})
|
|
50
|
-
})
|