@pradip1995/segment-login-template 0.5.24 → 0.5.26

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 (38) hide show
  1. package/package.json +54 -54
  2. package/src/account-addresses.tsx +287 -287
  3. package/src/account-guest-orders.tsx +98 -98
  4. package/src/account-orders.tsx +260 -260
  5. package/src/account-overview.tsx +133 -133
  6. package/src/account-payment-methods.tsx +328 -328
  7. package/src/account-profile-logic.ts +282 -282
  8. package/src/account-profile.tsx +111 -111
  9. package/src/account-theme.ts +91 -91
  10. package/src/account-utils.ts +20 -20
  11. package/src/auth-server.ts +442 -442
  12. package/src/commerce-auth-otp-modal.css +125 -125
  13. package/src/commerce-auth-otp-modal.tsx +121 -121
  14. package/src/forgot-password-form.tsx +109 -109
  15. package/src/google-auth-section.tsx +22 -22
  16. package/src/google-sign-in-section.tsx +67 -142
  17. package/src/guest-order-modal.tsx +215 -215
  18. package/src/index.ts +7 -7
  19. package/src/is-next-redirect.ts +60 -60
  20. package/src/login-brand-panel.tsx +158 -158
  21. package/src/login-form.tsx +469 -469
  22. package/src/manifest.ts +11 -11
  23. package/src/order-history-status.test.ts +224 -224
  24. package/src/order-history-status.ts +244 -244
  25. package/src/otp-component.ts +14 -14
  26. package/src/otp-input.tsx +46 -46
  27. package/src/otp-unified-form.tsx +333 -333
  28. package/src/otp-verification-modal.tsx +112 -112
  29. package/src/payment-methods-actions.ts +243 -243
  30. package/src/profile-email-field.tsx +116 -116
  31. package/src/profile-email.test.ts +182 -182
  32. package/src/profile-email.ts +54 -54
  33. package/src/profile-phone-field.tsx +119 -119
  34. package/src/register-form.tsx +339 -339
  35. package/src/reorder-checkout-address.ts +101 -101
  36. package/src/reset-password-form.tsx +103 -103
  37. package/src/reset-password-page.tsx +12 -12
  38. package/src/segment.tsx +272 -272
