1 import { Spinner } from "@medusajs/icons"
2 import type { AuthTypes } from "@medusajs/types"
3 import { Button, toast } from "@medusajs/ui"
4 import { useCallback, useEffect, useRef, useState } from "react"
5 import { useTranslation } from "react-i18next"
6 import { decodeToken } from "react-jwt"
7 import { useNavigate, useSearchParams } from "react-router-dom"
8 import { callbackWithCloudAuth } from "../../../hooks/api"
9 import {
10 useCloudAuthEnabled,
11 useCreateCloudAuthUser,
12 } from "../../../hooks/api/cloud"
13 import { sdk } from "../../../lib/client"
14
15 export const CLOUD_AUTH_PROVIDER = "cloud"
16
17 type CloudAuthLoginProps = {
18 onMfaChallenge?: (
19 challenge: AuthTypes.AuthMfaChallengeDTO,
20 onSuccess: (token: string) => void | Promise<void>
21 ) => void
22 }
23
24 export const CloudAuthLogin = ({ onMfaChallenge }: CloudAuthLoginProps) => {
25 const { t } = useTranslation()
26 const [searchParams] = useSearchParams()
27 const { data: cloudAuth } = useCloudAuthEnabled()
28
29 const isAutoLogin =
30 searchParams.get("auth_provider") === CLOUD_AUTH_PROVIDER &&
31 searchParams.get("auto") === "true"
32
33 const isCallback =
34 searchParams.get("auth_provider") === CLOUD_AUTH_PROVIDER &&
35 (searchParams.has("code") || searchParams.has("error"))
36
37 const { handleLogin, isLoginPending } = useHandleLogin(isAutoLogin)
38 const { handleCallback, isCallbackPending } = useAuthCallback(
39 searchParams,
40 onMfaChallenge
41 )
42
43 const actionInitiated = useRef(false) // ref to prevent duplicate calls in React strict mode and other unmounting+mounting scenarios
44 useEffect(() => {
45 if (actionInitiated.current) {
46 return
47 }
48
49 if (isAutoLogin) {
50 actionInitiated.current = true
51 handleLogin()
52 } else if (isCallback) {
53 actionInitiated.current = true
54 handleCallback()
55 }
56 }, [isAutoLogin, isCallback, handleLogin, handleCallback])
57
58 // Render full-screen overlay during auto-login or callback to hide the login form
59 if (isAutoLogin || isCallback) {
60 return (
61 <div className="bg-ui-bg-subtle fixed inset-0 z-50 flex items-center justify-center">
62 <Spinner className="text-ui-fg-subtle animate-spin" />
63 </div>
64 )
65 }
66
67 // This check is last on purpose.
68 // If it was first, the /app/login form would show briefly before being replaced by the above spinner.
69 if (!cloudAuth?.enabled) {
70 return null
71 }
72
73 // If it's not auto-login or callback, and the cloud auth is enabled, just show the login button.
74 return (
75 <>
76 <hr className="bg-ui-border-base my-4" />
77 <Button
78 variant="secondary"
79 onClick={handleLogin}
80 className="w-full"
81 disabled={isLoginPending || isCallbackPending}
82 isLoading={isLoginPending || isCallbackPending}
83 >
84 {t("auth.login.cloud")}
85 </Button>
86 </>
87 )
88 }
89
90 const useHandleLogin = (isAutoLogin: boolean) => {
91 const { t } = useTranslation()
92 const navigate = useNavigate()
93 const [isPending, setIsPending] = useState(false)
94
95 // Not using useMutation from @tanstack/react-query because it doesn't play well with strict mode when invoked only once from a useEffect.
96 // The issue is that the first instance of the mutation is invoked but quickly canceled upon the second mounting of the component, and its status gets stuck at pending.
97 const handleLogin = useCallback(async () => {
98 setIsPending(true)
99 try {
100 const result = await sdk.auth.login("user", CLOUD_AUTH_PROVIDER, {
101 // setting callback_url in case the admin is on a different domain, or the backend URL is set to just "/" which won't work for the callback
102 callback_url: `${window.location.origin}${window.location.pathname}?auth_provider=${CLOUD_AUTH_PROVIDER}`,
103 })
104
105 if (typeof result === "object" && "location" in result) {
106 // Redirect to Medusa Cloud for authentication
107 window.location.href = result.location
108 return
109 }
110
111 throw new Error("Unexpected login response")
112 } catch {
113 toast.error(t("auth.login.authenticationFailed"))
114 if (isAutoLogin) {
115 // Navigate to /login without query string cause otherwise a failed auto-login would get stuck on the spinner.
116 // There's no point in using the query string anyway because the auto-login would just fail again.
117 navigate("/login")
118 }
119 }
120
121 setIsPending(false)
122 }, [t, navigate, isAutoLogin])
123
124 return { handleLogin, isLoginPending: isPending }
125 }
126
127 const useAuthCallback = (
128 searchParams: URLSearchParams,
129 onMfaChallenge?: (
130 challenge: AuthTypes.AuthMfaChallengeDTO,
131 onSuccess: (token: string) => void | Promise<void>
132 ) => void
133 ) => {
134 const { t } = useTranslation()
135 const navigate = useNavigate()
136 const { mutateAsync: createCloudAuthUser } = useCreateCloudAuthUser()
137 const [isPending, setIsPending] = useState(false)
138
139 const ensureCloudAuthUser = useCallback(
140 async (token: string) => {
141 const decodedToken = decodeToken(token) as {
142 actor_id: string
143 user_metadata: Record<string, unknown>
144 }
145
146 // If user doesn't exist, create it
147 if (!decodedToken?.actor_id) {
148 await createCloudAuthUser()
149
150 // Refresh token to get the updated token with actor_id
151 const refreshedToken = await sdk.auth.refresh({
152 Authorization: `Bearer ${token}`, // passing it manually in case the auth type is session
153 })
154 if (!refreshedToken) {
155 throw new Error("Failed to refresh token after user creation")
156 }
157 }
158 },
159 [createCloudAuthUser]
160 )
161
162 // Not using useMutation from @tanstack/react-query because it doesn't play well with strict mode when invoked only once from a useEffect.
163 // The issue is that the first instance of the mutation is invoked but quickly canceled upon the second mounting of the component, and its status gets stuck at pending.
164 const handleCallback = useCallback(async () => {
165 setIsPending(true)
166 try {
167 let token: string
168 try {
169 const query = Object.fromEntries(searchParams)
170 delete query.auth_provider // BE doesn't need this
171
172 const result = await callbackWithCloudAuth(query)
173
174 if (typeof result === "object" && "mfa_challenge" in result) {
175 if (!onMfaChallenge) {
176 throw new Error("MFA challenge handler is missing")
177 }
178
179 onMfaChallenge?.(result.mfa_challenge, async (verifiedToken) => {
180 await ensureCloudAuthUser(verifiedToken)
181 navigate("/")
182 })
183 return
184 }
185
186 if (typeof result === "object" && "verification_required" in result) {
187 throw new Error("Verification required but not implemented yet")
188 }
189
190 token = result
191 } catch (error) {
192 throw new Error("Authentication callback failed")
193 }
194
195 await ensureCloudAuthUser(token)
196
197 navigate("/")
198 } catch (error) {
199 toast.error(t("auth.login.authenticationFailed"))
200 // Navigate to /login without query string cause otherwise a failed callback would get stuck on the spinner.
201 // There's no point in using the query string anyway because the callback would just fail again.
202 navigate("/login")
203 }
204
205 setIsPending(false)
206 }, [searchParams, t, onMfaChallenge, ensureCloudAuthUser, navigate])
207
208 return { handleCallback, isCallbackPending: isPending }
209 }