@shopsbuilder/auth-sdk 1.1.0

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.
Files changed (84) hide show
  1. package/README.md +469 -0
  2. package/dist/README.md +469 -0
  3. package/dist/SaleorAccessTokenStorageHandler.d.mts +13 -0
  4. package/dist/SaleorAccessTokenStorageHandler.d.ts +13 -0
  5. package/dist/SaleorAccessTokenStorageHandler.js +50 -0
  6. package/dist/SaleorAccessTokenStorageHandler.mjs +8 -0
  7. package/dist/SaleorAuthClient.d.mts +52 -0
  8. package/dist/SaleorAuthClient.d.ts +52 -0
  9. package/dist/SaleorAuthClient.js +464 -0
  10. package/dist/SaleorAuthClient.mjs +13 -0
  11. package/dist/SaleorExternalAuth.d.mts +29 -0
  12. package/dist/SaleorExternalAuth.d.ts +29 -0
  13. package/dist/SaleorExternalAuth.js +198 -0
  14. package/dist/SaleorExternalAuth.mjs +12 -0
  15. package/dist/SaleorRefreshTokenStorageHandler.d.mts +24 -0
  16. package/dist/SaleorRefreshTokenStorageHandler.d.ts +24 -0
  17. package/dist/SaleorRefreshTokenStorageHandler.js +83 -0
  18. package/dist/SaleorRefreshTokenStorageHandler.mjs +12 -0
  19. package/dist/chunk-263DHBMK.mjs +56 -0
  20. package/dist/chunk-74GMXOK4.mjs +13 -0
  21. package/dist/chunk-77CRMKFX.mjs +12 -0
  22. package/dist/chunk-7JTFMRQS.mjs +105 -0
  23. package/dist/chunk-BRRF6LN3.mjs +224 -0
  24. package/dist/chunk-BZFBMGPG.mjs +25 -0
  25. package/dist/chunk-K5MTKW5C.mjs +16 -0
  26. package/dist/chunk-KLIEZ4V4.mjs +10 -0
  27. package/dist/chunk-NAQNA6DI.mjs +20 -0
  28. package/dist/chunk-Q3UFWDCC.mjs +38 -0
  29. package/dist/chunk-T35JF4IS.mjs +59 -0
  30. package/dist/chunk-UDLCOX6B.mjs +49 -0
  31. package/dist/chunk-WJVMUY3P.mjs +33 -0
  32. package/dist/graphql.d.mts +11 -0
  33. package/dist/graphql.d.ts +11 -0
  34. package/dist/graphql.js +40 -0
  35. package/dist/graphql.mjs +6 -0
  36. package/dist/index.d.mts +5 -0
  37. package/dist/index.d.ts +5 -0
  38. package/dist/index.js +524 -0
  39. package/dist/index.mjs +23 -0
  40. package/dist/mutations.d.mts +12 -0
  41. package/dist/mutations.d.ts +12 -0
  42. package/dist/mutations.js +145 -0
  43. package/dist/mutations.mjs +17 -0
  44. package/dist/next/handler.d.mts +9 -0
  45. package/dist/next/handler.d.ts +9 -0
  46. package/dist/next/handler.js +36 -0
  47. package/dist/next/handler.mjs +11 -0
  48. package/dist/next/index.d.mts +6 -0
  49. package/dist/next/index.d.ts +6 -0
  50. package/dist/next/index.js +38 -0
  51. package/dist/next/index.mjs +11 -0
  52. package/dist/next/server.d.mts +20 -0
  53. package/dist/next/server.d.ts +20 -0
  54. package/dist/next/server.js +79 -0
  55. package/dist/next/server.mjs +53 -0
  56. package/dist/react/SaleorAuthProvider.d.mts +10 -0
  57. package/dist/react/SaleorAuthProvider.d.ts +10 -0
  58. package/dist/react/SaleorAuthProvider.js +50 -0
  59. package/dist/react/SaleorAuthProvider.mjs +13 -0
  60. package/dist/react/context.d.mts +9 -0
  61. package/dist/react/context.d.ts +9 -0
  62. package/dist/react/context.js +46 -0
  63. package/dist/react/context.mjs +16 -0
  64. package/dist/react/index.d.mts +8 -0
  65. package/dist/react/index.d.ts +8 -0
  66. package/dist/react/index.js +291 -0
  67. package/dist/react/index.mjs +30 -0
  68. package/dist/react/useAuthChange.d.mts +8 -0
  69. package/dist/react/useAuthChange.d.ts +8 -0
  70. package/dist/react/useAuthChange.js +58 -0
  71. package/dist/react/useAuthChange.mjs +7 -0
  72. package/dist/react/useSaleorExternalAuth.d.mts +22 -0
  73. package/dist/react/useSaleorExternalAuth.d.ts +22 -0
  74. package/dist/react/useSaleorExternalAuth.js +227 -0
  75. package/dist/react/useSaleorExternalAuth.mjs +11 -0
  76. package/dist/types.d.mts +82 -0
  77. package/dist/types.d.ts +82 -0
  78. package/dist/types.js +34 -0
  79. package/dist/types.mjs +6 -0
  80. package/dist/utils.d.mts +28 -0
  81. package/dist/utils.d.ts +28 -0
  82. package/dist/utils.js +77 -0
  83. package/dist/utils.mjs +15 -0
  84. package/package.json +129 -0
