Template
Add customer accounts: login, signup, reset, activate, orders
- Storefront customer operations in graphql/customer.js and a server-safe services/shopify/customer.ts - Session held in an httpOnly, sameSite=lax cookie set by the /api/account handlers; the access token never reaches client JS - Pages: /account/login, /register, /recover, /reset/[id]/[token] and /activate/[id]/[token] for Shopify's emailed links - /account renders order history as master-detail on one screen, since the Storefront API has no standalone order-by-id query for customers - Header user icon: links to sign-in when signed out, otherwise a menu with name, email, order history, and sign out - Login errors are collapsed and password recovery responds identically for known and unknown emails, so neither form enumerates accounts Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016jWbNNJLksC1QG8z8845FX
This commit is contained in:
co-authored by
Claude Opus 5
parent
8163f99bd7
commit
8167acb231
@@ -0,0 +1,223 @@
|
||||
// Server-safe customer account access.
|
||||
//
|
||||
// The customer access token is a credential: it is only ever handled here and
|
||||
// in the /api/account route handlers, and is stored in an httpOnly cookie so
|
||||
// client JavaScript can never read it.
|
||||
import { shopifyFetch } from '@/services/shopify/client';
|
||||
import {
|
||||
CUSTOMER_QUERY,
|
||||
CUSTOMER_CREATE_MUTATION,
|
||||
CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION,
|
||||
CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION,
|
||||
CUSTOMER_RECOVER_MUTATION,
|
||||
CUSTOMER_RESET_MUTATION,
|
||||
CUSTOMER_ACTIVATE_MUTATION,
|
||||
CUSTOMER_UPDATE_MUTATION,
|
||||
} from '@/graphql/customer';
|
||||
|
||||
export const CUSTOMER_TOKEN_COOKIE = 'customerAccessToken';
|
||||
|
||||
export interface CustomerUserError {
|
||||
code?: string;
|
||||
field?: string[] | null;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface CustomerAddress {
|
||||
id: string;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
address1?: string | null;
|
||||
address2?: string | null;
|
||||
city?: string | null;
|
||||
province?: string | null;
|
||||
zip?: string | null;
|
||||
country?: string | null;
|
||||
phone?: string | null;
|
||||
}
|
||||
|
||||
export interface CustomerOrder {
|
||||
id: string;
|
||||
orderNumber: number;
|
||||
processedAt: string;
|
||||
financialStatus?: string | null;
|
||||
fulfillmentStatus?: string | null;
|
||||
statusUrl?: string | null;
|
||||
currentTotalPrice: { amount: string; currencyCode: string };
|
||||
lineItems: {
|
||||
edges: Array<{
|
||||
node: {
|
||||
title: string;
|
||||
quantity: number;
|
||||
variant?: { image?: { url: string; altText?: string | null } | null } | null;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Customer {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
phone?: string | null;
|
||||
displayName: string;
|
||||
acceptsMarketing?: boolean;
|
||||
createdAt?: string;
|
||||
defaultAddress?: CustomerAddress | null;
|
||||
orders?: { edges: Array<{ node: CustomerOrder }> };
|
||||
}
|
||||
|
||||
export interface AccessToken {
|
||||
accessToken: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
/** Either a token (success) or the errors Shopify reported. */
|
||||
export interface AuthResult {
|
||||
token: AccessToken | null;
|
||||
errors: CustomerUserError[];
|
||||
}
|
||||
|
||||
const firstMessage = (errors: CustomerUserError[]) =>
|
||||
errors[0]?.message ?? 'Something went wrong. Please try again.';
|
||||
|
||||
export { firstMessage as customerErrorMessage };
|
||||
|
||||
export async function createCustomer(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
acceptsMarketing?: boolean;
|
||||
}): Promise<{ errors: CustomerUserError[] }> {
|
||||
const response = await shopifyFetch({
|
||||
query: CUSTOMER_CREATE_MUTATION,
|
||||
variables: { input },
|
||||
});
|
||||
|
||||
return { errors: response.data.customerCreate.customerUserErrors ?? [] };
|
||||
}
|
||||
|
||||
export async function login(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const response = await shopifyFetch({
|
||||
query: CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION,
|
||||
variables: { input: { email, password } },
|
||||
});
|
||||
|
||||
const result = response.data.customerAccessTokenCreate;
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function logout(accessToken: string): Promise<void> {
|
||||
try {
|
||||
await shopifyFetch({
|
||||
query: CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION,
|
||||
variables: { customerAccessToken: accessToken },
|
||||
});
|
||||
} catch (err) {
|
||||
// The cookie is cleared regardless; a failed revoke shouldn't block logout.
|
||||
console.error('Failed to revoke customer access token:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Always resolves without error detail: revealing whether an address exists
|
||||
// would leak account membership.
|
||||
export async function recoverPassword(email: string): Promise<void> {
|
||||
try {
|
||||
await shopifyFetch({
|
||||
query: CUSTOMER_RECOVER_MUTATION,
|
||||
variables: { email },
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Password recovery request failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function resetPassword(
|
||||
id: string,
|
||||
resetToken: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const response = await shopifyFetch({
|
||||
query: CUSTOMER_RESET_MUTATION,
|
||||
variables: { id, input: { resetToken, password } },
|
||||
});
|
||||
|
||||
const result = response.data.customerReset;
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function activateAccount(
|
||||
id: string,
|
||||
activationToken: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const response = await shopifyFetch({
|
||||
query: CUSTOMER_ACTIVATE_MUTATION,
|
||||
variables: { id, input: { activationToken, password } },
|
||||
});
|
||||
|
||||
const result = response.data.customerActivate;
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCustomer(
|
||||
accessToken: string,
|
||||
orderCount = 10
|
||||
): Promise<Customer | null> {
|
||||
try {
|
||||
const response = await shopifyFetch({
|
||||
query: CUSTOMER_QUERY,
|
||||
variables: { customerAccessToken: accessToken, orderCount },
|
||||
});
|
||||
|
||||
return response.data.customer ?? null;
|
||||
} catch (err) {
|
||||
// An expired or revoked token reads as "not signed in".
|
||||
console.error('Failed to load customer:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateCustomer(
|
||||
accessToken: string,
|
||||
customer: {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
}
|
||||
): Promise<{ customer: Customer | null; errors: CustomerUserError[] }> {
|
||||
const response = await shopifyFetch({
|
||||
query: CUSTOMER_UPDATE_MUTATION,
|
||||
variables: { customerAccessToken: accessToken, customer },
|
||||
});
|
||||
|
||||
const result = response.data.customerUpdate;
|
||||
|
||||
return {
|
||||
customer: result.customer ?? null,
|
||||
errors: result.customerUserErrors ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
// Shopify's emailed links carry a numeric id; the mutations want a GID.
|
||||
export function toCustomerGid(id: string): string {
|
||||
return id.startsWith('gid://') ? id : `gid://shopify/Customer/${id}`;
|
||||
}
|
||||
Reference in New Issue
Block a user