Raw
1 import { Spinner } from "@medusajs/icons"
2 import type { AuthTypes } from "@medusajs/types"
3 import { Button, Text, toast } from "@medusajs/ui"
4 import type { TFunction } from "i18next"
5 import { useCallback, useEffect, useMemo, useRef, useState } from "react"
6 import { useTranslation } from "react-i18next"
7 import { decodeToken } from "react-jwt"
8 import { useNavigate, useSearchParams } from "react-router-dom"
9
10 import { AuthProvider, provisionAuthUser } from "../../../hooks/api"
11 import { isFetchError } from "../../../lib/is-fetch-error"
12 import { sdk } from "../../../lib/client"
13 import { getRedirectProviders, hasEmailPassProvider } from "../utils"
14 import { CLOUD_AUTH_PROVIDER } from "./cloud-auth-login"
15
16 type SsoLoginProps = {
17 providers: AuthProvider[]
18 onMfaChallenge?: (
19 challenge: AuthTypes.AuthMfaChallengeDTO,
20 onSuccess: (token: string) => void | Promise<void>
21 ) => void
22 }
23
24 export const SsoLogin = ({ providers, onMfaChallenge }: SsoLoginProps) => {
25 const { t } = useTranslation()
26 const [searchParams] = useSearchParams()
27
28 const redirectProviders = useMemo(
29 () =>
30 getRedirectProviders(providers).filter(
31 (provider) => provider.id !== CLOUD_AUTH_PROVIDER
32 ),
33 [providers]
34 )
35
36 const callbackProviderId = searchParams.get("auth_provider")
37 const isCallback =
38 !!callbackProviderId &&
39 callbackProviderId !== CLOUD_AUTH_PROVIDER &&
40 (searchParams.has("code") || searchParams.has("error"))
41
42 const showDivider = hasEmailPassProvider(providers)
43
44 const { handleLogin, pendingProviderId } = useHandleLogin()
45 const { handleCallback, isCallbackPending } = useAuthCallback(
46 callbackProviderId,
47 searchParams,
48 onMfaChallenge
49 )
50
51 // ref to prevent duplicate calls in React strict mode and other
52 // unmounting+mounting scenarios
53 const actionInitiated = useRef(false)
54 useEffect(() => {
55 if (actionInitiated.current) {
56 return
57 }
58
59 if (isCallback) {
60 actionInitiated.current = true
61 handleCallback()
62 }
63 }, [isCallback, handleCallback])
64
65 // Render full-screen overlay during the callback to hide the login form
66 if (isCallback) {
67 return (
68 <div className="bg-ui-bg-subtle fixed inset-0 z-50 flex items-center justify-center">
69 <Spinner className="text-ui-fg-subtle animate-spin" />
70 </div>
71 )
72 }
73
74 if (!redirectProviders.length) {
75 return null
76 }
77
78 const isPending = !!pendingProviderId || isCallbackPending
79
80 return (
81 <div className="flex w-full flex-col gap-y-3">
82 {showDivider && <OrDivider />}
83 {redirectProviders.map((provider) => {
84 return (
85 <Button
86 key={provider.id}
87 variant="secondary"
88 onClick={() => handleLogin(provider.id)}
89 className="w-full"
90 disabled={isPending}
91 isLoading={pendingProviderId === provider.id || isCallbackPending}
92 >
93 {t("auth.login.continueWithProvider", {
94 provider: provider.display_name,
95 })}
96 </Button>
97 )
98 })}
99 </div>
100 )
101 }
102
103 const OrDivider = () => {
104 const { t } = useTranslation()
105
106 return (
107 <div className="flex items-center gap-x-3">
108 <hr className="bg-ui-border-base h-px flex-1 border-0" />
109 <Text size="small" leading="compact" className="text-ui-fg-muted">
110 {t("auth.login.or")}
111 </Text>
112 <hr className="bg-ui-border-base h-px flex-1 border-0" />
113 </div>
114 )
115 }
116
117 const useHandleLogin = () => {
118 const { t } = useTranslation()
119 const [pendingProviderId, setPendingProviderId] = useState<string | null>(
120 null
121 )
122
123 // Not using useMutation from @tanstack/react-query because it doesn't play
124 // well with strict mode when invoked only once from a useEffect. The issue is
125 // that the first instance of the mutation is invoked but quickly canceled upon
126 // the second mounting of the component, and its status gets stuck at pending.
127 const handleLogin = useCallback(
128 async (providerId: string) => {
129 setPendingProviderId(providerId)
130 try {
131 const result = await sdk.auth.login("user", providerId, {
132 // setting callback_url in case the admin is on a different domain, or
133 // the backend URL is set to just "/" which won't work for the callback
134 callback_url: `${window.location.origin}${window.location.pathname}?auth_provider=${providerId}`,
135 })
136
137 if (typeof result === "object" && "location" in result) {
138 // Redirect to the identity provider for authentication
139 window.location.href = result.location
140 return
141 }
142
143 throw new Error("Unexpected login response")
144 } catch {
145 toast.error(t("auth.login.authenticationFailed"))
146 setPendingProviderId(null)
147 }
148 },
149 [t]
150 )
151
152 return { handleLogin, pendingProviderId }
153 }
154
155 const useAuthCallback = (
156 providerId: string | null,
157 searchParams: URLSearchParams,
158 onMfaChallenge?: (
159 challenge: AuthTypes.AuthMfaChallengeDTO,
160 onSuccess: (token: string) => void | Promise<void>
161 ) => void
162 ) => {
163 const { t } = useTranslation()
164 const navigate = useNavigate()
165 const [isPending, setIsPending] = useState(false)
166
167 const ensureUser = useCallback(
168 async (token: string) => {
169 const decodedToken = decodeToken(token) as {
170 actor_id?: string
171 } | null
172
173 // If the token has no actor linked yet, provision the user and refresh the
174 // token so it comes back with the actor_id set.
175 if (!decodedToken?.actor_id && providerId) {
176 await provisionAuthUser(providerId, token)
177
178 const refreshedToken = await sdk.auth.refresh({
179 Authorization: `Bearer ${token}`, // passing it manually in case the auth type is session
180 })
181 if (!refreshedToken) {
182 throw new Error("Failed to refresh token after user provisioning")
183 }
184 }
185 },
186 [providerId]
187 )
188
189 // Not using useMutation from @tanstack/react-query because it doesn't play
190 // well with strict mode when invoked only once from a useEffect (see note in
191 // useHandleLogin).
192 const handleCallback = useCallback(async () => {
193 if (!providerId) {
194 return
195 }
196
197 setIsPending(true)
198 try {
199 let token: string
200 try {
201 const query = Object.fromEntries(searchParams)
202 delete query.auth_provider
203
204 const result = await sdk.auth.callback("user", providerId, query)
205
206 if (typeof result === "object" && "mfa_challenge" in result) {
207 if (!onMfaChallenge) {
208 throw new Error("MFA challenge handler is missing")
209 }
210
211 onMfaChallenge(result.mfa_challenge, async (verifiedToken) => {
212 try {
213 await ensureUser(verifiedToken)
214 navigate("/")
215 } catch (error) {
216 toast.error(resolveProvisionError(error, t))
217 navigate("/login")
218 }
219 })
220 return
221 }
222
223 if (typeof result === "object" && "verification_required" in result) {
224 throw new Error("Verification required but not implemented yet")
225 }
226
227 token = result
228 } catch (error) {
229 throw new AuthCallbackError(t("auth.login.authenticationFailed"))
230 }
231
232 try {
233 await ensureUser(token)
234 } catch (error) {
235 throw new AuthCallbackError(resolveProvisionError(error, t))
236 }
237
238 navigate("/")
239 } catch (error) {
240 toast.error(
241 error instanceof AuthCallbackError
242 ? error.message
243 : t("auth.login.authenticationFailed")
244 )
245 // Navigate to /login without the query string, otherwise a failed
246 // callback would get stuck on the spinner. There's no point in keeping the
247 // query string anyway because the callback would just fail again.
248 navigate("/login")
249 }
250
251 setIsPending(false)
252 }, [providerId, searchParams, t, onMfaChallenge, ensureUser, navigate])
253
254 return { handleCallback, isCallbackPending: isPending }
255 }
256
257 class AuthCallbackError extends Error {}
258
259 // The provisioning route returns user-friendly messages, so we surface the
260 // backend message when available and fall back to a generic string otherwise.
261 const resolveProvisionError = (error: unknown, t: TFunction): string => {
262 if (isFetchError(error) && error.message) {
263 return error.message
264 }
265
266 return t("auth.login.provisioningFailed")
267 }