feat(MED-100): create medusa store account for user
This commit is contained in:
@@ -18,6 +18,23 @@ export const getAuthHeaders = async (): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
export const getMedusaCustomerId = async (): Promise<
|
||||
{ customerId: string | null }
|
||||
> => {
|
||||
try {
|
||||
const cookies = await nextCookies()
|
||||
const customerId = cookies.get("_medusa_customer_id")?.value
|
||||
|
||||
if (!customerId) {
|
||||
return { customerId: null }
|
||||
}
|
||||
|
||||
return { customerId }
|
||||
} catch {
|
||||
return { customerId: null}
|
||||
}
|
||||
}
|
||||
|
||||
export const getCacheTag = async (tag: string): Promise<string> => {
|
||||
try {
|
||||
const cookies = await nextCookies()
|
||||
@@ -59,6 +76,16 @@ export const setAuthToken = async (token: string) => {
|
||||
})
|
||||
}
|
||||
|
||||
export const setMedusaCustomerId = async (customerId: string) => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_customer_id", customerId, {
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
})
|
||||
}
|
||||
|
||||
export const removeAuthToken = async () => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_jwt", "", {
|
||||
|
||||
@@ -259,3 +259,51 @@ export const updateCustomerAddress = async (
|
||||
return { success: false, error: err.toString() }
|
||||
})
|
||||
}
|
||||
|
||||
export async function medusaLoginOrRegister(credentials: {
|
||||
email: string
|
||||
password?: string
|
||||
}) {
|
||||
const { email, password } = credentials;
|
||||
|
||||
try {
|
||||
const token = await sdk.auth.login("customer", "emailpass", {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
await setAuthToken(token as string);
|
||||
await transferCart();
|
||||
|
||||
const customerCacheTag = await getCacheTag("customers");
|
||||
revalidateTag(customerCacheTag);
|
||||
} catch (error) {
|
||||
console.error("Failed to login customer, attempting to register", error);
|
||||
try {
|
||||
const registerToken = await sdk.auth.register("customer", "emailpass", {
|
||||
email: email,
|
||||
password: password,
|
||||
})
|
||||
|
||||
await setAuthToken(registerToken as string);
|
||||
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
};
|
||||
|
||||
await sdk.store.customer.create({ email }, {}, headers);
|
||||
|
||||
const loginToken = await sdk.auth.login("customer", "emailpass", {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
await setAuthToken(loginToken as string);
|
||||
|
||||
const customerCacheTag = await getCacheTag("customers");
|
||||
revalidateTag(customerCacheTag);
|
||||
await transferCart();
|
||||
} catch (registerError) {
|
||||
throw medusaError(registerError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user