feat(mall): authenticate against the live API
Wave 2 of replacing the fixed-data mock adapter: the auth domain joins the live list, so credentials, roles and tokens belong to the real user. - session: validate a restored token through /auth/me instead of trusting localStorage, clearing it on 401/403 but keeping it when the API is merely unreachable; the route guard now uses the validated session - login: report a 401 as invalid credentials rather than a generic failure, and drop the 6-character client rule so the API owns the password policy - register: raise the rule to the API's 8 characters, remove the verification-code field (its button only counted down and the value was never sent), and report a duplicate email (409) distinctly - TopBar and the user profile render their session-dependent branch client-only: validating the session before hydration made those localStorage-backed branches report hydration mismatches the previous code did not Verified against the running backend: wrong password rejected, real JWT issued, /user reachable, a short password refused with no network call, duplicate email reported, a tampered token cleared and bounced to sign-in, a stale token kept when the API is down, and the fixed-data rollback still signs in with the backend stopped. Also re-cuts docs/TBD-migrate-wave.md: auth is done, and cart, orders, shipments and invoices must move together, because the mock adapter keeps their state in one shared object and a partial flip fails at checkout. OpenSpec change: openspec/changes/replace-mock-api-wave-2
This commit is contained in:
@@ -18,17 +18,27 @@ const { t } = useI18n();
|
||||
<li class="city">{{ t("shell.city") }}</li>
|
||||
</ul>
|
||||
<ul class="right">
|
||||
<template v-if="session.isLoggedIn">
|
||||
<li>{{ t("shell.welcome") }}<NuxtLink to="/user" class="red">{{ session.user?.display_name }}</NuxtLink></li>
|
||||
<li>|</li>
|
||||
<li><NuxtLink to="/user">{{ t("shell.userCenter") }}</NuxtLink></li>
|
||||
<li>|</li>
|
||||
<li class="clickable" @click="session.logout()">{{ t("shell.logout") }}</li>
|
||||
</template>
|
||||
<template v-else>
|
||||
<li><NuxtLink to="/login" class="red">{{ t("shell.login") }}</NuxtLink></li>
|
||||
<li><NuxtLink to="/register">{{ t("shell.register") }}</NuxtLink></li>
|
||||
</template>
|
||||
<!-- The token lives in localStorage, so the server cannot know whether
|
||||
anyone is signed in. Rendering this branch client-only keeps the
|
||||
hydrated DOM in step with the server's logged-out markup; without
|
||||
it, validating the session before hydration reports mismatches. -->
|
||||
<ClientOnly>
|
||||
<template v-if="session.isLoggedIn">
|
||||
<li>{{ t("shell.welcome") }}<NuxtLink to="/user" class="red">{{ session.user?.display_name }}</NuxtLink></li>
|
||||
<li>|</li>
|
||||
<li><NuxtLink to="/user">{{ t("shell.userCenter") }}</NuxtLink></li>
|
||||
<li>|</li>
|
||||
<li class="clickable" @click="session.logout()">{{ t("shell.logout") }}</li>
|
||||
</template>
|
||||
<template v-else>
|
||||
<li><NuxtLink to="/login" class="red">{{ t("shell.login") }}</NuxtLink></li>
|
||||
<li><NuxtLink to="/register">{{ t("shell.register") }}</NuxtLink></li>
|
||||
</template>
|
||||
<template #fallback>
|
||||
<li><NuxtLink to="/login" class="red">{{ t("shell.login") }}</NuxtLink></li>
|
||||
<li><NuxtLink to="/register">{{ t("shell.register") }}</NuxtLink></li>
|
||||
</template>
|
||||
</ClientOnly>
|
||||
<li>|</li>
|
||||
<li><NuxtLink to="/stores" class="red">{{ t("shell.sellerJoin") }}</NuxtLink></li>
|
||||
<li>|</li>
|
||||
|
||||
@@ -29,9 +29,11 @@ export default {
|
||||
resetSuccessHint: "Your password has been reset. Sign in with your new password.",
|
||||
validationRequired: "Please complete all required fields.",
|
||||
validationEmail: "Enter a valid email address.",
|
||||
validationPassword: "Password must be at least 6 characters.",
|
||||
validationPassword: "Password must be at least 8 characters.",
|
||||
validationMismatch: "Passwords do not match.",
|
||||
requestFailed: "Unable to complete this request. Please try again.",
|
||||
invalidCredentials: "Incorrect email or password.",
|
||||
emailTaken: "That email is already registered.",
|
||||
},
|
||||
},
|
||||
zh: {
|
||||
@@ -64,9 +66,11 @@ export default {
|
||||
resetSuccessHint: "您的密码已重置,请使用新密码登录。",
|
||||
validationRequired: "请填写所有必填项。",
|
||||
validationEmail: "请输入有效的邮箱地址。",
|
||||
validationPassword: "密码至少需要 6 位。",
|
||||
validationPassword: "密码至少需要 8 位。",
|
||||
validationMismatch: "两次输入的密码不一致。",
|
||||
requestFailed: "操作失败,请稍后重试。",
|
||||
invalidCredentials: "邮箱或密码不正确。",
|
||||
emailTaken: "该邮箱已被注册。",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
export default defineNuxtRouteMiddleware(() => {
|
||||
export default defineNuxtRouteMiddleware(async () => {
|
||||
if (import.meta.server) return;
|
||||
const token = localStorage.getItem("vmall.token");
|
||||
let role: string | null = null;
|
||||
try {
|
||||
const raw = localStorage.getItem("vmall.user");
|
||||
const user: unknown = raw ? JSON.parse(raw) : null;
|
||||
if (user && typeof user === "object" && "role" in user && typeof user.role === "string") {
|
||||
role = user.role;
|
||||
}
|
||||
} catch {
|
||||
role = null;
|
||||
}
|
||||
if (!token || role !== "customer") return navigateTo("/login");
|
||||
const session = useSessionStore();
|
||||
if (!session.token) session.hydrate();
|
||||
if (!session.token) return navigateTo("/login");
|
||||
// Trust the auth API's answer rather than whatever localStorage claims; a
|
||||
// rejected token clears the session inside validate().
|
||||
if (!(await session.validate())) return navigateTo("/login");
|
||||
if (session.user?.role !== "customer") return navigateTo("/login");
|
||||
});
|
||||
|
||||
@@ -8,8 +8,8 @@ export default defineNuxtConfig({
|
||||
apiBase: "http://localhost:8080/api",
|
||||
// Domains served by the live backend; every other domain stays on the
|
||||
// fixed-data adapter. Override with NUXT_PUBLIC_LIVE_DOMAINS='["catalog"]'.
|
||||
// See openspec/changes/replace-mock-api-wave-1/design.md.
|
||||
liveDomains: ["catalog", "currency"],
|
||||
// See openspec/changes/replace-mock-api-wave-1/design.md and wave 2.
|
||||
liveDomains: ["catalog", "currency", "auth"],
|
||||
appName: "mall",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -35,7 +35,8 @@ function validate(): boolean {
|
||||
errorKey.value = "auth.validationEmail";
|
||||
return false;
|
||||
}
|
||||
if (password.value.length < 6) {
|
||||
// Matches the shared validationPassword message and the auth API's rule.
|
||||
if (password.value.length < 8) {
|
||||
errorKey.value = "auth.validationPassword";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { ApiError } from "@vmall/shared";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
const session = useSessionStore();
|
||||
@@ -18,10 +20,8 @@ function validate(): boolean {
|
||||
errorKey.value = "auth.validationEmail";
|
||||
return false;
|
||||
}
|
||||
if (password.value.length < 6) {
|
||||
errorKey.value = "auth.validationPassword";
|
||||
return false;
|
||||
}
|
||||
// No length rule here: the auth API owns the password policy, and a wrong
|
||||
// password should be reported as rejected credentials, not as bad input.
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -33,8 +33,10 @@ async function submit(): Promise<void> {
|
||||
const auth = await $api.login(email.value, password.value);
|
||||
session.setAuth(auth);
|
||||
await router.push("/");
|
||||
} catch {
|
||||
errorKey.value = "auth.requestFailed";
|
||||
} catch (error) {
|
||||
errorKey.value = error instanceof ApiError && error.status === 401
|
||||
? "auth.invalidCredentials"
|
||||
: "auth.requestFailed";
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { ApiError } from "@vmall/shared";
|
||||
|
||||
const { t } = useI18n();
|
||||
const { $api } = useNuxtApp();
|
||||
const session = useSessionStore();
|
||||
@@ -8,30 +10,14 @@ const displayName = ref("");
|
||||
const email = ref("");
|
||||
const password = ref("");
|
||||
const confirmPassword = ref("");
|
||||
const code = ref("");
|
||||
const errorKey = ref("");
|
||||
const submitting = ref(false);
|
||||
const countdown = ref(0);
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
function startCountdown(): void {
|
||||
if (countdown.value > 0) return;
|
||||
countdown.value = 60;
|
||||
timer = setInterval(() => {
|
||||
countdown.value -= 1;
|
||||
if (countdown.value <= 0 && timer) {
|
||||
clearInterval(timer);
|
||||
timer = undefined;
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
if (timer) clearInterval(timer);
|
||||
});
|
||||
/** Mirrors the auth API's rule so a short password fails here, not as a 400. */
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
function validate(): boolean {
|
||||
if (!displayName.value || !email.value || !password.value || !confirmPassword.value || !code.value) {
|
||||
if (!displayName.value || !email.value || !password.value || !confirmPassword.value) {
|
||||
errorKey.value = "auth.validationRequired";
|
||||
return false;
|
||||
}
|
||||
@@ -39,7 +25,7 @@ function validate(): boolean {
|
||||
errorKey.value = "auth.validationEmail";
|
||||
return false;
|
||||
}
|
||||
if (password.value.length < 6) {
|
||||
if (password.value.length < MIN_PASSWORD_LENGTH) {
|
||||
errorKey.value = "auth.validationPassword";
|
||||
return false;
|
||||
}
|
||||
@@ -58,8 +44,10 @@ async function submit(): Promise<void> {
|
||||
const auth = await $api.register(email.value, password.value, displayName.value);
|
||||
session.setAuth(auth);
|
||||
await router.push("/");
|
||||
} catch {
|
||||
errorKey.value = "auth.requestFailed";
|
||||
} catch (error) {
|
||||
errorKey.value = error instanceof ApiError && error.status === 409
|
||||
? "auth.emailTaken"
|
||||
: "auth.requestFailed";
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
@@ -91,15 +79,6 @@ async function submit(): Promise<void> {
|
||||
<span>{{ t("auth.confirmPassword") }}</span>
|
||||
<input v-model="confirmPassword" class="minput" type="password" autocomplete="new-password" :placeholder="t('auth.confirmPasswordPlaceholder')" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>{{ t("auth.smsCode") }}</span>
|
||||
<span class="code-row">
|
||||
<input v-model.trim="code" class="minput" type="text" :placeholder="t('auth.smsCodePlaceholder')" />
|
||||
<button class="mbtn code-button" type="button" :disabled="countdown > 0" @click="startCountdown">
|
||||
{{ countdown > 0 ? t("auth.codeCountdown", { n: countdown }) : t("auth.getCode") }}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
<p v-if="errorKey" class="error">{{ t(errorKey) }}</p>
|
||||
<button class="mbtn red block submit" type="submit" :disabled="submitting">
|
||||
{{ t("auth.registerAction") }}
|
||||
|
||||
@@ -36,7 +36,8 @@ function isActive(to: string): boolean {
|
||||
<div class="profile">
|
||||
<img src="/mock/avatar.svg" :alt="t('user.title')" />
|
||||
<div class="profile-copy">
|
||||
<strong>{{ session.user?.display_name }}</strong>
|
||||
<!-- Session lives in localStorage, so the name is unknown at SSR time. -->
|
||||
<ClientOnly><strong>{{ session.user?.display_name }}</strong></ClientOnly>
|
||||
<NuxtLink to="/user">{{ t("user.editProfile") }}</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { ApiError } from "@vmall/shared";
|
||||
import type { AuthTokens, User } from "@vmall/shared";
|
||||
|
||||
const USER_KEY = "vmall.user";
|
||||
@@ -30,10 +31,12 @@ export function readStoredUser(): User | null {
|
||||
interface SessionState {
|
||||
user: User | null;
|
||||
token: string | null;
|
||||
/** Set once the session is trusted: by a fresh sign-in or a successful validate(). */
|
||||
validated: boolean;
|
||||
}
|
||||
|
||||
export const useSessionStore = defineStore("session", {
|
||||
state: (): SessionState => ({ user: null, token: null }),
|
||||
state: (): SessionState => ({ user: null, token: null, validated: false }),
|
||||
getters: {
|
||||
isLoggedIn: (s): boolean => s.token !== null,
|
||||
},
|
||||
@@ -46,18 +49,48 @@ export const useSessionStore = defineStore("session", {
|
||||
setAuth(auth: AuthTokens): void {
|
||||
this.token = auth.token;
|
||||
this.user = auth.user;
|
||||
this.validated = true;
|
||||
if (import.meta.client) {
|
||||
localStorage.setItem(TOKEN_KEY, auth.token);
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(auth.user));
|
||||
}
|
||||
},
|
||||
logout(): void {
|
||||
clear(): void {
|
||||
this.token = null;
|
||||
this.user = null;
|
||||
this.validated = false;
|
||||
if (import.meta.client) {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Check a token restored from storage against the auth API, replacing the
|
||||
* previous blind trust in localStorage. Only a rejected token clears the
|
||||
* session - an unreachable API must not sign the shopper out. Runs at most
|
||||
* once per load, because setAuth() marks a fresh sign-in as already trusted.
|
||||
*/
|
||||
async validate(): Promise<boolean> {
|
||||
if (this.validated) return true;
|
||||
if (!import.meta.client || !this.token) return false;
|
||||
const { $api } = useNuxtApp();
|
||||
try {
|
||||
const user = await $api.me();
|
||||
this.user = user;
|
||||
this.validated = true;
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
|
||||
this.clear();
|
||||
return false;
|
||||
}
|
||||
// Network or server failure: keep the session rather than guess.
|
||||
return this.token !== null;
|
||||
}
|
||||
},
|
||||
logout(): void {
|
||||
this.clear();
|
||||
navigateTo("/login");
|
||||
},
|
||||
},
|
||||
|
||||
+38
-25
@@ -1,46 +1,58 @@
|
||||
# TBD — migrate the mall off the mock API (waves 2+)
|
||||
# TBD — migrate the mall off the mock API (waves 3+)
|
||||
|
||||
Wave 1 is planned in the OpenSpec change `openspec/changes/replace-mock-api-wave-1/`
|
||||
(catalog + currency). This file tracks everything after it.
|
||||
Waves 1 and 2 are captured in `openspec/changes/replace-mock-api-wave-1/` (catalog +
|
||||
currency) and `replace-mock-api-wave-2/` (auth). This file tracks what remains.
|
||||
|
||||
**How to use:** check a box only once the behaviour is implemented *and* verified against
|
||||
the live backend (`cargo run -p vmall-api`, `node scripts/seed-demo.mjs`). Wave 1 leaves a
|
||||
per-domain switch in `apps/mall/plugins/api.ts`, so most of these are adding a domain name
|
||||
to the live list — each still needs its own verification below.
|
||||
the live backend (`cargo run -p vmall-api`, `node scripts/seed-demo.mjs`). The per-domain
|
||||
switch in `apps/mall/plugins/api.ts` means most of these are adding a domain name to the
|
||||
live list — each still needs its own verification below.
|
||||
|
||||
**Delete this file** once every box in Waves 2 and 3 is checked. Wave 4 is optional: if you
|
||||
decide against it, delete this file anyway and record that decision wherever you like.
|
||||
**Delete this file** once every box in Wave 3 is checked. Wave 4 is optional: if you decide
|
||||
against it, delete this file anyway and record that decision wherever you like.
|
||||
|
||||
---
|
||||
|
||||
## Wave 2 — auth + cart
|
||||
## Wave 2 — auth (done)
|
||||
|
||||
- [ ] Flip `auth` to live and verify `login` / `register` / `me` against `:8080` using the seeded `customer@vmall.local` / `customer123`.
|
||||
- [ ] Confirm bad credentials now produce a real 401 — the mock accepted any input (`apps/mall/mock/api.ts:125`), so this is a deliberate UX change.
|
||||
- [ ] Confirm the JWT round-trips through the `vmall.token` localStorage key, shared with shop-admin and admin, and that logout clears it.
|
||||
- [ ] Flip `cart` to live. Cart requires a token (`AuthUser` on all four handlers in `apps/api/src/routes/cart.rs`) and real SKU ids from Wave 1 — both are prerequisites, not optional.
|
||||
- [ ] Remove cart's mock display coupling: `apps/mall/pages/cart.vue:4,34,41,56,60` uses `productById` / `storeById` for shop name, image and stock. The live `CartView` already returns `product_name`, `image` and `unit_price_minor` (`apps/api/src/cart.rs:44-53`).
|
||||
- [ ] Verify: add / qty update / remove / empty cart for a logged-out user, and the out-of-stock 409 path.
|
||||
Captured in `openspec/changes/replace-mock-api-wave-2/`; auth is live, with the session
|
||||
validated through `/auth/me` rather than trusted from `localStorage`.
|
||||
|
||||
## Wave 3 — orders + shipments + invoices
|
||||
- [x] Flip `auth` to live and verify `login` / `register` / `me` against `:8080` using the seeded `customer@vmall.local` / `customer123`.
|
||||
- [x] Confirm bad credentials now produce a real 401 — the mock accepted any input (`apps/mall/mock/api.ts:125`), so this is a deliberate UX change.
|
||||
- [x] Confirm the JWT round-trips through the `vmall.token` localStorage key, shared with shop-admin and admin, and that logout clears it.
|
||||
|
||||
- [ ] Flip `orders` to live and verify checkout splits one cart into per-shop orders with a price snapshot and stock decrement.
|
||||
- [ ] Checkout still sources `shipping_address` from `MOCK_ADDRESSES` (`apps/mall/pages/checkout/index.vue:4,23,37,127`) — that is intentional; see the out-of-scope note below.
|
||||
- [ ] Verify cancel restores stock and `payOrder` only accepts `pending_payment` (both are enforced live; the mock only mimicked them).
|
||||
- [ ] Flip `shipments` to live and verify `confirmDelivered` moves the order to `completed`.
|
||||
- [ ] Flip `invoices` to live and verify a company invoice requires a tax number and that one order can hold only one active invoice.
|
||||
## Wave 3 — the transaction chain: cart + orders + shipments + invoices
|
||||
|
||||
These move **together**, not one at a time. The mock adapter keeps
|
||||
`state.cart -> state.orders -> state.shipments` in a single shared state, so a partial flip
|
||||
leaves the mock half reading state the live half never populates:
|
||||
|
||||
- live cart + mock `checkout()` fails with `EMPTY_CART` (`apps/mall/mock/api.ts:194`),
|
||||
- mock `requestInvoice()` 404s on any live order id (`mock/api.ts:285`),
|
||||
- mock `listMyShipments()` returns shipments whose `order_id` matches no live order, so the
|
||||
shipment block is silently empty (`mock/api.ts:282`, `pages/user/orders/[id].vue:25`).
|
||||
|
||||
- [ ] Flip `cart`, `orders`, `shipments` and `invoices` in the same change, then verify one purchase end to end: add to cart, check out into per-shop orders, pay, ship, confirm delivery, request an invoice.
|
||||
- [ ] Verify cancel restores stock and `payOrder` only accepts `pending_payment` (both enforced live; the mock only mimicked them).
|
||||
- [ ] Verify a company invoice requires a tax number, and that one order can hold only one active invoice.
|
||||
- [ ] Remove cart's mock display coupling: `apps/mall/pages/cart.vue:4,34,41,56,60` uses `productById` / `storeById` for shop name, image and stock. The live `CartView` already returns `product_name`, `image` and `unit_price_minor` (`apps/api/src/cart.rs:44-53`) — but **not** the shop, so decide whether to add a shop field to `CartItem` in the shared contract or accept ungrouped lines until the public store read exists.
|
||||
- [ ] Decide what caps cart quantity: `CartItem` carries no `stock`, so `maxFor` falls back to 999 (`pages/cart.vue:60`). The live cart does not enforce stock either — only checkout does (409). Either add `stock` to `CartItem` or keep the cap at checkout and say so.
|
||||
- [ ] Gate add-to-cart for anonymous shoppers: a live `addCartItem` on the public product page returns 401, and `pages/goods/[id].vue` is not behind the auth middleware.
|
||||
- [ ] Checkout keeps sourcing `shipping_address` from `MOCK_ADDRESSES` (`pages/checkout/index.vue:4,23,37,127`) — intentional; see the out-of-scope note below.
|
||||
- [ ] Fix contract debt so the TS types stop lying: `Shipment.items` is required in `packages/shared/src/types.ts` but the live struct has no `items` field (`apps/api/src/models.rs:172-182`), and `Invoice.invoice_no` is nullable live (`models.rs:194`) but non-null `string` in TS.
|
||||
- [ ] Remove the remaining `storeById` mock usage on the order pages (`apps/mall/pages/user/orders/index.vue:4`).
|
||||
- [ ] Confirm the mall still renders when the live API is down (mock mode remains the fallback for local UI work).
|
||||
- [ ] Confirm the mall still renders when the live API is down, with every domain configured to fixed data.
|
||||
|
||||
## Wave 4 — optional new backend capabilities
|
||||
## Wave 4 — optional, mostly new backend capabilities
|
||||
|
||||
Only if you want more of the storefront backed by real data. Each is a new capability, not a flip.
|
||||
|
||||
- [ ] **Storefront content** — banners, promos, quick links, home floors and floor advert art. Needs real tables, admin CRUD and i18n JSONB. Do this first if you want the home page fully live; it is the most visible remaining mock surface.
|
||||
- [ ] **Public store read** — a buyer-facing shop endpoint so `stores/index` and `stores/[id]` leave mock. Small: products already carry `shop_id`, and the public catalog already joins shops for the active check.
|
||||
- [ ] **Storefront content** — banners, promos, quick links and floor advert art. Needs real tables, admin CRUD and i18n JSONB. Do this first if you want the home page fully live; it is the most visible remaining mock surface.
|
||||
- [ ] **Public store read** — a buyer-facing shop endpoint so `stores/index`, `stores/[id]` and the cart's shop grouping leave mock. Small: products already carry `shop_id`, and the public catalog already joins shops for the active check.
|
||||
- [ ] **Brand model + sales/comments sorts** — restores the brand facet and the sorts removed in Wave 1. Needs a `brands` table (`products.brand_id` + i18n) plus sales and comments data, neither of which exists today.
|
||||
- [ ] Extend the `ORDER BY` whitelist if more sorts are wanted beyond the `sort=price` added in Wave 1.
|
||||
- [ ] *(adjacent, not part of the migration)* Move the session token to a cookie so SSR knows whether anyone is signed in. Today a full page load of a guarded route renders the page and then redirects on the client, which logs a hydration mismatch; it is pre-existing (verified identical before Wave 2) and harmless, but it is the real fix for the `ClientOnly` workarounds in `components/shell/TopBar.vue` and `pages/user.vue`.
|
||||
|
||||
---
|
||||
|
||||
@@ -57,3 +69,4 @@ These have no API contract and no backend model. Leaving them on `~/mock/data` i
|
||||
- Category filtering is by **subtree**; the backend exact-match filter was the bug (fixed in Wave 1).
|
||||
- A migration wave must not change what the UI claims: facets without a backing model are removed rather than left matching nothing.
|
||||
- The mall is the last mock holdout; `shop-admin` and `admin` already run live against the same backend.
|
||||
- Auth flips independently, but the transaction domains do not: the mock's shared cart/order/shipment state makes any partial flip fail loudly.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-09-17
|
||||
@@ -0,0 +1,60 @@
|
||||
# Design
|
||||
|
||||
## Context
|
||||
|
||||
See `proposal.md` — Why. After wave 1 the mall selects adapters per domain through `liveDomains` (`apps/mall/plugins/api.ts`); `auth`, `cart`, `orders`, `shipments` and `invoices` are what remain on fixed data.
|
||||
|
||||
Session truth today lives entirely in `localStorage`: `vmall.token` is read by the plugin's `getToken`, `vmall.user` is read by `middleware/auth.ts`, and both are written by `stores/session.ts`. The fixed-data `me()` returns a constant `MOCK_USER`, so nothing ever proves a stored token is still valid.
|
||||
|
||||
The live contract this wave targets (`apps/api/src/routes/auth.rs`):
|
||||
|
||||
| Endpoint | Behaviour |
|
||||
|---|---|
|
||||
| `POST /auth/register` | 400 on invalid email, password under 8 characters, or blank display name; **409** on duplicate email |
|
||||
| `POST /auth/login` | **401** on bad credentials; returns `{ token, user }` |
|
||||
| `GET /auth/me` | requires a bearer token; returns the `User` |
|
||||
|
||||
`ApiError` already carries `status` and `code` (`packages/shared/src/api.ts:26-34`).
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Credentials, roles and tokens become the real user's, with failures reported distinctly.
|
||||
- The flip stays confined to the `auth` domain, so every other domain keeps working.
|
||||
|
||||
**Non-Goals:**
|
||||
- No refresh-token or cookie/session-server move: the JWT stays in `localStorage`.
|
||||
- No password-reset backend; `/forgot-password` stays presentational, which is a known gap rather than something this wave fixes.
|
||||
- No change to what the buyer center displays — its data is still fixed.
|
||||
|
||||
## Decisions
|
||||
|
||||
**1. Validate a restored token once per load through `me()`, and only clear the session on 401/403.**
|
||||
`middleware/auth.ts` currently trusts `localStorage`, so a stale or forged token reaches protected pages and fails later, further from the cause. A single `me()` call on hydrate puts the check where the session is established.
|
||||
*Alternatives:* a 401 interceptor inside the shared `request()` helper (touches all three apps — a shared-package change outside this wave); validating in every guarded page (one call per navigation).
|
||||
A network failure is deliberately **not** treated as a rejected token, so an unreachable API does not silently log the shopper out.
|
||||
|
||||
**2. The 8-character rule lives in the panel and mirrors the API.**
|
||||
The API is the authority; the client check exists only to avoid a pointless round trip and a generic error. Relaxing the API to accept 6 would weaken the backend and needs a change outside this wave.
|
||||
|
||||
**3. Errors are mapped on `ApiError.status`/`code`, never on message text.**
|
||||
Matching the API's prose would break whenever its wording changes. New strings go in `apps/mall/locales-extra.ts`, because AGENTS.md reserves the shared locale bundle for contract changes.
|
||||
|
||||
**4. The register panel drops the verification-code field.**
|
||||
It is a mandatory no-op: the button only starts a countdown, the value is never sent, and no endpoint issues a code. Keeping it would demand input the API never checks.
|
||||
|
||||
**5. `liveDomains` gains `auth`; rollback stays a one-string edit.**
|
||||
The fixed-data adapter keeps serving auth, so removing the entry restores the previous behaviour with no data migration.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [A 401 from a still-mocked domain could be mistaken for a session failure] → only `me()` drives validation; cart, orders and invoices stay fixed-data and never answer 401.
|
||||
- [Validation adds a round trip before the session is usable] → it runs only when a stored token exists, and it replaces blind trust rather than adding a second source of truth.
|
||||
- [The demo loses "any password works"] → intended and marked **BREAKING**; the seeded `customer@vmall.local` account still demonstrates sign-in.
|
||||
- [The register panel becomes shorter than the backend's own validation] → the panel mirrors the API rule, and the API still enforces it independently.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
1. Add `auth` to `liveDomains` and land the panel, session and middleware changes in the same commit, so no user can submit the old 6-character rule against the new API.
|
||||
2. Verify against the running backend with the seeded customer, then a wrong password, then a tampered token.
|
||||
3. Rollback: drop `auth` from `liveDomains`. The fixed-data adapter still serves the domain, and no stored data needs reverting.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Auth is the last thing between the mall and real accounts. The fixed-data adapter accepts any credentials and always returns the same demo user, so login, register and "me" are theatre — and every domain needing a bearer token (cart, orders, invoices) is pinned behind them. `shop-admin` and `admin` already authenticate against the live backend.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Flip the `auth` domain to live via `liveDomains`; cart, orders, shipments and invoices stay on fixed data.
|
||||
- Align the client password rule with the API: the panels require 6 characters, but `/auth/register` requires 8 and answers 400 (`apps/api/src/routes/auth.rs:32`).
|
||||
- Map real failures to distinct messages — 401 for bad credentials, 409 when an email is taken — instead of one generic "request failed".
|
||||
- Drop the register SMS-code field: its button only runs a countdown, there is no endpoint, and the value is never sent, so it is a mandatory no-op once auth is real.
|
||||
- Validate a stored token through `/auth/me` on load rather than trusting `localStorage` alone.
|
||||
- **BREAKING** (auth UX): the demo's "log in as anyone, any password" behaviour ends; wrong credentials now fail.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
(none)
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `frontend-mall`: the "Auth and buyer center" requirement stops being backed by deterministic mock auth and uses the live auth API.
|
||||
|
||||
## Impact
|
||||
|
||||
`apps/mall/plugins/api.ts` and `apps/mall/nuxt.config.ts` (`liveDomains`), `pages/login.vue`, `pages/register.vue`, `stores/session.ts`, `middleware/auth.ts`, and `locales-extra.ts` for the new error strings. No backend or `shop-admin`/`admin` change.
|
||||
|
||||
## Non-goals
|
||||
|
||||
Cart, orders, shipments and invoices stay on fixed data: the mock adapter holds `cart -> orders -> shipments` as one shared state, so flipping cart alone would fail checkout with `EMPTY_CART`. They move together in a later wave. No store, address, favourite or coupon work.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Spec Delta
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Auth and buyer center
|
||||
The mall SHALL provide B2B2C mall-style login, register and forgot-password panels backed by the live auth API, so credentials, roles and tokens belong to the real user rather than a fixed demo account. Registration SHALL require a password of at least 8 characters, matching the API's rule, and the register panel SHALL NOT ask for a verification code because no endpoint issues one. Failures SHALL be reported distinctly: invalid credentials on sign-in, and an already-registered email on registration. A token restored from storage SHALL be validated against the auth API on load, and a rejected token SHALL clear the session and return the shopper to sign-in. `/user` SHALL render a two-column buyer center with dashboard, order list/detail, addresses, favorites, coupons and invoices.
|
||||
|
||||
#### Scenario: sign in and inspect buyer data
|
||||
- **WHEN** a shopper signs in with valid credentials and opens `/user`
|
||||
- **THEN** the session carries the authenticated user, and the buyer-center shell and its fixed account/order/address/favorite/coupon/invoice data render
|
||||
|
||||
#### Scenario: wrong password rejected
|
||||
- **WHEN** a shopper submits a password that does not match the account
|
||||
- **THEN** sign-in fails with an invalid-credentials message and no session is established
|
||||
|
||||
#### Scenario: short password refused before the API call
|
||||
- **WHEN** a shopper submits a registration password shorter than 8 characters
|
||||
- **THEN** the panel asks for at least 8 characters without calling the API
|
||||
|
||||
#### Scenario: duplicate email reported
|
||||
- **WHEN** a shopper registers an email that already has an account
|
||||
- **THEN** the panel reports that the email is already registered rather than a generic failure
|
||||
|
||||
#### Scenario: rejected token clears the session
|
||||
- **WHEN** a token restored from storage is rejected by the auth API
|
||||
- **THEN** the stored session is cleared and the shopper is returned to sign-in
|
||||
@@ -0,0 +1,28 @@
|
||||
# Tasks
|
||||
|
||||
## 1. Adapter and configuration
|
||||
|
||||
- [x] 1.1 Add `auth` to the default `liveDomains` in `apps/mall/nuxt.config.ts` and confirm `LIVE_PICKS.auth` in `apps/mall/plugins/api.ts` already covers `register`/`login`/`me`; verify a sign-in request reaches `:8080` while `getCart` still resolves from fixed data
|
||||
- [x] 1.2 Confirm the rollback path: with `NUXT_PUBLIC_LIVE_DOMAINS` set to catalog and currency only, sign-in returns the fixed demo user again; verify by signing in with any password
|
||||
|
||||
## 2. Session and route guard
|
||||
|
||||
- [x] 2.1 Add a session action that validates a restored token through `$api.me()`, clearing the stored session and returning to sign-in on 401/403 but leaving the session intact when the API is merely unreachable; verify with a tampered `vmall.token` and again with the backend stopped
|
||||
- [x] 2.2 Make `middleware/auth.ts` rely on the validated session rather than `localStorage` alone; verify a shopper with a stale token lands on `/login` while a valid one reaches `/user`
|
||||
- [x] 2.3 Render the session-dependent header and profile name client-only (`components/shell/TopBar.vue`, `pages/user.vue`); added during implementation because validating the session before hydration made those `localStorage`-backed branches report hydration mismatches that the pre-change code did not; verified by A/B that the sign-in flow now produces no mismatch warnings
|
||||
|
||||
## 3. Sign-in panel
|
||||
|
||||
- [x] 3.1 Map failures on `ApiError.status`/`code` so a 401 reports invalid credentials rather than the current generic message, adding the key to `apps/mall/locales/auth.ts` in en and zh (the per-domain module behind `locales-extra.ts`); verify with a deliberately wrong password
|
||||
|
||||
## 4. Registration panel
|
||||
|
||||
- [x] 4.1 Raise the client password rule to 8 characters with its own message; verify a 7-character password is refused without any network call. `apps/mall/pages/forgot-password.vue` was aligned to the same rule because it shares the `validationPassword` message
|
||||
- [x] 4.2 Remove the verification-code field and its countdown so the form no longer requires it; verify registration submits with display name, email and password only
|
||||
- [x] 4.3 Report a duplicate email (409) distinctly from other failures, adding the key to `apps/mall/locales/auth.ts` in en and zh; verify by registering an address that already exists
|
||||
|
||||
## 5. Verification
|
||||
|
||||
- [x] 5.1 Run `pnpm --filter @vmall/mall build` and confirm it passes
|
||||
- [x] 5.2 With the backend running and seeded, verify in a browser: sign in as `customer@vmall.local`, see the utility-bar welcome/sign-out state, reach `/user`, and confirm the only console entries are the deliberately triggered 401/409 responses plus a pre-existing hydration warning on the unauthenticated `/user` redirect (A/B verified identical before this change)
|
||||
- [x] 5.3 With every domain set to fixed data and the backend stopped, verify sign-in and browsing still work, so the rollback path is intact
|
||||
Reference in New Issue
Block a user