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");
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user