package/README.md ADDED
@@ -0,0 +1,469 @@
1
+ <div align="center">
2
+ <img width="150" alt="" src="https://github.com/saleor/auth-sdk/assets/1338731/c90a73d0-5ef1-4d09-9347-c5d02cd7244d">
3
+ </div>
4
+
5
+ <div align="center">
6
+
7
+ # Saleor Auth SDK
8
+
9
+ Saleor Auth SDK integrates secure and customizable authentication and authorization into storefronts using Saleor.
10
+
11
+ **Below 3kB bundle size (gzipped).**
12
+
13
+ </div>
14
+
15
+ <div align="center">
16
+ <a href="https://www.npmjs.com/package/@saleor/auth-sdk">npm</a>
17
+ <span> • </span>
18
+ <a href="https://docs.saleor.io/docs/3.x/api-usage/authentication">Docs</a>
19
+ <span> • </span>
20
+ <a href="https://twitter.com/getsaleor">Twitter</a>
21
+ <span> • </span>
22
+ <a href="https://saleor.io/discord">Discord</a>
23
+ </div>
24
+
25
+ <br/>
26
+
27
+
28
+
29
+ ## Usage
30
+
31
+ ### Next.js App Router
32
+
33
+ The Saleor Auth SDK supports both **Next.js 13/14** and **Next.js 15**, but due to changes in how cookies are handled, different storage methods are required for each version.
34
+
35
+ ---
36
+
37
+ ## **Using Saleor Auth SDK in Next.js 13/14**
38
+ Next.js 13 and 14 support **synchronous cookies**, which means you can use the `getNextServerCookiesStorage` function without issues.
39
+
40
+ ## **Setting Up the Auth Client (Next.js 13/14)**
41
+
42
+ ```ts
43
+ import { createSaleorAuthClient } from "@saleor/auth-sdk";
44
+ import { getNextServerCookiesStorage } from "@saleor/auth-sdk/next/server";
45
+
46
+ const getServerAuthClient = () => {
47
+ const nextServerCookiesStorage = getNextServerCookiesStorage();
48
+ return createSaleorAuthClient({
49
+ saleorApiUrl: "…",
50
+ refreshTokenStorage: nextServerCookiesStorage,
51
+ accessTokenStorage: nextServerCookiesStorage,
52
+ });
53
+ };
54
+ ```
55
+
56
+ Logging in can be implemented via Server Actions:
57
+
58
+ ```tsx
59
+ <form
60
+ className="bg-white shadow-md rounded p-8"
61
+ action={async (formData) => {
62
+ "use server";
63
+
64
+ await getServerAuthClient().signIn(
65
+ {
66
+ email: formData.get("email").toString(),
67
+ password: formData.get("password").toString(),
68
+ },
69
+ { cache: "no-store" },
70
+ );
71
+ }}
72
+ >
73
+ {/* … rest of the form … */}
74
+ </form>
75
+ ```
76
+
77
+ ## **Using Saleor Auth SDK in Next.js 15**
78
+
79
+ Next.js 15 introduces asynchronous cookies, requiring the use of getNextServerCookiesStorageAsync instead.
80
+
81
+ ## **Setting Up the Auth Client (Next.js 15)**
82
+
83
+ ```ts
84
+ import { createSaleorAuthClient } from "@saleor/auth-sdk";
85
+ import { getNextServerCookiesStorageAsync } from "@saleor/auth-sdk/next/server";
86
+
87
+ const getServerAuthClient = async () => {
88
+ const nextServerCookiesStorage = await getNextServerCookiesStorageAsync();
89
+ return createSaleorAuthClient({
90
+ saleorApiUrl: "…",
91
+ refreshTokenStorage: nextServerCookiesStorage,
92
+ accessTokenStorage: nextServerCookiesStorage,
93
+ });
94
+ };
95
+ ```
96
+
97
+ Logging in can be implemented via Server Actions:
98
+
99
+ ```tsx
100
+ <form
101
+ className="bg-white shadow-md rounded p-8"
102
+ action={async (formData) => {
103
+ "use server";
104
+
105
+ await (await getServerAuthClient()).signIn(
106
+ {
107
+ email: formData.get("email").toString(),
108
+ password: formData.get("password").toString(),
109
+ },
110
+ { cache: "no-store" },
111
+ );
112
+ }}
113
+ >
114
+ {/* … rest of the form … */}
115
+ </form>
116
+ ```
117
+
118
+ Then, you can use `saleorAuthClient.fetchWithAuth` directly for any queries and mutations.
119
+
120
+ For a full working example, see the [Saleor Auth SDK example](https://github.com/saleor/example-auth-sdk/tree/app/ssr/page.tsx).
121
+
122
+ ### Next.js Pages Router with [Apollo Client](https://www.apollographql.com/docs/react/)
123
+
124
+ <details>
125
+ <summary>Step-by-step video tutorial</summary>
126
+
127
+ Check the following [step-by-step video](https://www.youtube.com/watch?v=XY1t8JiPwk0) guide on how to set this up.
128
+ [![Saleor Auth with Next.js](https://img.youtube.com/vi/t6nxBk7JHCw/0.jpg)](https://www.youtube.com/watch?v=XY1t8JiPwk0)
129
+
130
+ </details>
131
+
132
+ When using Next.js (Pages Router) along with [Apollo Client](https://www.apollographql.com/docs/react/), there are two essential steps to setting up your application. First, you have to surround your application's root with two providers: `<SaleorAuthProvider>` and `<ApolloProvider>`.
133
+
134
+ `<SaleorAuthProvider>` comes from our React.js-auth package, located at `@saleor/auth-sdk/react`, and it needs to be set up with the Saleor auth client instance.
135
+
136
+ The `<ApolloProvider>` comes from `@apollo/client` and it needs the live GraphQL client instance, which is enhanced with the authenticated `fetch` that comes from the Saleor auth client.
137
+
138
+ Lastly, you must run the `useAuthChange` hook. This links the `onSignedOut` and `onSignedIn` events.
139
+
140
+ Let's look at an example:
141
+
142
+ ```tsx
143
+ import { AppProps } from "next/app";
144
+ import { ApolloProvider, ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
145
+ import { createSaleorAuthClient } from "@saleor/auth-sdk";
146
+ import { SaleorAuthProvider, useAuthChange } from "@saleor/auth-sdk/react";
147
+
148
+ const saleorApiUrl = "<your Saleor API URL>";
149
+
150
+ // Saleor Client
151
+ const saleorAuthClient = createSaleorAuthClient({ saleorApiUrl });
152
+
153
+ // Apollo Client
154
+ const httpLink = createHttpLink({
155
+ uri: saleorApiUrl,
156
+ fetch: saleorAuthClient.fetchWithAuth,
157
+ });
158
+
159
+ export const apolloClient = new ApolloClient({
160
+ link: httpLink,
161
+ cache: new InMemoryCache(),
162
+ });
163
+
164
+ export default function App({ Component, pageProps }: AppProps) {
165
+ useAuthChange({
166
+ saleorApiUrl,
167
+ onSignedOut: () => apolloClient.resetStore(),
168
+ onSignedIn: () => {
169
+ apolloClient.refetchQueries({ include: "all" });
170
+ },
171
+ });
172
+
173
+ return (
174
+ <SaleorAuthProvider client={saleorAuthClient}>
175
+ <ApolloProvider client={apolloClient}>
176
+ <Component {...pageProps} />
177
+ </ApolloProvider>
178
+ </SaleorAuthProvider>
179
+ );
180
+ }
181
+ ```
182
+
183
+ Then, in your register, login and logout forms you can use the auth methods (`signIn`, `signOut`, `isAuthenticating`) provided by the `useSaleorAuthContext()`. For example, `signIn` is usually triggered when submitting the login form credentials.
184
+
185
+ ```tsx
186
+ import React, { FormEvent } from "react";
187
+ import { useSaleorAuthContext } from "@saleor/auth-sdk/react";
188
+ import { gql, useQuery } from "@apollo/client";
189
+
190
+ const CurrentUserDocument = gql`
191
+ query CurrentUser {
192
+ me {
193
+ id
194
+ email
195
+ firstName
196
+ lastName
197
+ avatar {
198
+ url
199
+ alt
200
+ }
201
+ }
202
+ }
203
+ `;
204
+
205
+ export default function LoginPage() {
206
+ const { signIn, signOut } = useSaleorAuthContext();
207
+
208
+ const { data: currentUser, loading } = useQuery(CurrentUserDocument);
209
+
210
+ const submitHandler = async (event: FormEvent<HTMLFormElement>) => {
211
+ event.preventDefault();
212
+
213
+ const result = await signIn({
214
+ email: "admin@example.com",
215
+ password: "admin",
216
+ });
217
+
218
+ if (result.data.tokenCreate.errors.length) {
219
+ // handle errors
220
+ }
221
+ };
222
+
223
+ if (loading) {
224
+ return <div>Loading...</div>;
225
+ }
226
+
227
+ return (
228
+ <main>
229
+ {currentUser?.me ? (
230
+ <>
231
+ <div>Display user {JSON.stringify(currentUser)}</div>
232
+ <button className="button" onClick={() => signOut()}>
233
+ Log Out
234
+ </button>
235
+ </>
236
+ ) : (
237
+ <div>
238
+ <form onSubmit={submitHandler}>
239
+ {/* You must connect your inputs to state or use a form library such as react-hook-form */}
240
+ <input type="email" name="email" placeholder="Email" />
241
+ <input type="password" name="password" placeholder="Password" />
242
+ <button className="button" type="submit">
243
+ Log In
244
+ </button>
245
+ </form>
246
+ </div>
247
+ )}
248
+ </main>
249
+ );
250
+ }
251
+ ```
252
+
253
+ ### Next.js (Pages Router) with [urql](https://formidable.com/open-source/urql/)
254
+
255
+ When using Next.js (Pages Router) along with [urql](https://formidable.com/open-source/urql/) client, there are two essential steps to setting up your application. First, you have to surround your application's root with two providers: `<SaleorAuthProvider>` and `<Provider>`.
256
+
257
+ `<SaleorAuthProvider>` comes from our React.js-auth package, located at `@saleor/auth-sdk/react`, and it needs to be set up with the Saleor auth client.
258
+
259
+ The `<Provider>` comes from `urql` and it needs the GraphQL client instance, which is enhanced with the authenticated `fetch` that comes from the Saleor auth client.
260
+
261
+ Lastly, you must run the `useAuthChange` hook. This links the `onSignedOut` and `onSignedIn` events and is meant to refresh the GraphQL store and in-flight active GraphQL queries.
262
+
263
+ Let's look at an example:
264
+
265
+ ```tsx
266
+ import { AppProps } from "next/app";
267
+ import { Provider, cacheExchange, fetchExchange, ssrExchange } from "urql";
268
+ import { SaleorAuthProvider, useAuthChange } from "@saleor/auth-sdk/react";
269
+
270
+ const saleorApiUrl = "<your Saleor API URL>";
271
+
272
+ const saleorAuthClient = createSaleorAuthClient({ saleorApiUrl });
273
+
274
+ const makeUrqlClient = () =>
275
+ createClient({
276
+ url: saleorApiUrl,
277
+ fetch: saleorAuthClient.fetchWithAuth,
278
+ exchanges: [cacheExchange, fetchExchange],
279
+ });
280
+
281
+ export default function App({ Component, pageProps }: AppProps) {
282
+ // https://github.com/urql-graphql/urql/issues/297#issuecomment-504782794
283
+ const [urqlClient, setUrqlClient] = useState<Client>(makeUrqlClient());
284
+
285
+ useAuthChange({
286
+ saleorApiUrl,
287
+ onSignedOut: () => setUrqlClient(makeUrqlClient()),
288
+ onSignedIn: () => setUrqlClient(makeUrqlClient()),
289
+ });
290
+
291
+ return (
292
+ <SaleorAuthProvider client={saleorAuthClient}>
293
+ <Provider value={urqlClient}>
294
+ <Component {...pageProps} />
295
+ </Provider>
296
+ </SaleorAuthProvider>
297
+ );
298
+ }
299
+ ```
300
+
301
+ Then, in your register, login and logout forms you can use the auth methods (`signIn`, `signOut`) provided by the `useSaleorAuthContext()`. For example, `signIn` is usually triggered when submitting the login form credentials.
302
+
303
+ ```tsx
304
+ import React, { FormEvent } from "react";
305
+ import { useSaleorAuthContext } from "@saleor/auth-sdk/react";
306
+ import { gql, useQuery } from "urql";
307
+
308
+ const CurrentUserDocument = gql`
309
+ query CurrentUser {
310
+ me {
311
+ id
312
+ email
313
+ firstName
314
+ lastName
315
+ avatar {
316
+ url
317
+ alt
318
+ }
319
+ }
320
+ }
321
+ `;
322
+
323
+ export default function LoginPage() {
324
+ const { signIn, signOut } = useSaleorAuthContext();
325
+
326
+ const [{ data: currentUser, fetching: loading }] = useQuery({
327
+ query: CurrentUserDocument,
328
+ pause: isAuthenticating,
329
+ });
330
+
331
+ const submitHandler = async (event: FormEvent<HTMLFormElement>) => {
332
+ event.preventDefault();
333
+
334
+ const result = await signIn({
335
+ email: "admin@example.com",
336
+ password: "admin",
337
+ });
338
+
339
+ if (result.data.tokenCreate.errors) {
340
+ // handle errors
341
+ }
342
+ };
343
+
344
+ if (loading) {
345
+ return <div>Loading...</div>;
346
+ }
347
+
348
+ return (
349
+ <main>
350
+ {currentUser?.me ? (
351
+ <>
352
+ <div>Display user {JSON.stringify(currentUser)}</div>
353
+ <button className="button" onClick={() => signOut()}>
354
+ Log Out
355
+ </button>
356
+ </>
357
+ ) : (
358
+ <div>
359
+ <form onSubmit={submitHandler}>
360
+ {/* You must connect your inputs to state or use a form library such as react-hook-form */}
361
+ <input type="email" name="email" placeholder="Email" />
362
+ <input type="password" name="password" placeholder="Password" />
363
+ <button className="button" type="submit">
364
+ Log In
365
+ </button>
366
+ </form>
367
+ </div>
368
+ )}
369
+ </main>
370
+ );
371
+ }
372
+ ```
373
+
374
+ ### Next.js (Pages Router) with OpenID Connect
375
+
376
+ Setup `_app.tsx` as described above. In your login component trigger the external auth flow using the following code:
377
+
378
+ ```tsx
379
+ import { useSaleorAuthContext, useSaleorExternalAuth } from "@saleor/auth-sdk/react";
380
+ import { ExternalProvider } from "@saleor/auth-sdk";
381
+ import Link from "next/link";
382
+ import { gql, useQuery } from "@apollo/client";
383
+
384
+ export default function Home() {
385
+ const {
386
+ loading: isLoadingCurrentUser,
387
+ error,
388
+ data,
389
+ } = useQuery(gql`
390
+ query CurrentUser {
391
+ me {
392
+ id
393
+ email
394
+ firstName
395
+ lastName
396
+ }
397
+ }
398
+ `);
399
+ const { authURL, loading: isLoadingExternalAuth } = useSaleorExternalAuth({
400
+ saleorApiUrl,
401
+ provider: ExternalProvider.OpenIDConnect,
402
+ redirectURL: "<your Next.js app>/api/auth/callback",
403
+ });
404
+
405
+ const { signOut } = useSaleorAuthContext();
406
+
407
+ if (isLoadingExternalAuth || isLoadingCurrentUser) {
408
+ return <div>Loading...</div>;
409
+ }
410
+
411
+ if (data?.me) {
412
+ return (
413
+ <div>
414
+ {JSON.stringify(data)}
415
+ <button onClick={() => signOut()}>Logout</button>
416
+ </div>
417
+ );
418
+ }
419
+ if (authURL) {
420
+ return (
421
+ <div>
422
+ <Link href={authURL}>Login</Link>
423
+ </div>
424
+ );
425
+ }
426
+ return <div>Something went wrong</div>;
427
+ }
428
+ ```
429
+
430
+ You also need to define the auth callback. In `pages/api/auth` create the `callback.ts` with the following content:
431
+
432
+ ```ts
433
+ import { ExternalProvider, SaleorExternalAuth } from "@saleor/auth-sdk";
434
+ import { createSaleorExternalAuthHandler } from "@saleor/auth-sdk/next";
435
+
436
+ const externalAuth = new SaleorExternalAuth("<your Saleor instance URL>", ExternalProvider.OpenIDConnect);
437
+
438
+ export default createSaleorExternalAuthHandler(externalAuth);
439
+ ```
440
+
441
+ ## FAQ
442
+
443
+ ## How do I reset password?
444
+
445
+ The `SaleorAuthClient` class provides you with a reset password method. If the reset password mutation is successful, it will log you in automatically, just like after a regular sign-in. The [`onSignIn` method of `useAuthChange` hook](#how-do-i-tell-my-graphql-client-to-refresh-queries-on-signin--signout) will also be triggered.
446
+
447
+ ```javascript
448
+ const { resetPassword } = useSaleorAuthContext();
449
+
450
+ const response = await resetPassword({
451
+ email: "example@mail.com",
452
+ password: "newPassword",
453
+ token: "apiToken",
454
+ });
455
+ ```
456
+
457
+
458
+
459
+ ## Releasing
460
+
461
+ 1. Merge all needed changes to the `main` branch.
462
+ 2. Use [the example](https://github.com/saleor/examples/tree/main/example-auth-nextjs-apollo-urql) to manually test changes. First run `pnpm run build` in auth-sdk, then `pnpm link` from the example to locally link the package.
463
+ 3. Update (increment) package version in package.json.
464
+ 4. Open a PR and merge release changes to the `main` branch.
465
+ 5. Create a tag with a version, e.g. `1.0.5` and push it with `--tags`.
466
+ 6. Create Github release from the tag.
467
+ 7. Run `pnpm publish` from local machine, from latest `main` branch.
468
+
469
+ TODO: Add `changesets` package for automated release flow and workflow similar to @saleor/app-sdk