Raw
1 import { AuthTypes, HttpTypes } from "@medusajs/types"
2 import { Client } from "../client.js"
3 import { ClientHeaders, Config } from "../types.js"
4
5 /**
6 * Redirect response returned when an authentication provider requires the user
7 * to continue authentication on another page.
8 */
9 export type AuthRedirectResponse = {
10 /**
11 * The URL to redirect the user to.
12 */
13 location: string
14 }
15
16 /**
17 * Response returned when authentication succeeds but must be completed with
18 * a multi-factor authentication (MFA) challenge before issuing a token.
19 */
20 export type AuthMfaRequiredResponse = {
21 /**
22 * A token without an actor type (permissions) attached to it. Used to request and confirm verifications.
23 */
24 token: string
25 /**
26 * Indicates that the client must complete the returned MFA challenge.
27 */
28 mfa_required: true
29 /**
30 * The MFA challenge to complete.
31 */
32 mfa_challenge: AuthTypes.AuthMfaChallengeDTO
33 }
34
35 /**
36 * Response returned when authentication succeeds but must be completed with
37 * verification before issuing a token.
38 *
39 * @since 2.15.5
40 */
41 export type AuthVerificationRequiredResponse = {
42 /**
43 * A token without an actor type (permissions) attached to it. Used to request and confirm verifications.
44 */
45 token: string
46 /**
47 * Indicates that the client must complete verification.
48 */
49 verification_required: true
50 /**
51 * The verification state to show to the caller.
52 */
53 verification?: AuthTypes.AuthVerificationDTO
54 }
55
56 /**
57 * Response returned from a registration attempt.
58 *
59 * @since 2.15.5
60 */
61 export type AuthRegisterResponse = string
62
63 /**
64 * Response returned from an authentication attempt.
65 */
66 export type AuthLoginResponse =
67 | string
68 | AuthRedirectResponse
69 | AuthMfaRequiredResponse
70 | AuthVerificationRequiredResponse
71
72 /**
73 * Response returned from an authentication callback.
74 */
75 export type AuthCallbackResponse =
76 | string
77 | AuthMfaRequiredResponse
78 | AuthVerificationRequiredResponse
79
80 /**
81 * Response returned from a token refresh attempt.
82 */
83 export type AuthRefreshResponse =
84 | { token: string }
85 | AuthMfaRequiredResponse
86 | AuthVerificationRequiredResponse
87
88 /**
89 * Response containing the authenticated identity's MFA factors.
90 */
91 export type AuthMfaListResponse = {
92 /**
93 * The MFA factors configured for the authenticated identity.
94 */
95 mfa_factors: AuthTypes.AuthMfaDTO[]
96 }
97
98 /**
99 * Response returned when starting MFA setup.
100 */
101 export type AuthMfaSetupResponse = {
102 /**
103 * The pending MFA factor.
104 */
105 mfa_factor: AuthTypes.AuthMfaDTO
106 /**
107 * The setup secret. For TOTP, this can be entered manually in an
108 * authenticator app.
109 */
110 secret?: string
111 /**
112 * The setup URI. For TOTP, this can be rendered as a QR code.
113 */
114 otpauth_url?: string
115 }
116
117 /**
118 * Response containing a single MFA factor.
119 */
120 export type AuthMfaFactorResponse = {
121 /**
122 * The MFA factor.
123 */
124 mfa_factor: AuthTypes.AuthMfaDTO
125 }
126
127 /**
128 * Response containing newly generated MFA recovery codes.
129 */
130 export type AuthMfaRecoveryCodesResponse = {
131 /**
132 * The recovery codes. These are only returned once and should be stored by
133 * the user.
134 */
135 recovery_codes: string[]
136 }
137
138 /**
139 * Payload used to start MFA setup.
140 */
141 export type AuthMfaStartPayload = {
142 /**
143 * The MFA provider to set up.
144 */
145 provider: AuthTypes.AuthMfaProviderMethod
146 /**
147 * Optional label for the MFA factor.
148 */
149 label?: string | null
150 /**
151 * Optional issuer name. For TOTP, authenticator apps show this as the
152 * service name.
153 */
154 issuer?: string
155 /**
156 * Optional metadata to store with the MFA factor.
157 */
158 metadata?: Record<string, unknown> | null
159 }
160
161 /**
162 * Payload used to verify a pending MFA setup.
163 */
164 export type AuthMfaVerifyPayload = {
165 /**
166 * The verification code from the MFA provider.
167 */
168 code: string
169 }
170
171 /**
172 * Payload used to disable an MFA factor.
173 */
174 export type AuthMfaDisablePayload = {
175 /**
176 * Optional challenge method used to authorize disabling MFA when configured.
177 */
178 method?: AuthTypes.AuthMfaChallengeMethod
179 /**
180 * Optional verification code for the selected challenge method.
181 */
182 code?: string
183 }
184
185 /**
186 * Payload used to generate recovery codes.
187 */
188 export type AuthMfaGenerateRecoveryCodesPayload = {
189 /**
190 * Number of recovery codes to generate.
191 */
192 count?: number
193 }
194
195 /**
196 * Payload used to verify an MFA challenge.
197 */
198 export type AuthMfaVerifyChallengePayload = {
199 /**
200 * The MFA challenge method used for verification.
201 */
202 method: AuthTypes.AuthMfaChallengeMethod
203 /**
204 * The verification code for the selected challenge method.
205 */
206 code: string
207 }
208
209 /**
210 * Payload used to request a verification token.
211 *
212 * @since 2.15.5
213 */
214 export type AuthVerificationRequestPayload = {
215 /**
216 * The provider identity to verify.
217 */
218 entity_id: string
219 /**
220 * The kind of entity being verified, such as `email` or `phone_number`.
221 */
222 entity_type: string
223 /**
224 * The verification provider to use. Defaults to `token`.
225 */
226 code_provider?: string
227 /**
228 * Optional metadata to include in the verification request event.
229 */
230 metadata?: Record<string, unknown>
231 }
232
233 /**
234 * Payload used to confirm a verification code.
235 *
236 * @since 2.15.5
237 */
238 export type AuthVerificationConfirmPayload = {
239 /**
240 * The verification code delivered to the user, such as an OTP or pseudorandom token.
241 */
242 code: string
243 /**
244 * The verification provider to use. Defaults to `token`.
245 */
246 code_provider?: string
247 }
248
249 /**
250 * Response returned after requesting a verification token.
251 *
252 * @since 2.15.5
253 */
254 export type AuthVerificationRequestResponse = {
255 /**
256 * The verification state.
257 */
258 verification: AuthTypes.AuthVerificationDTO
259 }
260
261 /**
262 * Response returned after confirming verification.
263 *
264 * @since 2.15.5
265 */
266 export type AuthVerificationConfirmResponse = {
267 /**
268 * The verified entity identifier.
269 */
270 entity_id: string
271 /**
272 * The kind of entity that was verified.
273 */
274 entity_type: string
275 /**
276 * The verification provider that confirmed the verification.
277 */
278 code_provider: string
279 /**
280 * When the verification was confirmed.
281 */
282 verified_at: Date | string
283 }
284
285 type AuthProviderResponse = {
286 token?: string
287 location?: string
288 mfa_required?: true
289 mfa_challenge?: AuthTypes.AuthMfaChallengeDTO
290 verification_required?: true
291 verification?: AuthTypes.AuthVerificationDTO
292 }
293
294 /**
295 * This class provides methods for authentication operations including login, registration, logout, and MFA management.
296 */
297 export class Auth {
298 private client: Client
299 private config: Config
300
301 constructor(client: Client, config: Config) {
302 this.client = client
303 this.config = config
304 }
305
306 /**
307 * Methods for managing and completing multi-factor authentication (MFA).
308 */
309 mfa = {
310 /**
311 * This method retrieves the MFA factors configured for the authenticated
312 * identity. It sends a request to the
313 * [List MFA Factors](https://docs.medusajs.com/api/admin/multi-factor-authentication/list-mfa-factors)
314 * API route.
315 *
316 * @param headers - Headers to pass in the request.
317 * @returns The configured MFA factors.
318 *
319 * @tags auth
320 *
321 * @example
322 * const { mfa_factors } = await sdk.auth.mfa.list()
323 */
324 list: async (headers?: ClientHeaders) => {
325 return await this.client.fetch<AuthMfaListResponse>("/auth/mfa/factors", {
326 headers,
327 })
328 },
329
330 /**
331 * This method starts MFA setup for the authenticated identity. It sends a
332 * request to the
333 * [Create MFA Factor](https://docs.medusajs.com/api/admin/multi-factor-authentication/start-mfa-factor-enrollment)
334 * API route.
335 *
336 * @param body - The MFA setup details.
337 * @param headers - Headers to pass in the request.
338 * @returns The pending MFA factor and any setup details returned by the provider.
339 *
340 * @tags auth
341 *
342 * @example
343 * const setup = await sdk.auth.mfa.start({
344 * provider: "totp",
345 * label: "Authenticator app"
346 * })
347 *
348 * // Render setup.otpauth_url as a QR code or show setup.secret manually.
349 */
350 start: async (body: AuthMfaStartPayload, headers?: ClientHeaders) => {
351 return await this.client.fetch<AuthMfaSetupResponse>(
352 "/auth/mfa/factors",
353 {
354 method: "POST",
355 body,
356 headers,
357 }
358 )
359 },
360
361 /**
362 * This method verifies a pending MFA factor setup. It sends a request to the
363 * [Verify MFA Factor](https://docs.medusajs.com/api/admin/multi-factor-authentication/verify-and-enable-mfa-factor)
364 * API route.
365 *
366 * @param id - The ID of the MFA factor to verify.
367 * @param body - The verification details.
368 * @param headers - Headers to pass in the request.
369 * @returns The verified MFA factor.
370 *
371 * @tags auth
372 *
373 * @example
374 * const { mfa_factor } = await sdk.auth.mfa.verify("authmfa_123", {
375 * code: "123456"
376 * })
377 */
378 verify: async (
379 id: string,
380 body: AuthMfaVerifyPayload,
381 headers?: ClientHeaders
382 ) => {
383 return await this.client.fetch<AuthMfaFactorResponse>(
384 `/auth/mfa/factors/${id}/verify`,
385 {
386 method: "POST",
387 body,
388 headers,
389 }
390 )
391 },
392
393 /**
394 * This method disables an MFA factor for the authenticated identity. It
395 * sends a request to the
396 * [Delete MFA Factor](https://docs.medusajs.com/api/admin/auth/disable-mfa-factor)
397 * API route.
398 *
399 * @param id - The ID of the MFA factor to disable.
400 * @param body - Optional verification details required by the server configuration.
401 * @param headers - Headers to pass in the request.
402 * @returns The disabled MFA factor.
403 *
404 * @tags auth
405 *
406 * @example
407 * const { mfa_factor } = await sdk.auth.mfa.disable("authmfa_123")
408 */
409 disable: async (
410 id: string,
411 body?: AuthMfaDisablePayload,
412 headers?: ClientHeaders
413 ) => {
414 return await this.client.fetch<AuthMfaFactorResponse>(
415 `/auth/mfa/factors/${id}`,
416 {
417 method: "DELETE",
418 body: body ?? {},
419 headers,
420 }
421 )
422 },
423
424 /**
425 * This method generates new recovery codes for the authenticated identity.
426 * It sends a request to the
427 * [Generate MFA Recovery Codes](https://docs.medusajs.com/api/admin/multi-factor-authentication/generate-mfa-recovery-codes)
428 * API route.
429 *
430 * @param body - Optional recovery code generation details.
431 * @param headers - Headers to pass in the request.
432 * @returns The generated recovery codes.
433 *
434 * @tags auth
435 *
436 * @example
437 * const { recovery_codes } = await sdk.auth.mfa.generateRecoveryCodes()
438 */
439 generateRecoveryCodes: async (
440 body?: AuthMfaGenerateRecoveryCodesPayload,
441 headers?: ClientHeaders
442 ) => {
443 return await this.client.fetch<AuthMfaRecoveryCodesResponse>(
444 "/auth/mfa/recovery-codes",
445 {
446 method: "POST",
447 body: body ?? {},
448 headers,
449 }
450 )
451 },
452
453 /**
454 * This method verifies an MFA challenge returned from `sdk.auth.login` or
455 * `sdk.auth.callback`. It sends a request to the
456 * [Verify MFA Challenge](https://docs.medusajs.com/api/admin/multi-factor-authentication/verify-mfa-challenge)
457 * API route.
458 *
459 * If verification succeeds, the returned token is stored based on the SDK's
460 * auth configuration, matching `sdk.auth.login`.
461 *
462 * @param id - The ID of the MFA challenge to verify.
463 * @param body - The challenge verification details.
464 * @param headers - Headers to pass in the request.
465 * @returns The authentication JWT token.
466 *
467 * @tags auth
468 *
469 * @example
470 * const result = await sdk.auth.login("user", "emailpass", {
471 * email: "user@example.com",
472 * password: "secret"
473 * })
474 *
475 * if (typeof result === "object" && "mfa_challenge" in result) {
476 * await sdk.auth.mfa.verifyChallenge(result.mfa_challenge.id, {
477 * method: "totp",
478 * code: "123456"
479 * })
480 * }
481 */
482 verifyChallenge: async (
483 id: string,
484 body: AuthMfaVerifyChallengePayload,
485 headers?: ClientHeaders
486 ) => {
487 const { token } = await this.client.fetch<{ token: string }>(
488 `/auth/mfa/challenges/${id}/verify`,
489 {
490 method: "POST",
491 body,
492 headers,
493 }
494 )
495
496 await this.setToken_(token)
497 return token
498 },
499 }
500
501 /**
502 * Methods for requesting and confirming verification.
503 *
504 * @since 2.15.5
505 */
506 verification = {
507 /**
508 * This method requests a verification token for an auth identity.
509 *
510 * @param body - The verification request details.
511 * @param headers - Headers to pass in the request. Must include a bearer token for the auth identity.
512 *
513 * @tags auth
514 */
515 request: async (
516 body: AuthVerificationRequestPayload,
517 headers?: ClientHeaders
518 ) => {
519 return await this.client.fetch<AuthVerificationRequestResponse>(
520 `/auth/verification/request`,
521 {
522 method: "POST",
523 body,
524 headers,
525 }
526 )
527 },
528
529 /**
530 * This method confirms a verification code.
531 *
532 * @param body - The verification code details.
533 * @param headers - Headers to pass in the request.
534 *
535 * @tags auth
536 */
537 confirm: async (
538 body: AuthVerificationConfirmPayload,
539 headers?: ClientHeaders
540 ) => {
541 return await this.client.fetch<AuthVerificationConfirmResponse>(
542 `/auth/verification/confirm`,
543 {
544 method: "POST",
545 body,
546 headers,
547 }
548 )
549 },
550 }
551
552 /**
553 * This method is used to retrieve a registration JWT token for a user, customer, or custom actor type. It sends a request to the
554 * [Retrieve Registration Token API route](https://docs.medusajs.com/api/store/auth/retrieve-registration-jwt-token).
555 *
556 * Then, it stores the returned token and passes it in the header of subsequent requests. So, you can call the
557 * [store.customer.create](https://docs.medusajs.com/resources/references/js-sdk/store/customer#create) method,
558 * for example, after calling this method.
559 *
560 * Learn more in the [JS SDK Authentication](https://docs.medusajs.com/resources/js-sdk/auth/overview) guide.
561 *
562 * @param actor - The actor type. For example, `user` for admin user, or `customer` for customer.
563 * @param method - The authentication provider to use. For example, `emailpass` or `google`.
564 * @param payload - The data to pass in the request's body for authentication. When using the `emailpass` provider,
565 * you pass the email and password.
566 * @param options - Optional behavior for multi-step registration responses.
567 * @returns The JWT token used for registration later.
568 *
569 * @tags auth
570 *
571 * @example
572 * await sdk.auth.register(
573 * "customer",
574 * "emailpass",
575 * {
576 * email: "customer@gmail.com",
577 * password: "supersecret"
578 * }
579 * )
580 *
581 * // all subsequent requests will use the token in the header
582 * const { customer } = await sdk.store.customer.create({
583 * email: "customer@gmail.com",
584 * password: "supersecret"
585 * })
586 */
587 register = async (
588 actor: string,
589 method: string,
590 payload: HttpTypes.AdminSignUpWithEmailPassword | Record<string, unknown>
591 ): Promise<AuthRegisterResponse> => {
592 const { token } = await this.client.fetch<AuthProviderResponse>(
593 `/auth/${actor}/${method}/register`,
594 {
595 method: "POST",
596 body: payload,
597 }
598 )
599
600 if (!token) {
601 throw new Error("Unexpected registration response")
602 }
603
604 // The reason we don't use setToken_ (i.e. start a session) here is because the token doesn't have any actor types attached to it yet.
605 // The token should be sent in a separate request to create an actor type, after which we can initiate the session.
606 this.client.setToken(token)
607 return token
608 }
609
610 /**
611 * This method retrieves the JWT authenticated token for an admin user, customer, or custom
612 * actor type. It sends a request to the [Authenticate API Route](https://docs.medusajs.com/api/admin/auth/authenticate-user).
613 *
614 * ### Third-Party Authentication
615 *
616 * If the API route returns a `location` property, it means that the authentication requires additional steps,
617 * typically in a third-party service. The `location` property is returned so that you
618 * can redirect the user to the appropriate page.
619 *
620 * :::note
621 *
622 * For an example of implementing third-party authentication, refer to the
623 * [Third-Party Login in Storefront](https://docs.medusajs.com/resources/storefront-development/customers/third-party-login) guide.
624 *
625 * :::
626 *
627 * ### Session Authentication
628 *
629 * If the `auth.type` of the SDK is set to `session`, this method will also send a request to the
630 * [Set Authentication Session API route](https://docs.medusajs.com/api/admin/auth/set-authentication-session).
631 *
632 * Learn more in the [JS SDK Authentication](https://docs.medusajs.com/resources/js-sdk/auth/overview) guide.
633 *
634 * ### Automatic Authentication
635 *
636 * If the authentication was successful, subsequent requests using the SDK will automatically have the necessary authentication headers / session
637 * set, based on your JS SDK authentication configurations.
638 *
639 * Learn more in the [JS SDK Authentication](https://docs.medusajs.com/resources/js-sdk/auth/overview) guide.
640 *
641 * @param actor - The actor type. For example, `user` for admin user, or `customer` for customer.
642 * @param method - The authentication provider to use. For example, `emailpass` or `google`.
643 * @param payload - The data to pass in the request's body for authentication. When using the `emailpass` provider,
644 * you pass the email and password.
645 * @returns The authentication JWT token
646 *
647 * @tags auth
648 *
649 * @example
650 * const result = await sdk.auth.login(
651 * "customer",
652 * "emailpass",
653 * {
654 * email: "customer@gmail.com",
655 * password: "supersecret"
656 * }
657 * )
658 *
659 * if (typeof result !== "string") {
660 * alert("Authentication requires additional steps")
661 * // replace with the redirect logic of your application
662 * window.location.href = result.location
663 * return
664 * }
665 *
666 * // customer is now authenticated
667 * // all subsequent requests will use the token in the header
668 * const { customer } = await sdk.store.customer.retrieve()
669 */
670 login = async (
671 actor: string,
672 method: string,
673 payload: HttpTypes.AdminSignInWithEmailPassword | Record<string, unknown>
674 ): Promise<AuthLoginResponse> => {
675 // There will either be token, location, MFA challenge, or verification returned from the backend.
676 const {
677 token,
678 location,
679 mfa_challenge,
680 verification_required,
681 verification,
682 } = await this.client.fetch<AuthProviderResponse>(
683 `/auth/${actor}/${method}`,
684 {
685 method: "POST",
686 body: payload,
687 }
688 )
689
690 // In the case of an oauth login, we return the redirect location to the caller.
691 // They can decide if they do an immediate redirect or put it in an <a> tag.
692 if (location) {
693 return { location }
694 }
695
696 if (!token) {
697 throw new Error("Unexpected authentication response")
698 }
699
700 await this.setToken_(token)
701
702 if (verification_required) {
703 return {
704 verification_required: true,
705 verification,
706 token,
707 }
708 }
709
710 if (mfa_challenge) {
711 return {
712 mfa_required: true,
713 mfa_challenge,
714 token,
715 }
716 }
717
718 return token
719 }
720
721 /**
722 * This method is used to validate an Oauth callback from a third-party service, such as Google, for an admin user, customer, or custom actor types.
723 * It sends a request to the [Validate Authentication Callback](https://docs.medusajs.com/api/admin/auth/validate-authentication-callback).
724 *
725 * The method stores the returned token and passes it in the header of subsequent requests. So, you can call the
726 * [store.customer.create](https://docs.medusajs.com/resources/references/js-sdk/store/customer#create) or {@link refresh} methods,
727 * for example, after calling this method.
728 *
729 * Learn more in the [JS SDK Authentication](https://docs.medusajs.com/resources/js-sdk/auth/overview) guide.
730 *
731 * @param actor - The actor type. For example, `user` for admin user, or `customer`.
732 * @param method - The authentication provider to use. For example, `google`.
733 * @param query - The query parameters from the Oauth callback, which should be passed to the API route. This includes query parameters like
734 * `code` and `state`.
735 * @returns The authentication JWT token
736 *
737 * @tags auth
738 *
739 * @example
740 * await sdk.auth.callback(
741 * "customer",
742 * "google",
743 * {
744 * code: "123",
745 * state: "456"
746 * }
747 * )
748 *
749 * // all subsequent requests will use the token in the header
750 * const { customer } = await sdk.store.customer.create({
751 * email: "customer@gmail.com",
752 * password: "supersecret"
753 * })
754 *
755 * @privateRemarks
756 * The callback expects all query parameters from the Oauth callback to be passed to
757 * the backend, and the provider is in charge of parsing and validating them
758 */
759 callback = async (
760 actor: string,
761 method: string,
762 query?: Record<string, unknown>
763 ): Promise<AuthCallbackResponse> => {
764 const { token, mfa_challenge, verification_required, verification } =
765 await this.client.fetch<AuthProviderResponse>(
766 `/auth/${actor}/${method}/callback`,
767 {
768 method: "GET",
769 query,
770 }
771 )
772
773 if (!token) {
774 throw new Error("Unexpected authentication callback response")
775 }
776
777 await this.setToken_(token)
778
779 if (verification_required) {
780 return {
781 verification_required: true,
782 verification,
783 token,
784 }
785 }
786
787 if (mfa_challenge && token) {
788 return {
789 mfa_required: true,
790 mfa_challenge,
791 token,
792 }
793 }
794
795 return token
796 }
797
798 /**
799 * This method refreshes a JWT authentication token, which is useful after validating the Oauth callback
800 * with {@link callback}. It sends a request to the [Refresh Authentication Token API route](https://docs.medusajs.com/api/admin/auth/refresh-authentication-token).
801 *
802 * The method stores the returned token and passes it in the header of subsequent requests. So, you can call other
803 * methods that require authentication after calling this method.
804 *
805 * Learn more in the [JS SDK Authentication](https://docs.medusajs.com/resources/js-sdk/auth/overview) guide.
806 *
807 * For an example of implementing third-party authentication, refer to the
808 * [Third-Party Login in Storefront](https://docs.medusajs.com/resources/storefront-development/customers/third-party-login) guide.
809 *
810 * @param headers - Headers to pass in the request
811 *
812 * @returns The refreshed JWT authentication token, or any requirements such as MFA or verification.
813 *
814 * @tags auth
815 *
816 * @example
817 * const token = await sdk.auth.refresh()
818 *
819 * // all subsequent requests will use the token in the header
820 * const { customer } = await sdk.store.customer.retrieve()
821 */
822 refresh = async (headers?: ClientHeaders) => {
823 const response = await this.client.fetch<AuthRefreshResponse>(
824 "/auth/token/refresh",
825 {
826 method: "POST",
827 headers,
828 }
829 )
830
831 // Putting the token in session after refreshing is only useful when the new token has updated info (eg. actor_id).
832 // Ideally we don't use the full JWT in session as key, but just store a pseudorandom key that keeps the rest of the auth context as value.
833 await this.setToken_(response.token)
834 return response
835 }
836
837 /**
838 * This method logs out the currently authenticated user based on your JS SDK authentication configurations.
839 *
840 * If the `auth.type` of the SDK is set to `session`, this method will also send a request to the
841 * [Delete Authentication Session API route](https://docs.medusajs.com/api/admin/auth/delete-authentication-session).
842 *
843 * The method also clears any stored tokens or sessions, based on your JS SDK authentication configurations.
844 *
845 * Learn more in the [JS SDK Authentication](https://docs.medusajs.com/resources/js-sdk/auth/overview) guide.
846 *
847 * @tags auth
848 *
849 * @example
850 * await sdk.auth.logout()
851 *
852 * // user is now logged out
853 * // you can't send any requests that require authentication
854 */
855 logout = async () => {
856 if (this.config?.auth?.type === "session") {
857 await this.client.fetch("/auth/session", {
858 method: "DELETE",
859 })
860 }
861
862 this.client.clearToken()
863 }
864
865 /**
866 * This method requests a reset password token for an admin user, customer, or custom actor type.
867 * It sends a request to the [Generate Reset Password Token API route](https://docs.medusajs.com/api/admin/auth/generate-reset-password-token).
868 *
869 * To reset the password later using the token delivered to the user, use the {@link updateProvider} method.
870 *
871 * Related guide: [How to allow customers to reset their passwords in a storefront](https://docs.medusajs.com/resources/storefront-development/customers/reset-password).
872 *
873 * @param actor - The actor type. For example, `user` for admin user, or `customer` for customer.
874 * @param provider - The authentication provider to use. For example, `emailpass`.
875 * @param body - The data required to identify the user.
876 *
877 * @tags auth
878 *
879 * @example
880 * sdk.auth.resetPassword(
881 * "customer",
882 * "emailpass",
883 * {
884 * identifier: "customer@gmail.com"
885 * }
886 * )
887 * .then(() => {
888 * // user receives token
889 * })
890 */
891 resetPassword = async (
892 actor: string,
893 provider: string,
894 body: {
895 /**
896 * The user's identifier. For example, when using the `emailpass` provider,
897 * this would be the user's email.
898 */
899 identifier: string
900 /**
901 * Optional metadata to include in the reset password request.
902 *
903 * @since 2.12.4
904 */
905 metadata?: Record<string, unknown>
906 }
907 ) => {
908 await this.client.fetch(`/auth/${actor}/${provider}/reset-password`, {
909 method: "POST",
910 body,
911 headers: { accept: "text/plain" }, // 201 Created response
912 })
913 }
914
915 /**
916 * This method is used to update user-related data authentication data.
917 *
918 * More specifically, use this method when updating the password of an admin user, customer, or
919 * custom actor type after requesting to reset their password with {@link resetPassword}.
920 *
921 * This method sends a request to [this API route](https://docs.medusajs.com/api/admin/auth/reset-password).
922 *
923 * Related guide: [How to allow customers to reset their passwords in a storefront](https://docs.medusajs.com/resources/storefront-development/customers/reset-password).
924 *
925 * @param actor - The actor type. For example, `user` for admin user, or `customer` for customer.
926 * @param provider - The authentication provider to use. For example, `emailpass`.
927 * @param body - The data necessary to update the user's authentication data. When resetting the user's password,
928 * send the `password` property.
929 *
930 * @tags auth
931 *
932 * @example
933 * sdk.auth.updateProvider(
934 * "customer",
935 * "emailpass",
936 * {
937 * password: "supersecret"
938 * },
939 * token
940 * )
941 * .then(() => {
942 * // password updated
943 * })
944 */
945 updateProvider = async (
946 actor: string,
947 provider: string,
948 body: HttpTypes.AdminUpdateProvider,
949 token: string
950 ) => {
951 await this.client.fetch(`/auth/${actor}/${provider}/update`, {
952 method: "POST",
953 body,
954 headers: { Authorization: `Bearer ${token}` },
955 })
956 }
957
958 /**
959 * This method lists the authentication providers available for an actor type.
960 * It sends a request to the [List Auth Providers API route](https://docs.medusajs.com/api/admin#auth_getactor_typeproviders).
961 *
962 * This is a public, pre-authentication endpoint. A frontend can use it to
963 * render the available login options, such as an email/password form or
964 * "Continue with ..." redirect buttons, based on each provider's `flow`.
965 *
966 * @param actor - The actor type. For example, `user` for admin user, or `customer` for customer.
967 * @param headers - Headers to pass in the request.
968 * @returns The list of available auth providers.
969 *
970 * @tags auth
971 *
972 * @example
973 * const { providers } = await sdk.auth.listProviders("user")
974 */
975 listProviders = async (actor: string, headers?: ClientHeaders) => {
976 return await this.client.fetch<HttpTypes.AuthProvidersListResponse>(
977 `/auth/${actor}/providers`,
978 {
979 method: "GET",
980 headers,
981 }
982 )
983 }
984
985 /**
986 * This method creates or links the `user` (admin) actor for a redirect-based
987 * authentication provider after a successful callback. An existing user with
988 * a matching, identity-provider-verified email is linked; otherwise a new
989 * user is created. It sends a request to the [Provision Auth User API route](https://docs.medusajs.com/api/admin#auth_postauth_provideruser).
990 *
991 * The token returned by {@link callback} is actorless until the user is
992 * provisioned. Pass that token in the `Authorization` header, then call
993 * {@link refresh} to obtain a token bound to the newly linked user.
994 *
995 * @param provider - The authentication provider instance ID. For example, `okta`.
996 * @param headers - Headers to pass in the request, typically the `Authorization`
997 * bearer token returned by the callback.
998 * @returns The created or linked user.
999 *
1000 * @tags auth
1001 *
1002 * @example
1003 * const token = await sdk.auth.callback("user", "okta", queryParams)
1004 * await sdk.auth.createUser("okta", { Authorization: `Bearer ${token}` })
1005 * await sdk.auth.refresh()
1006 */
1007 createUser = async (provider: string, headers?: ClientHeaders) => {
1008 return await this.client.fetch<HttpTypes.AdminUserResponse>(
1009 `/auth/${provider}/user`,
1010 {
1011 method: "POST",
1012 headers,
1013 }
1014 )
1015 }
1016
1017 /**
1018 * @ignore
1019 */
1020 private setToken_ = async (token: string) => {
1021 // By default we just set the token in the configured storage, if configured to use sessions we convert it into session storage instead.
1022 if (this.config?.auth?.type === "session") {
1023 await this.client.fetch("/auth/session", {
1024 method: "POST",
1025 headers: { Authorization: `Bearer ${token}` },
1026 })
1027 } else {
1028 this.client.setToken(token)
1029 }
1030 }
1031 }