@@ -1,442 +1,442 @@
1
- "use server"
2
-
3
- import {
4
- checkEmailRegistered,
5
- completePasswordReset,
6
- registerCustomer as registerCustomerBase,
7
- requestPasswordReset,
8
- sendCustomerOTP,
9
- verifyCustomerOTP,
10
- } from "@pradip1995/commerce-core/data/customer-registration"
11
- import {
12
- authenticateGoogleCredential as authenticateGoogleCredentialCore,
13
- handleGoogleCallback as handleGoogleCallbackCore,
14
- transferCart,
15
- } from "@pradip1995/commerce-core/data/customer"
16
- import { getAuthHeaders, getCacheTag, setAuthToken } from "@pradip1995/commerce-core/data/cookies"
17
- import { sendOTP, verifyOTP } from "@pradip1995/commerce-core/data/guest"
18
- import { getGoogleOAuthCallbackUrl } from "@pradip1995/commerce-core/util/google-oauth"
19
- import { revalidateTag } from "next/cache"
20
- import { redirect } from "next/navigation"
21
-
22
- export {
23
- sendCustomerOTP,
24
- verifyCustomerOTP,
25
- requestPasswordReset,
26
- checkEmailRegistered,
27
- completePasswordReset,
28
- sendOTP,
29
- verifyOTP,
30
- }
31
-
32
- function normalizeRegistrationError(message: string): string {
33
- const lower = message.toLowerCase()
34
- if (
35
- lower.includes("identity with email already exists") ||
36
- lower.includes("email already exists") ||
37
- lower.includes("email is already registered")
38
- ) {
39
- return "Email already exists"
40
- }
41
- if (
42
- lower.includes("identity with phone already exists") ||
43
- lower.includes("phone already exists")
44
- ) {
45
- return "Phone number already exists"
46
- }
47
- return message
48
- }
49
-
50
- export async function registerCustomer(data: {
51
- email: string
52
- first_name: string
53
- last_name: string
54
- phone?: string
55
- password: string
56
- }) {
57
- const result = await registerCustomerBase(data)
58
- if (!result.success && result.error) {
59
- return { ...result, error: normalizeRegistrationError(result.error) }
60
- }
61
- return result
62
- }
63
-
64
- function getHeaders() {
65
- return {
66
- "Content-Type": "application/json",
67
- "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "",
68
- }
69
- }
70
-
71
- async function getAuthenticatedHeaders() {
72
- return {
73
- ...getHeaders(),
74
- ...(await getAuthHeaders()),
75
- }
76
- }
77
-
78
- function getBaseUrl() {
79
- return process.env.MEDUSA_BACKEND_URL || "http://localhost:9000"
80
- }
81
-
82
- export async function sendAuthOtp(input: {
83
- email?: string
84
- phone?: string
85
- type: "email_auth" | "phone_auth"
86
- }) {
87
- const baseUrl = getBaseUrl()
88
- const body =
89
- input.type === "email_auth"
90
- ? { email: input.email?.toLowerCase().trim(), type: input.type }
91
- : { phone: input.phone?.replace(/[^\d+]/g, ""), type: input.type }
92
-
93
- const response = await fetch(`${baseUrl}/store/customers/otp/send`, {
94
- method: "POST",
95
- headers: getHeaders(),
96
- body: JSON.stringify(body),
97
- })
98
-
99
- if (!response.ok) {
100
- const err = await response.json().catch(() => ({}))
101
- return {
102
- success: false as const,
103
- error: (err as { message?: string }).message || "Failed to send verification code",
104
- }
105
- }
106
-
107
- const data = (await response.json()) as {
108
- token?: string
109
- expires_at?: string
110
- is_new_user?: boolean
111
- }
112
-
113
- return {
114
- success: true as const,
115
- token: data.token,
116
- isNewUser: data.is_new_user ?? false,
117
- }
118
- }
119
-
120
- export async function verifyAuthOtpAndLogin(input: {
121
- token: string
122
- code: string
123
- countryCode: string
124
- first_name?: string
125
- last_name?: string
126
- /** When true, return success instead of redirecting (used by login popup). */
127
- skipRedirect?: boolean
128
- }) {
129
- const baseUrl = getBaseUrl()
130
-
131
- const response = await fetch(`${baseUrl}/store/customers/otp/verify`, {
132
- method: "POST",
133
- headers: getHeaders(),
134
- body: JSON.stringify({
135
- token: input.token,
136
- code: input.code,
137
- first_name: input.first_name,
138
- last_name: input.last_name,
139
- }),
140
- })
141
-
142
- if (!response.ok) {
143
- const err = await response.json().catch(() => ({}))
144
- const raw =
145
- (err as { message?: string }).message || "Invalid verification code"
146
- const lower = raw.toLowerCase()
147
- const error =
148
- lower.includes("unable to retrieve the auth provider") &&
149
- (lower.includes("emailotp") || lower.includes("phoneotp"))
150
- ? "OTP sign-in is not configured on the backend. Ask the shop admin to enable emailotp/phoneotp auth providers and redeploy."
151
- : raw.replace(/\s+/g, " ").trim()
152
- return {
153
- success: false as const,
154
- error,
155
- }
156
- }
157
-
158
- const data = (await response.json()) as {
159
- token?: string | null
160
- verified?: boolean
161
- is_new_user?: boolean
162
- customer?: { email?: string }
163
- }
164
-
165
- const jwt = data.token
166
- if (!jwt) {
167
- return {
168
- success: false as const,
169
- error: "Verification succeeded but login token was not returned. Try signing in with your password.",
170
- }
171
- }
172
-
173
- await setAuthToken(jwt)
174
-
175
- // Don't block login on cart merge — middleware recovers guest cart after redirect.
176
- void transferCart(jwt).catch(() => {})
177
-
178
- const customerCacheTag = await getCacheTag("customers")
179
- if (customerCacheTag) {
180
- revalidateTag(customerCacheTag)
181
- }
182
-
183
- if (input.skipRedirect) {
184
- return {
185
- success: true as const,
186
- isNewUser: data.is_new_user ?? false,
187
- }
188
- }
189
-
190
- const countryCode = input.countryCode || "in"
191
- redirect(`/${countryCode}`)
192
- }
193
-
194
- export async function completePasswordResetAction(input: {
195
- email: string
196
- password: string
197
- token: string
198
- countryCode: string
199
- }) {
200
- const result = await completePasswordReset({
201
- email: input.email,
202
- password: input.password,
203
- token: input.token,
204
- })
205
-
206
- if (!result.success) {
207
- return result
208
- }
209
-
210
- redirect(`/${input.countryCode || "in"}/account`)
211
- }
212
-
213
- export async function verifyRegistrationOtp(input: {
214
- otpToken: string
215
- code: string
216
- countryCode: string
217
- /** When true, do not redirect after login (account profile verify flow). */
218
- skipRedirect?: boolean
219
- }) {
220
- const response = await fetch(`${getBaseUrl()}/store/customers/otp/verify`, {
221
- method: "POST",
222
- headers: getHeaders(),
223
- body: JSON.stringify({
224
- token: input.otpToken,
225
- code: input.code,
226
- }),
227
- cache: "no-store",
228
- })
229
-
230
- const data = (await response.json().catch(() => ({}))) as {
231
- message?: string
232
- token?: string | null
233
- email_verified?: boolean
234
- phone_verified?: boolean
235
- needs_login?: boolean
236
- }
237
-
238
- if (!response.ok) {
239
- return {
240
- success: false as const,
241
- error: data.message || "Invalid verification code",
242
- }
243
- }
244
-
245
- const loginToken = data.token
246
- if (loginToken) {
247
- await setAuthToken(loginToken)
248
- try {
249
- await transferCart(loginToken)
250
- } catch {
251
- // non-fatal
252
- }
253
- const customerCacheTag = await getCacheTag("customers")
254
- revalidateTag(customerCacheTag)
255
- if (!input.skipRedirect) {
256
- redirect(`/${input.countryCode || "in"}`)
257
- }
258
- }
259
-
260
- return {
261
- success: true as const,
262
- emailVerified: data.email_verified,
263
- phoneVerified: data.phone_verified,
264
- needsLogin: data.needs_login ?? true,
265
- }
266
- }
267
-
268
- export async function sendRegistrationOtp(
269
- customerId: string,
270
- type: "email_verification" | "phone_verification"
271
- ) {
272
- const response = await fetch(`${getBaseUrl()}/store/customers/otp/send`, {
273
- method: "POST",
274
- headers: getHeaders(),
275
- body: JSON.stringify({
276
- customer_id: customerId,
277
- type,
278
- }),
279
- cache: "no-store",
280
- })
281
-
282
- if (!response.ok) {
283
- const err = (await response.json().catch(() => ({}))) as {
284
- message?: string
285
- }
286
- const message = err.message || "Failed to send verification code"
287
- if (message.includes("Channel configuration not found")) {
288
- return {
289
- success: false as const,
290
- error:
291
- "Verification is not configured on the backend. Rebuild and restart the Medusa server with customer-registration OTP settings.",
292
- }
293
- }
294
- return { success: false as const, error: message }
295
- }
296
-
297
- const data = (await response.json()) as {
298
- token?: string
299
- expires_at?: string
300
- message?: string
301
- }
302
-
303
- return {
304
- success: true as const,
305
- token: data.token,
306
- message: data.message || "OTP sent successfully",
307
- }
308
- }
309
-
310
- export async function requestContactChange(input: { email?: string; phone?: string }) {
311
- const body = input.email
312
- ? { email: input.email.trim().toLowerCase() }
313
- : { phone: input.phone }
314
-
315
- const response = await fetch(`${getBaseUrl()}/store/customers/me/contact`, {
316
- method: "POST",
317
- headers: await getAuthenticatedHeaders(),
318
- body: JSON.stringify(body),
319
- cache: "no-store",
320
- })
321
-
322
- if (!response.ok) {
323
- const err = (await response.json().catch(() => ({}))) as { message?: string }
324
- const message = err.message || "Failed to send verification code"
325
- if (message.includes("Channel configuration not found")) {
326
- return {
327
- success: false as const,
328
- error:
329
- "Verification is not configured on the backend. Rebuild and restart the Medusa server with customer-registration OTP settings.",
330
- }
331
- }
332
- return { success: false as const, error: message }
333
- }
334
-
335
- const data = (await response.json()) as { token?: string; expires_at?: string }
336
-
337
- return {
338
- success: true as const,
339
- token: data.token,
340
- }
341
- }
342
-
343
- export async function verifyContactChange(input: { otpToken: string; code: string }) {
344
- const response = await fetch(`${getBaseUrl()}/store/customers/me/contact/verify`, {
345
- method: "POST",
346
- headers: await getAuthenticatedHeaders(),
347
- body: JSON.stringify({
348
- token: input.otpToken,
349
- code: input.code,
350
- }),
351
- cache: "no-store",
352
- })
353
-
354
- const data = (await response.json().catch(() => ({}))) as {
355
- message?: string
356
- token?: string | null
357
- }
358
-
359
- if (!response.ok) {
360
- return {
361
- success: false as const,
362
- error: data.message || "Invalid verification code",
363
- }
364
- }
365
-
366
- if (data.token) {
367
- await setAuthToken(data.token)
368
- }
369
-
370
- const customerCacheTag = await getCacheTag("customers")
371
- if (customerCacheTag) {
372
- revalidateTag(customerCacheTag)
373
- }
374
-
375
- return { success: true as const }
376
- }
377
-
378
- /** GIS One Tap / credential button → Medusa POST /auth/customer/google/callback { credential } */
379
- export async function authenticateGoogleCredential(credential: string) {
380
- return authenticateGoogleCredentialCore(credential)
381
- }
382
-
383
- /** After OAuth JWT: link or create customer (guest upgrade via customer-registration). */
384
- export async function handleGoogleCallback(
385
- token: string,
386
- email?: string,
387
- first_name?: string,
388
- last_name?: string
389
- ) {
390
- return handleGoogleCallbackCore(token, email, first_name, last_name)
391
- }
392
-
393
- export async function initiateGoogleAuth(countryCode?: string) {
394
- try {
395
- const backendUrl = getBaseUrl()
396
-
397
- if (!backendUrl) {
398
- return { error: "Backend URL not configured" }
399
- }
400
-
401
- if (!process.env.GOOGLE_CLIENT_ID && !process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID) {
402
- return { error: "Google sign-in is not configured on the storefront" }
403
- }
404
-
405
- const callbackUrl = getGoogleOAuthCallbackUrl(countryCode)
406
-
407
- const response = await fetch(`${backendUrl}/auth/customer/google`, {
408
- method: "POST",
409
- headers: { "Content-Type": "application/json" },
410
- body: JSON.stringify({ callback_url: callbackUrl }),
411
- cache: "no-store",
412
- })
413
-
414
- if (!response.ok) {
415
- const err = (await response.json().catch(() => ({}))) as {
416
- message?: string
417
- type?: string
418
- }
419
- const message = err.message?.trim()
420
- if (message?.includes("Unable to retrieve the auth provider")) {
421
- return {
422
- error:
423
- "Google sign-in is not enabled on the backend. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in backend/.env and restart the Medusa server.",
424
- }
425
- }
426
- return { error: message || "Google sign-in failed. Check backend Google OAuth configuration." }
427
- }
428
-
429
- const result = await response.json()
430
- const redirectUrl =
431
- typeof result === "string" ? result : (result as { location?: string })?.location
432
-
433
- if (!redirectUrl) {
434
- return { error: "No redirect URL received from Google OAuth" }
435
- }
436
-
437
- return { redirectUrl }
438
- } catch (error: unknown) {
439
- const message = error instanceof Error ? error.message : "Internal server error"
440
- return { error: message }
441
- }
442
- }
1
+ "use server"
2
+
3
+ import {
4
+ checkEmailRegistered,
5
+ completePasswordReset,
6
+ registerCustomer as registerCustomerBase,
7
+ requestPasswordReset,
8
+ sendCustomerOTP,
9
+ verifyCustomerOTP,
10
+ } from "@pradip1995/commerce-core/data/customer-registration"
11
+ import {
12
+ authenticateGoogleCredential as authenticateGoogleCredentialCore,
13
+ handleGoogleCallback as handleGoogleCallbackCore,
14
+ transferCart,
15
+ } from "@pradip1995/commerce-core/data/customer"
16
+ import { getAuthHeaders, getCacheTag, setAuthToken } from "@pradip1995/commerce-core/data/cookies"
17
+ import { sendOTP, verifyOTP } from "@pradip1995/commerce-core/data/guest"
18
+ import { getGoogleOAuthCallbackUrl } from "@pradip1995/commerce-core/util/google-oauth"
19
+ import { revalidateTag } from "next/cache"
20
+ import { redirect } from "next/navigation"
21
+
22
+ export {
23
+ sendCustomerOTP,
24
+ verifyCustomerOTP,
25
+ requestPasswordReset,
26
+ checkEmailRegistered,
27
+ completePasswordReset,
28
+ sendOTP,
29
+ verifyOTP,
30
+ }
31
+
32
+ function normalizeRegistrationError(message: string): string {
33
+ const lower = message.toLowerCase()
34
+ if (
35
+ lower.includes("identity with email already exists") ||
36
+ lower.includes("email already exists") ||
37
+ lower.includes("email is already registered")
38
+ ) {
39
+ return "Email already exists"
40
+ }
41
+ if (
42
+ lower.includes("identity with phone already exists") ||
43
+ lower.includes("phone already exists")
44
+ ) {
45
+ return "Phone number already exists"
46
+ }
47
+ return message
48
+ }
49
+
50
+ export async function registerCustomer(data: {
51
+ email: string
52
+ first_name: string
53
+ last_name: string
54
+ phone?: string
55
+ password: string
56
+ }) {
57
+ const result = await registerCustomerBase(data)
58
+ if (!result.success && result.error) {
59
+ return { ...result, error: normalizeRegistrationError(result.error) }
60
+ }
61
+ return result
62
+ }
63
+
64
+ function getHeaders() {
65
+ return {
66
+ "Content-Type": "application/json",
67
+ "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "",
68
+ }
69
+ }
70
+
71
+ async function getAuthenticatedHeaders() {
72
+ return {
73
+ ...getHeaders(),
74
+ ...(await getAuthHeaders()),
75
+ }
76
+ }
77
+
78
+ function getBaseUrl() {
79
+ return process.env.MEDUSA_BACKEND_URL || "http://localhost:9000"
80
+ }
81
+
82
+ export async function sendAuthOtp(input: {
83
+ email?: string
84
+ phone?: string
85
+ type: "email_auth" | "phone_auth"
86
+ }) {
87
+ const baseUrl = getBaseUrl()
88
+ const body =
89
+ input.type === "email_auth"
90
+ ? { email: input.email?.toLowerCase().trim(), type: input.type }
91
+ : { phone: input.phone?.replace(/[^\d+]/g, ""), type: input.type }
92
+
93
+ const response = await fetch(`${baseUrl}/store/customers/otp/send`, {
94
+ method: "POST",
95
+ headers: getHeaders(),
96
+ body: JSON.stringify(body),
97
+ })
98
+
99
+ if (!response.ok) {
100
+ const err = await response.json().catch(() => ({}))
101
+ return {
102
+ success: false as const,
103
+ error: (err as { message?: string }).message || "Failed to send verification code",
104
+ }
105
+ }
106
+
107
+ const data = (await response.json()) as {
108
+ token?: string
109
+ expires_at?: string
110
+ is_new_user?: boolean
111
+ }
112
+
113
+ return {
114
+ success: true as const,
115
+ token: data.token,
116
+ isNewUser: data.is_new_user ?? false,
117
+ }
118
+ }
119
+
120
+ export async function verifyAuthOtpAndLogin(input: {
121
+ token: string
122
+ code: string
123
+ countryCode: string
124
+ first_name?: string
125
+ last_name?: string
126
+ /** When true, return success instead of redirecting (used by login popup). */
127
+ skipRedirect?: boolean
128
+ }) {
129
+ const baseUrl = getBaseUrl()
130
+
131
+ const response = await fetch(`${baseUrl}/store/customers/otp/verify`, {
132
+ method: "POST",
133
+ headers: getHeaders(),
134
+ body: JSON.stringify({
135
+ token: input.token,
136
+ code: input.code,
137
+ first_name: input.first_name,
138
+ last_name: input.last_name,
139
+ }),
140
+ })
141
+
142
+ if (!response.ok) {
143
+ const err = await response.json().catch(() => ({}))
144
+ const raw =
145
+ (err as { message?: string }).message || "Invalid verification code"
146
+ const lower = raw.toLowerCase()
147
+ const error =
148
+ lower.includes("unable to retrieve the auth provider") &&
149
+ (lower.includes("emailotp") || lower.includes("phoneotp"))
150
+ ? "OTP sign-in is not configured on the backend. Ask the shop admin to enable emailotp/phoneotp auth providers and redeploy."
151
+ : raw.replace(/\s+/g, " ").trim()
152
+ return {
153
+ success: false as const,
154
+ error,
155
+ }
156
+ }
157
+
158
+ const data = (await response.json()) as {
159
+ token?: string | null
160
+ verified?: boolean
161
+ is_new_user?: boolean
162
+ customer?: { email?: string }
163
+ }
164
+
165
+ const jwt = data.token
166
+ if (!jwt) {
167
+ return {
168
+ success: false as const,
169
+ error: "Verification succeeded but login token was not returned. Try signing in with your password.",
170
+ }
171
+ }
172
+
173
+ await setAuthToken(jwt)
174
+
175
+ // Don't block login on cart merge — middleware recovers guest cart after redirect.
176
+ void transferCart(jwt).catch(() => {})
177
+
178
+ const customerCacheTag = await getCacheTag("customers")
179
+ if (customerCacheTag) {
180
+ revalidateTag(customerCacheTag)
181
+ }
182
+
183
+ if (input.skipRedirect) {
184
+ return {
185
+ success: true as const,
186
+ isNewUser: data.is_new_user ?? false,
187
+ }
188
+ }
189
+
190
+ const countryCode = input.countryCode || "in"
191
+ redirect(`/${countryCode}`)
192
+ }
193
+
194
+ export async function completePasswordResetAction(input: {
195
+ email: string
196
+ password: string
197
+ token: string
198
+ countryCode: string
199
+ }) {
200
+ const result = await completePasswordReset({
201
+ email: input.email,
202
+ password: input.password,
203
+ token: input.token,
204
+ })
205
+
206
+ if (!result.success) {
207
+ return result
208
+ }
209
+
210
+ redirect(`/${input.countryCode || "in"}/account`)
211
+ }
212
+
213
+ export async function verifyRegistrationOtp(input: {
214
+ otpToken: string
215
+ code: string
216
+ countryCode: string
217
+ /** When true, do not redirect after login (account profile verify flow). */
218
+ skipRedirect?: boolean
219
+ }) {
220
+ const response = await fetch(`${getBaseUrl()}/store/customers/otp/verify`, {
221
+ method: "POST",
222
+ headers: getHeaders(),
223
+ body: JSON.stringify({
224
+ token: input.otpToken,
225
+ code: input.code,
226
+ }),
227
+ cache: "no-store",
228
+ })
229
+
230
+ const data = (await response.json().catch(() => ({}))) as {
231
+ message?: string
232
+ token?: string | null
233
+ email_verified?: boolean
234
+ phone_verified?: boolean
235
+ needs_login?: boolean
236
+ }
237
+
238
+ if (!response.ok) {
239
+ return {
240
+ success: false as const,
241
+ error: data.message || "Invalid verification code",
242
+ }
243
+ }
244
+
245
+ const loginToken = data.token
246
+ if (loginToken) {
247
+ await setAuthToken(loginToken)
248
+ try {
249
+ await transferCart(loginToken)
250
+ } catch {
251
+ // non-fatal
252
+ }
253
+ const customerCacheTag = await getCacheTag("customers")
254
+ revalidateTag(customerCacheTag)
255
+ if (!input.skipRedirect) {
256
+ redirect(`/${input.countryCode || "in"}`)
257
+ }
258
+ }
259
+
260
+ return {
261
+ success: true as const,
262
+ emailVerified: data.email_verified,
263
+ phoneVerified: data.phone_verified,
264
+ needsLogin: data.needs_login ?? true,
265
+ }
266
+ }
267
+
268
+ export async function sendRegistrationOtp(
269
+ customerId: string,
270
+ type: "email_verification" | "phone_verification"
271
+ ) {
272
+ const response = await fetch(`${getBaseUrl()}/store/customers/otp/send`, {
273
+ method: "POST",
274
+ headers: getHeaders(),
275
+ body: JSON.stringify({
276
+ customer_id: customerId,
277
+ type,
278
+ }),
279
+ cache: "no-store",
280
+ })
281
+
282
+ if (!response.ok) {
283
+ const err = (await response.json().catch(() => ({}))) as {
284
+ message?: string
285
+ }
286
+ const message = err.message || "Failed to send verification code"
287
+ if (message.includes("Channel configuration not found")) {
288
+ return {
289
+ success: false as const,
290
+ error:
291
+ "Verification is not configured on the backend. Rebuild and restart the Medusa server with customer-registration OTP settings.",
292
+ }
293
+ }
294
+ return { success: false as const, error: message }
295
+ }
296
+
297
+ const data = (await response.json()) as {
298
+ token?: string
299
+ expires_at?: string
300
+ message?: string
301
+ }
302
+
303
+ return {
304
+ success: true as const,
305
+ token: data.token,
306
+ message: data.message || "OTP sent successfully",
307
+ }
308
+ }
309
+
310
+ export async function requestContactChange(input: { email?: string; phone?: string }) {
311
+ const body = input.email
312
+ ? { email: input.email.trim().toLowerCase() }
313
+ : { phone: input.phone }
314
+
315
+ const response = await fetch(`${getBaseUrl()}/store/customers/me/contact`, {
316
+ method: "POST",
317
+ headers: await getAuthenticatedHeaders(),
318
+ body: JSON.stringify(body),
319
+ cache: "no-store",
320
+ })
321
+
322
+ if (!response.ok) {
323
+ const err = (await response.json().catch(() => ({}))) as { message?: string }
324
+ const message = err.message || "Failed to send verification code"
325
+ if (message.includes("Channel configuration not found")) {
326
+ return {
327
+ success: false as const,
328
+ error:
329
+ "Verification is not configured on the backend. Rebuild and restart the Medusa server with customer-registration OTP settings.",
330
+ }
331
+ }
332
+ return { success: false as const, error: message }
333
+ }
334
+
335
+ const data = (await response.json()) as { token?: string; expires_at?: string }
336
+
337
+ return {
338
+ success: true as const,
339
+ token: data.token,
340
+ }
341
+ }
342
+
343
+ export async function verifyContactChange(input: { otpToken: string; code: string }) {
344
+ const response = await fetch(`${getBaseUrl()}/store/customers/me/contact/verify`, {
345
+ method: "POST",
346
+ headers: await getAuthenticatedHeaders(),
347
+ body: JSON.stringify({
348
+ token: input.otpToken,
349
+ code: input.code,
350
+ }),
351
+ cache: "no-store",
352
+ })
353
+
354
+ const data = (await response.json().catch(() => ({}))) as {
355
+ message?: string
356
+ token?: string | null
357
+ }
358
+
359
+ if (!response.ok) {
360
+ return {
361
+ success: false as const,
362
+ error: data.message || "Invalid verification code",
363
+ }
364
+ }
365
+
366
+ if (data.token) {
367
+ await setAuthToken(data.token)
368
+ }
369
+
370
+ const customerCacheTag = await getCacheTag("customers")
371
+ if (customerCacheTag) {
372
+ revalidateTag(customerCacheTag)
373
+ }
374
+
375
+ return { success: true as const }
376
+ }
377
+
378
+ /** GIS One Tap / credential button → Medusa POST /auth/customer/google/callback { credential } */
379
+ export async function authenticateGoogleCredential(credential: string) {
380
+ return authenticateGoogleCredentialCore(credential)
381
+ }
382
+
383
+ /** After OAuth JWT: link or create customer (guest upgrade via customer-registration). */
384
+ export async function handleGoogleCallback(
385
+ token: string,
386
+ email?: string,
387
+ first_name?: string,
388
+ last_name?: string
389
+ ) {
390
+ return handleGoogleCallbackCore(token, email, first_name, last_name)
391
+ }
392
+
393
+ export async function initiateGoogleAuth(countryCode?: string) {
394
+ try {
395
+ const backendUrl = getBaseUrl()
396
+
397
+ if (!backendUrl) {
398
+ return { error: "Backend URL not configured" }
399
+ }
400
+
401
+ if (!process.env.GOOGLE_CLIENT_ID && !process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID) {
402
+ return { error: "Google sign-in is not configured on the storefront" }
403
+ }
404
+
405
+ const callbackUrl = getGoogleOAuthCallbackUrl(countryCode)
406
+
407
+ const response = await fetch(`${backendUrl}/auth/customer/google`, {
408
+ method: "POST",
409
+ headers: { "Content-Type": "application/json" },
410
+ body: JSON.stringify({ callback_url: callbackUrl }),
411
+ cache: "no-store",
412
+ })
413
+
414
+ if (!response.ok) {
415
+ const err = (await response.json().catch(() => ({}))) as {
416
+ message?: string
417
+ type?: string
418
+ }
419
+ const message = err.message?.trim()
420
+ if (message?.includes("Unable to retrieve the auth provider")) {
421
+ return {
422
+ error:
423
+ "Google sign-in is not enabled on the backend. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in backend/.env and restart the Medusa server.",
424
+ }
425
+ }
426
+ return { error: message || "Google sign-in failed. Check backend Google OAuth configuration." }
427
+ }
428
+
429
+ const result = await response.json()
430
+ const redirectUrl =
431
+ typeof result === "string" ? result : (result as { location?: string })?.location
432
+
433
+ if (!redirectUrl) {
434
+ return { error: "No redirect URL received from Google OAuth" }
435
+ }
436
+
437
+ return { redirectUrl }
438
+ } catch (error: unknown) {
439
+ const message = error instanceof Error ? error.message : "Internal server error"
440
+ return { error: message }
441
+ }
442
+ }