@ -8,6 +8,15 @@ import "@/styles/look-grid.css"
|
||||
|
||||
const { locale, t, getRelativeLocaleUrl } = getI18n(Astro)
|
||||
|
||||
// 登录门禁弹窗文案
|
||||
const loginModalTitle = t('login')
|
||||
const loginModalPrompt = t('login to continue')
|
||||
const loginModalAccountLabel = t('username or email')
|
||||
const loginModalPasswordLabel = t('password')
|
||||
const loginModalSubmitLabel = t('login')
|
||||
const loginModalClose = t('close')
|
||||
const loginModalFail = t('login failed')
|
||||
|
||||
// 热门品牌:走 SSG 专属接口 /api/v1/ssg/brands/hot,后端固定返回热度前 30 个、按热度顺序排列。
|
||||
// 侧栏 filter 展示前 10 个(模板内 slice(0,10)),品牌弹窗 HOT 标签展示全部 30 个。
|
||||
// 接口不可用时回落假数据先看效果。
|
||||
@ -64,7 +73,7 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
|
||||
---
|
||||
|
||||
<div class="showsroot w-full" x-data="showsPage()" data-locale={locale}>
|
||||
<div class="showsroot w-full" x-data="showsPage()" data-locale={locale} data-login-fail={loginModalFail}>
|
||||
<!-- 顶部:极简眉头 -->
|
||||
<header class="showshead">
|
||||
<div>
|
||||
@ -252,7 +261,31 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
<!-- 品牌筛选弹窗:抽成独立组件 BrandModal.astro(状态由本页 showsPage 提供) -->
|
||||
<BrandModal />
|
||||
|
||||
|
||||
<!-- 登录门禁弹窗:未登录点筛选/翻页时弹出内联登录表单 -->
|
||||
<div x-show="showLoginModal" x-cloak class="fixed inset-0 z-[100] flex items-center justify-center bg-black/40" @click.self="closeLoginModal()">
|
||||
<div class="bg-white border border-black/10 shadow-lg w-full max-w-md p-8">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<h3 class="font-serif text-2xl uppercase">{loginModalTitle}</h3>
|
||||
<button type="button" @click="closeLoginModal()" class="text-xs uppercase tracking-widest hover:opacity-60">{loginModalClose}</button>
|
||||
</div>
|
||||
<p class="text-xs text-zinc-500 uppercase tracking-wide mb-6">{loginModalPrompt}</p>
|
||||
<form @submit.prevent="modalLogin()" class="space-y-5">
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{loginModalAccountLabel}</label>
|
||||
<input type="text" x-model="loginModalAccount" required class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{loginModalPasswordLabel}</label>
|
||||
<input type="password" x-model="loginModalPassword" required class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
<p x-show="loginModalError" x-text="loginModalError" class="text-xs text-red-600 uppercase tracking-wide"></p>
|
||||
<button type="submit" :disabled="loginModalLoading" class="w-full border border-black py-3 text-[12px] font-bold uppercase tracking-[0.2em] hover:bg-black hover:text-white transition-colors disabled:opacity-40">
|
||||
<span x-show="!loginModalLoading">{loginModalSubmitLabel}</span>
|
||||
<span x-show="loginModalLoading" x-cloak>…</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@ -262,7 +295,7 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
|
||||
|
||||
<script>
|
||||
import { getArticles, getBrands, toAbs, type ArticleItem, type BrandEntry } from "@/lib/api"
|
||||
import { getArticles, getBrands, toAbs, getUser, login, type ArticleItem, type BrandEntry } from "@/lib/api"
|
||||
import { clientHref, ROUTES } from "@/lib/routes"
|
||||
import { SPIN_SVG, makeCardSlots, buildPageList } from "@/lib/looks-grid"
|
||||
|
||||
@ -301,6 +334,13 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
lastPage: 1,
|
||||
reqToken: 0,
|
||||
|
||||
// 登录门禁弹窗状态(硬门禁:未登录点筛选/翻页时弹出内联登录表单)
|
||||
showLoginModal: false,
|
||||
loginModalAccount: "",
|
||||
loginModalPassword: "",
|
||||
loginModalError: "",
|
||||
loginModalLoading: false,
|
||||
|
||||
init() {
|
||||
this.locale = this.$el.dataset.locale || 'en';
|
||||
// 支持从 header 下拉深链 ?collection=xxx 直接进入对应分类(与侧栏 COLLECTION 筛选一致)
|
||||
@ -353,6 +393,7 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
},
|
||||
|
||||
refreshFilter() {
|
||||
if (!this.requireLogin()) return
|
||||
this.loadPage(1)
|
||||
},
|
||||
|
||||
@ -441,6 +482,34 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
this.refreshFilter()
|
||||
},
|
||||
|
||||
// ===== 登录门禁 =====
|
||||
// 未登录返回 false 并弹出登录框;已登录返回 true。
|
||||
requireLogin(): boolean {
|
||||
if (getUser()) return true
|
||||
this.showLoginModal = true
|
||||
return false
|
||||
},
|
||||
async modalLogin() {
|
||||
this.loginModalError = ""
|
||||
this.loginModalLoading = true
|
||||
try {
|
||||
await login({ account: this.loginModalAccount, password: this.loginModalPassword })
|
||||
this.showLoginModal = false
|
||||
this.loginModalAccount = ""
|
||||
this.loginModalPassword = ""
|
||||
// 登录成功后按当前筛选刷新,用户无需再次点击
|
||||
this.loadPage(1)
|
||||
} catch {
|
||||
this.loginModalError = this.$el.dataset.loginFail || "login failed"
|
||||
} finally {
|
||||
this.loginModalLoading = false
|
||||
}
|
||||
},
|
||||
closeLoginModal() {
|
||||
this.showLoginModal = false
|
||||
this.loginModalError = ""
|
||||
},
|
||||
|
||||
// API 加载(分页:每次整页替换,不追加)
|
||||
async loadPage(page: number) {
|
||||
const myToken = ++this.reqToken
|
||||
@ -478,6 +547,7 @@ const seasonOptions: { value: string; label: string }[] = [
|
||||
},
|
||||
|
||||
goPage(p: number) {
|
||||
if (!this.requireLogin()) return
|
||||
if (this.loading) return
|
||||
if (p < 1 || p > this.lastPage || p === this.page) return
|
||||
this.loadPage(p)
|
||||
|
||||
@ -7,6 +7,15 @@ import "@/styles/look-grid.css"
|
||||
|
||||
const { locale, t } = getI18n(Astro)
|
||||
|
||||
// 登录门禁弹窗文案
|
||||
const loginModalTitle = t('login')
|
||||
const loginModalPrompt = t('login to continue')
|
||||
const loginModalAccountLabel = t('username or email')
|
||||
const loginModalPasswordLabel = t('password')
|
||||
const loginModalSubmitLabel = t('login')
|
||||
const loginModalClose = t('close')
|
||||
const loginModalFail = t('login failed')
|
||||
|
||||
// 年份筛选:近 10 年(含当年),末项兜底
|
||||
const currentYear = new Date().getFullYear()
|
||||
const yearFloor = currentYear - 9
|
||||
@ -47,7 +56,7 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
]
|
||||
---
|
||||
|
||||
<div class="snapsroot w-full" x-data="streetSnapsPage()" data-locale={locale}>
|
||||
<div class="snapsroot w-full" x-data="streetSnapsPage()" data-locale={locale} data-login-fail={loginModalFail}>
|
||||
<!-- 顶部:极简眉头 -->
|
||||
<header class="snapshead">
|
||||
<div>
|
||||
@ -88,7 +97,7 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
<div class="snapsg-b" x-show="!collapsedGroups.year">
|
||||
<ul class="snapschecks snapschecks--flat">
|
||||
{yearOptions.map((o) => (
|
||||
<li><label><input type="radio" name="snapYear" value={String(o.value)} :checked={'selectedYear === "' + String(o.value) + '"'} :class={`{'is-checked': selectedYear === '${String(o.value)}'`} @click.prevent={'selectedYear = selectedYear === "' + String(o.value) + '" ? "" : "' + String(o.value) + '"; loadPage(1)'} /> <span>{o.label}</span></label></li>
|
||||
<li><label><input type="radio" name="snapYear" value={String(o.value)} :checked={'selectedYear === "' + String(o.value) + '"'} :class={`{'is-checked': selectedYear === '${String(o.value)}'`} @click.prevent={'selectedYear = selectedYear === "' + String(o.value) + '" ? "" : "' + String(o.value) + '"; requireLogin() && loadPage(1)'} /> <span>{o.label}</span></label></li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
@ -105,7 +114,7 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
<div class="snapsg-b" x-show="!collapsedGroups.sort">
|
||||
<ul class="snapschecks snapschecks--flat">
|
||||
{sortOptions.map((o) => (
|
||||
<li><label><input type="radio" name="snapSort" value={o.value} :checked={'selectedSort === "' + o.value + '"'} :class={`{'is-checked': selectedSort === '${o.value}'}`} @click.prevent={'selectedSort = selectedSort === "' + o.value + '" ? "image_count" : "' + o.value + '"; loadPage(1)'} /> <span>{o.label}</span></label></li>
|
||||
<li><label><input type="radio" name="snapSort" value={o.value} :checked={'selectedSort === "' + o.value + '"'} :class={`{'is-checked': selectedSort === '${o.value}'}`} @click.prevent={'selectedSort = selectedSort === "' + o.value + '" ? "image_count" : "' + o.value + '"; requireLogin() && loadPage(1)'} /> <span>{o.label}</span></label></li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
@ -122,13 +131,13 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
<div class="snapsg-b" x-show="!collapsedGroups.city">
|
||||
<ul class="snapschecks snapschecks--flat">
|
||||
{cityOptions.map((o) => (
|
||||
<li><label><input type="radio" name="snapCity" value={o.value} :checked={'selectedCity === "' + o.value + '"'} :class={`{'is-checked': selectedCity === '${o.value}'}`} @click.prevent={'selectedCity = selectedCity === "' + o.value + '" ? "" : "' + o.value + '"; loadPage(1)'} /> <span>{o.label}</span></label></li>
|
||||
<li><label><input type="radio" name="snapCity" value={o.value} :checked={'selectedCity === "' + o.value + '"'} :class={`{'is-checked': selectedCity === '${o.value}'}`} @click.prevent={'selectedCity = selectedCity === "' + o.value + '" ? "" : "' + o.value + '"; requireLogin() && loadPage(1)'} /> <span>{o.label}</span></label></li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button class="snapsclear" type="button" @click="clearAll()" x-show="pills.length > 0" x-cloak>Clear all ×</button>
|
||||
<button class="snapsclear" type="button" @click="requireLogin() && clearAll()" x-show="pills.length > 0" x-cloak>Clear all ×</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@ -210,6 +219,33 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
</nav>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- 登录门禁弹窗:未登录点筛选/翻页时弹出内联登录表单 -->
|
||||
<div x-show="showLoginModal" x-cloak class="fixed inset-0 z-[100] flex items-center justify-center bg-black/40" @click.self="closeLoginModal()">
|
||||
<div class="bg-white border border-black/10 shadow-lg w-full max-w-md p-8">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<h3 class="font-serif text-2xl uppercase">{loginModalTitle}</h3>
|
||||
<button type="button" @click="closeLoginModal()" class="text-xs uppercase tracking-widest hover:opacity-60">{loginModalClose}</button>
|
||||
</div>
|
||||
<p class="text-xs text-zinc-500 uppercase tracking-wide mb-6">{loginModalPrompt}</p>
|
||||
<form @submit.prevent="modalLogin()" class="space-y-5">
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{loginModalAccountLabel}</label>
|
||||
<input type="text" x-model="loginModalAccount" required class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{loginModalPasswordLabel}</label>
|
||||
<input type="password" x-model="loginModalPassword" required class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
<p x-show="loginModalError" x-text="loginModalError" class="text-xs text-red-600 uppercase tracking-wide"></p>
|
||||
<button type="submit" :disabled="loginModalLoading" class="w-full border border-black py-3 text-[12px] font-bold uppercase tracking-[0.2em] hover:bg-black hover:text-white transition-colors disabled:opacity-40">
|
||||
<span x-show="!loginModalLoading">{loginModalSubmitLabel}</span>
|
||||
<span x-show="loginModalLoading" x-cloak>…</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script id="snaps-year-opts" type="application/json" set:html={JSON.stringify({ yearOptions, sortOptions, cityOptions })}></script>
|
||||
@ -217,7 +253,7 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
|
||||
|
||||
<script>
|
||||
import { getStreetSnaps, toAbs, type StreetSnapItem } from "@/lib/api"
|
||||
import { getStreetSnaps, toAbs, getUser, login, type StreetSnapItem } from "@/lib/api"
|
||||
import { clientHref, ROUTES } from "@/lib/routes"
|
||||
import { SPIN_SVG, makeCardSlots, buildPageList } from "@/lib/looks-grid"
|
||||
|
||||
@ -247,6 +283,13 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
lastPage: 1,
|
||||
reqToken: 0,
|
||||
|
||||
// 登录门禁弹窗状态(硬门禁:未登录点筛选/翻页时弹出内联登录表单)
|
||||
showLoginModal: false,
|
||||
loginModalAccount: "",
|
||||
loginModalPassword: "",
|
||||
loginModalError: "",
|
||||
loginModalLoading: false,
|
||||
|
||||
init() {
|
||||
this.locale = this.$el.dataset.locale || 'en'
|
||||
// 支持从 header 下拉深链 ?city=xxx 直接进入对应地区(与侧栏 City 筛选一致)
|
||||
@ -267,6 +310,34 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
this.loadPage(1)
|
||||
},
|
||||
|
||||
// ===== 登录门禁 =====
|
||||
// 未登录返回 false 并弹出登录框;已登录返回 true。
|
||||
requireLogin(): boolean {
|
||||
if (getUser()) return true
|
||||
this.showLoginModal = true
|
||||
return false
|
||||
},
|
||||
async modalLogin() {
|
||||
this.loginModalError = ""
|
||||
this.loginModalLoading = true
|
||||
try {
|
||||
await login({ account: this.loginModalAccount, password: this.loginModalPassword })
|
||||
this.showLoginModal = false
|
||||
this.loginModalAccount = ""
|
||||
this.loginModalPassword = ""
|
||||
// 登录成功后按当前筛选刷新,用户无需再次点击
|
||||
this.loadPage(1)
|
||||
} catch {
|
||||
this.loginModalError = this.$el.dataset.loginFail || "login failed"
|
||||
} finally {
|
||||
this.loginModalLoading = false
|
||||
}
|
||||
},
|
||||
closeLoginModal() {
|
||||
this.showLoginModal = false
|
||||
this.loginModalError = ""
|
||||
},
|
||||
|
||||
// 已激活筛选 chips(顶部 pills + 侧栏 Clear all 的可见性都依赖它)
|
||||
get pills() {
|
||||
const out: { label: string; clear: () => void }[] = []
|
||||
@ -331,6 +402,7 @@ const cityOptions: { value: string; label: string }[] = [
|
||||
},
|
||||
|
||||
goPage(p: number) {
|
||||
if (!this.requireLogin()) return
|
||||
if (this.loading) return
|
||||
if (p < 1 || p > this.lastPage || p === this.page) return
|
||||
this.loadPage(p)
|
||||
|
||||
@ -40,6 +40,22 @@ export const dict: Record<string, TranslationEntry> = {
|
||||
|
||||
'signup': { cn: '注册' },
|
||||
|
||||
// ── 账号 / Account ──
|
||||
'hi': { cn: '你好' },
|
||||
'password': { cn: '密码' },
|
||||
'account': { cn: '账户' },
|
||||
'sign out': { cn: '退出登录' },
|
||||
'my account': { cn: '我的账户' },
|
||||
'username or email': { cn: '用户名或邮箱' },
|
||||
'login failed': { cn: '登录失败,请检查账号或密码' },
|
||||
'please log in': { cn: '请先登录' },
|
||||
'login to continue': { cn: '登录以继续使用筛选与翻页' },
|
||||
'login prompt': { cn: '登录后可筛选与翻页浏览全部档案' },
|
||||
'email': { cn: '邮箱' },
|
||||
'my collections': { cn: '我的收藏' },
|
||||
'my history': { cn: '浏览历史' },
|
||||
'coming soon': { cn: '敬请期待' },
|
||||
|
||||
// ── 控件 / Controls ──
|
||||
|
||||
'back to index': { cn: '返回首页' },
|
||||
|
||||
@ -141,10 +141,9 @@ const headers = {
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<!-- <div class="flex items-center gap-2" id="auth-slot" data-hi-label={hiLabel} data-logout-label={logoutLabel}>
|
||||
<a href={href(locale, ROUTES.login)} class="hover:opacity-60 transition-opacity duration-200">{t('Login')}</a>
|
||||
<a href={href(locale, ROUTES.register)} class="hover:opacity-60 transition-opacity duration-200">{t('Signup')}</a>
|
||||
</div> -->
|
||||
<div class="flex items-center gap-3" id="auth-slot" data-hi-label={hiLabel} data-logout-label={logoutLabel}>
|
||||
<a href={href(locale, ROUTES.login)} class="hover:opacity-60 transition-opacity duration-200 uppercase tracking-[0.5px] text-[13px]">{t('Login')}</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@ -154,7 +153,7 @@ const headers = {
|
||||
|
||||
<footer class="relative z-[1] bg-white mt-20 pt-10 border-t-2 border-black text-black w-full font-sans">
|
||||
<script>
|
||||
import { getUser, fetchMe, clearSession } from "@/lib/api"
|
||||
import { getUser, fetchMe, logout } from "@/lib/api"
|
||||
const slot = document.getElementById("auth-slot")
|
||||
const hiLabel = slot?.dataset.hiLabel ?? "Hi"
|
||||
const logoutLabel = slot?.dataset.logoutLabel ?? "Logout"
|
||||
@ -162,7 +161,7 @@ const headers = {
|
||||
if (!user) return // 未登录:保留 SSR 渲染的 Login/Signup(已带语言前缀,无需重写)
|
||||
slot.innerHTML = `<span class="opacity-70">${hiLabel}, ${user.username}</span><button id="logout-btn" class="hover:opacity-60 transition-opacity cursor-pointer bg-transparent border-0 p-0 font-bold text-[13px] uppercase tracking-[0.5px]">${logoutLabel}</button>`
|
||||
const btn = slot.querySelector("#logout-btn")
|
||||
if (btn) btn.addEventListener("click", () => { clearSession(); location.reload() })
|
||||
if (btn) btn.addEventListener("click", () => { logout().finally(() => location.reload()) })
|
||||
}
|
||||
const cached = getUser()
|
||||
if (cached) render(cached)
|
||||
|
||||
131
src/lib/api.ts
131
src/lib/api.ts
@ -284,11 +284,12 @@ export async function getBrands(opts?: {
|
||||
}
|
||||
|
||||
// ===================== 账号体系(/api/auth/*) =====================
|
||||
// 说明:当前前端只用「取当前用户 + 登出」两个能力(顶栏已登录态)。
|
||||
// 登录/注册的表单提交暂未接入,相关接口函数已移除,避免无人调用的死代码。
|
||||
// 双令牌:access_token(短命,请求鉴权)+ refresh_token(长命,落库可吊销)。
|
||||
// 登录写两者;fetchMe 等受保护请求遇 401 自动用 refresh 续期一次;登出吊销 refresh。
|
||||
|
||||
const BASE_API_URL = (BASE_API || "").replace(/\/$/, "")
|
||||
const TOKEN_KEY = "fa_token"
|
||||
const TOKEN_KEY = "fa_token" // access token
|
||||
const REFRESH_KEY = "fa_refresh" // refresh token
|
||||
const USER_KEY = "fa_user"
|
||||
|
||||
// 注意:getUser / clearSession 只读写 localStorage,不发网络请求。
|
||||
@ -302,21 +303,77 @@ export function getUser(): AuthUser | null {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAccessToken(): string | null {
|
||||
if (typeof localStorage === "undefined") return null
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
if (typeof localStorage === "undefined") return null
|
||||
return localStorage.getItem(REFRESH_KEY)
|
||||
}
|
||||
|
||||
export function clearSession(): void {
|
||||
if (typeof localStorage === "undefined") return
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(REFRESH_KEY)
|
||||
localStorage.removeItem(USER_KEY)
|
||||
}
|
||||
|
||||
// 写登录态:登录成功后把 access + refresh + user 写入 localStorage。
|
||||
export function saveSession(access: string, refresh: string, user: AuthUser): void {
|
||||
if (typeof localStorage === "undefined") return
|
||||
localStorage.setItem(TOKEN_KEY, access)
|
||||
localStorage.setItem(REFRESH_KEY, refresh)
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
}
|
||||
|
||||
// 刷新 token:用 refresh_token 换新的 access_token(refresh 复用、不轮换)。
|
||||
export async function refreshSession(): Promise<string> {
|
||||
const refresh = getRefreshToken()
|
||||
if (!refresh) throw new Error("no refresh token")
|
||||
const res = await fetch(`${BASE_API_URL}/api/v1/auth/refresh`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token: refresh }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
clearSession()
|
||||
throw new Error("refresh failed")
|
||||
}
|
||||
const json: any = await res.json()
|
||||
const access: string | undefined = json?.access_token
|
||||
if (!access) throw new Error("refresh failed")
|
||||
// refresh 复用:仅更新 access,保留原 refresh。
|
||||
const user = getUser()
|
||||
if (user) saveSession(access, refresh, user)
|
||||
return access
|
||||
}
|
||||
|
||||
// 带鉴权的请求:自动附带 Bearer,遇 401 静默刷新一次后重试。
|
||||
async function authedFetch(url: string, opts: RequestInit = {}): Promise<Response> {
|
||||
const headers = new Headers(opts.headers)
|
||||
const token = getAccessToken()
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`)
|
||||
let res = await fetch(url, { ...opts, headers })
|
||||
if (res.status === 401 && getRefreshToken()) {
|
||||
try {
|
||||
await refreshSession()
|
||||
const newToken = getAccessToken()
|
||||
if (newToken) headers.set("Authorization", `Bearer ${newToken}`)
|
||||
res = await fetch(url, { ...opts, headers })
|
||||
} catch {
|
||||
/* 刷新失败:返回原始 401,由调用方处理 */
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
export async function fetchMe(): Promise<AuthUser | null> {
|
||||
if (typeof localStorage === "undefined") return null
|
||||
const token = localStorage.getItem(TOKEN_KEY)
|
||||
if (!token) return null
|
||||
if (!getAccessToken()) return null
|
||||
try {
|
||||
// 接口:GET /api/auth/me(需 Bearer token,客户端运行期 base 走 BASE_API)
|
||||
const res = await fetch(`${BASE_API_URL}/api/v1/auth/me?locale=${encodeURIComponent(currentLocale())}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
const res = await authedFetch(`${BASE_API_URL}/api/v1/auth/me?locale=${encodeURIComponent(currentLocale())}`)
|
||||
if (!res.ok) {
|
||||
clearSession()
|
||||
return null
|
||||
@ -329,9 +386,59 @@ export async function fetchMe(): Promise<AuthUser | null> {
|
||||
}
|
||||
}
|
||||
|
||||
// 注:saveSession(登录/注册成功后写 token+user 进 localStorage)已移除——
|
||||
// 站点没有登录注册入口,后端 POST /auth/register、POST /auth/login 也已下线。
|
||||
// 将来接入时恢复此函数,并补回后端注册/登录接口与前端表单。
|
||||
// 登录:POST /api/v1/auth/login(公开端点)。成功后写 access+refresh+user 进 localStorage。
|
||||
export async function login(input: { account: string; password: string }): Promise<AuthUser> {
|
||||
const res = await fetch(`${BASE_API_URL}/api/v1/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
if (!res.ok) {
|
||||
clearSession()
|
||||
throw new Error("login failed")
|
||||
}
|
||||
const json: any = await res.json()
|
||||
const access: string | undefined = json?.access_token
|
||||
const refresh: string | undefined = json?.refresh_token
|
||||
const user: any = json?.user
|
||||
if (!access || !refresh || !user) throw new Error("login failed")
|
||||
saveSession(access, refresh, user)
|
||||
return user as AuthUser
|
||||
}
|
||||
|
||||
// 登出:吊销当前 refresh_token,再清本地态。
|
||||
export async function logout(): Promise<void> {
|
||||
const refresh = getRefreshToken()
|
||||
if (refresh) {
|
||||
try {
|
||||
await fetch(`${BASE_API_URL}/api/v1/auth/logout`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token: refresh }),
|
||||
})
|
||||
} catch {
|
||||
/* 忽略网络错误,仍清本地态 */
|
||||
}
|
||||
}
|
||||
clearSession()
|
||||
}
|
||||
|
||||
// 踢下线:吊销当前用户所有 refresh_token(全设备退出)。
|
||||
export async function logoutAll(): Promise<void> {
|
||||
const refresh = getRefreshToken()
|
||||
if (refresh) {
|
||||
try {
|
||||
await fetch(`${BASE_API_URL}/api/v1/auth/logout-all`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token: refresh }),
|
||||
})
|
||||
} catch {
|
||||
/* 忽略网络错误,仍清本地态 */
|
||||
}
|
||||
}
|
||||
clearSession()
|
||||
}
|
||||
|
||||
// ===================== SSG 构建专用(/api/ssg/*,仅 Node 构建期) =====================
|
||||
|
||||
|
||||
@ -13,6 +13,7 @@ export const ROUTES = {
|
||||
portfolio: '/portfolio',
|
||||
login: '/login',
|
||||
register: '/register',
|
||||
account: '/account',
|
||||
runwayLooks: '/runway-looks',
|
||||
// 街拍
|
||||
streetSnaps: '/street-snaps',
|
||||
|
||||
74
src/pages/cn/account.astro
Normal file
74
src/pages/cn/account.astro
Normal file
@ -0,0 +1,74 @@
|
||||
---
|
||||
import Layout from '@/layouts/Layout.astro'
|
||||
import { getI18n } from '@/i18n/utils'
|
||||
import { href, ROUTES } from '@/lib/routes'
|
||||
const { locale, t } = getI18n(Astro)
|
||||
const titleLabel = t('my account')
|
||||
const pleaseLabel = t('please log in')
|
||||
const loginLabel = t('login')
|
||||
const accountLabel = t('account')
|
||||
const emailLabel = t('email')
|
||||
const signOutLabel = t('sign out')
|
||||
const collectionsLabel = t('my collections')
|
||||
const historyLabel = t('my history')
|
||||
const soonLabel = t('coming soon')
|
||||
---
|
||||
<Layout title={titleLabel}>
|
||||
<section class="mx-auto w-full max-w-2xl px-6 py-24" x-data="accountPage()" data-locale={locale}>
|
||||
<h1 class="font-serif text-4xl uppercase mb-2">{titleLabel}</h1>
|
||||
|
||||
<div x-show="!user" x-cloak class="mt-10 space-y-4">
|
||||
<p class="text-sm text-zinc-500">{pleaseLabel}</p>
|
||||
<a href={href(locale, ROUTES.login) + '?redirect=' + encodeURIComponent(href(locale, ROUTES.account))}
|
||||
class="inline-block border border-black px-6 py-3 text-[12px] font-bold uppercase tracking-[0.2em] transition-colors hover:bg-black hover:text-white">{loginLabel}</a>
|
||||
</div>
|
||||
|
||||
<div x-show="user" x-cloak class="mt-10">
|
||||
<dl class="space-y-4 text-sm">
|
||||
<div class="flex gap-4 border-b border-zinc-100 pb-3">
|
||||
<dt class="w-32 text-[11px] font-mono uppercase tracking-widest text-zinc-400 pt-1">{accountLabel}</dt>
|
||||
<dd class="font-medium" x-text="user?.username"></dd>
|
||||
</div>
|
||||
<div class="flex gap-4 border-b border-zinc-100 pb-3">
|
||||
<dt class="w-32 text-[11px] font-mono uppercase tracking-widest text-zinc-400 pt-1">{emailLabel}</dt>
|
||||
<dd class="font-medium" x-text="user?.email"></dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<button @click="logout()" class="mt-8 border border-black px-6 py-3 text-[12px] font-bold uppercase tracking-[0.2em] transition-colors hover:bg-black hover:text-white">{signOutLabel}</button>
|
||||
|
||||
<div class="mt-16 space-y-10">
|
||||
<section>
|
||||
<h2 class="font-serif text-2xl uppercase mb-3">{collectionsLabel}</h2>
|
||||
<p class="text-sm text-zinc-400">{soonLabel}</p>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="font-serif text-2xl uppercase mb-3">{historyLabel}</h2>
|
||||
<p class="text-sm text-zinc-400">{soonLabel}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { getUser, logout as logoutApi } from "@/lib/api"
|
||||
import { clientHref, ROUTES } from "@/lib/routes"
|
||||
document.addEventListener("alpine:init", () => {
|
||||
Alpine.data("accountPage", () => ({
|
||||
user: null,
|
||||
init() {
|
||||
const loc = this.$el.dataset.locale || "en"
|
||||
const u = getUser()
|
||||
if (!u) {
|
||||
window.location.href = clientHref(loc, ROUTES.login) + "?redirect=" + encodeURIComponent(clientHref(loc, ROUTES.account))
|
||||
return
|
||||
}
|
||||
this.user = u
|
||||
},
|
||||
logout() {
|
||||
logoutApi().finally(() => window.location.reload())
|
||||
}
|
||||
}))
|
||||
})
|
||||
</script>
|
||||
69
src/pages/cn/login.astro
Normal file
69
src/pages/cn/login.astro
Normal file
@ -0,0 +1,69 @@
|
||||
---
|
||||
import Layout from '@/layouts/Layout.astro'
|
||||
import { getI18n } from '@/i18n/utils'
|
||||
const { locale, t } = getI18n(Astro)
|
||||
const loginLabel = t('login')
|
||||
const promptLabel = t('login prompt')
|
||||
const accountLabel = t('username or email')
|
||||
const passwordLabel = t('password')
|
||||
const failLabel = t('login failed')
|
||||
---
|
||||
<Layout title={loginLabel}>
|
||||
<section class="mx-auto w-full max-w-md px-6 py-24">
|
||||
<h1 class="font-serif text-4xl tracking-tight uppercase mb-2">{loginLabel}</h1>
|
||||
<p class="text-[11px] font-mono uppercase tracking-widest text-zinc-400 mb-10">{promptLabel}</p>
|
||||
|
||||
<form x-data="loginForm()" data-locale={locale} data-fail-label={failLabel} @submit.prevent="submit()" class="space-y-8" novalidate>
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{accountLabel}</label>
|
||||
<input type="text" x-model="account" autocomplete="username" required
|
||||
class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{passwordLabel}</label>
|
||||
<input type="password" x-model="password" autocomplete="current-password" required
|
||||
class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
|
||||
<p x-show="error" x-text="error" x-cloak class="text-xs text-red-600 uppercase tracking-wide"></p>
|
||||
|
||||
<button type="submit" :disabled="loading"
|
||||
class="w-full border border-black py-3 text-[12px] font-bold uppercase tracking-[0.2em] transition-colors hover:bg-black hover:text-white disabled:opacity-40">
|
||||
<span x-show="!loading">{loginLabel}</span>
|
||||
<span x-show="loading" x-cloak>…</span>
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { login, getUser } from "@/lib/api"
|
||||
import { clientHref, ROUTES } from "@/lib/routes"
|
||||
document.addEventListener("alpine:init", () => {
|
||||
Alpine.data("loginForm", () => ({
|
||||
account: "",
|
||||
password: "",
|
||||
error: "",
|
||||
loading: false,
|
||||
init() {
|
||||
if (getUser()) {
|
||||
const loc = this.$el.dataset.locale || "en"
|
||||
window.location.href = clientHref(loc, ROUTES.account)
|
||||
}
|
||||
},
|
||||
submit() {
|
||||
this.error = ""
|
||||
this.loading = true
|
||||
login({ account: this.account, password: this.password })
|
||||
.then(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const redirect = params.get("redirect")
|
||||
const loc = this.$el.dataset.locale || "en"
|
||||
window.location.href = redirect || clientHref(loc, ROUTES.account)
|
||||
})
|
||||
.catch(() => { this.error = this.$el.dataset.failLabel || "login failed" })
|
||||
.finally(() => { this.loading = false })
|
||||
}
|
||||
}))
|
||||
})
|
||||
</script>
|
||||
74
src/pages/en/account.astro
Normal file
74
src/pages/en/account.astro
Normal file
@ -0,0 +1,74 @@
|
||||
---
|
||||
import Layout from '@/layouts/Layout.astro'
|
||||
import { getI18n } from '@/i18n/utils'
|
||||
import { href, ROUTES } from '@/lib/routes'
|
||||
const { locale, t } = getI18n(Astro)
|
||||
const titleLabel = t('my account')
|
||||
const pleaseLabel = t('please log in')
|
||||
const loginLabel = t('login')
|
||||
const accountLabel = t('account')
|
||||
const emailLabel = t('email')
|
||||
const signOutLabel = t('sign out')
|
||||
const collectionsLabel = t('my collections')
|
||||
const historyLabel = t('my history')
|
||||
const soonLabel = t('coming soon')
|
||||
---
|
||||
<Layout title={titleLabel}>
|
||||
<section class="mx-auto w-full max-w-2xl px-6 py-24" x-data="accountPage()" data-locale={locale}>
|
||||
<h1 class="font-serif text-4xl uppercase mb-2">{titleLabel}</h1>
|
||||
|
||||
<div x-show="!user" x-cloak class="mt-10 space-y-4">
|
||||
<p class="text-sm text-zinc-500">{pleaseLabel}</p>
|
||||
<a href={href(locale, ROUTES.login) + '?redirect=' + encodeURIComponent(href(locale, ROUTES.account))}
|
||||
class="inline-block border border-black px-6 py-3 text-[12px] font-bold uppercase tracking-[0.2em] transition-colors hover:bg-black hover:text-white">{loginLabel}</a>
|
||||
</div>
|
||||
|
||||
<div x-show="user" x-cloak class="mt-10">
|
||||
<dl class="space-y-4 text-sm">
|
||||
<div class="flex gap-4 border-b border-zinc-100 pb-3">
|
||||
<dt class="w-32 text-[11px] font-mono uppercase tracking-widest text-zinc-400 pt-1">{accountLabel}</dt>
|
||||
<dd class="font-medium" x-text="user?.username"></dd>
|
||||
</div>
|
||||
<div class="flex gap-4 border-b border-zinc-100 pb-3">
|
||||
<dt class="w-32 text-[11px] font-mono uppercase tracking-widest text-zinc-400 pt-1">{emailLabel}</dt>
|
||||
<dd class="font-medium" x-text="user?.email"></dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<button @click="logout()" class="mt-8 border border-black px-6 py-3 text-[12px] font-bold uppercase tracking-[0.2em] transition-colors hover:bg-black hover:text-white">{signOutLabel}</button>
|
||||
|
||||
<div class="mt-16 space-y-10">
|
||||
<section>
|
||||
<h2 class="font-serif text-2xl uppercase mb-3">{collectionsLabel}</h2>
|
||||
<p class="text-sm text-zinc-400">{soonLabel}</p>
|
||||
</section>
|
||||
<section>
|
||||
<h2 class="font-serif text-2xl uppercase mb-3">{historyLabel}</h2>
|
||||
<p class="text-sm text-zinc-400">{soonLabel}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { getUser, logout as logoutApi } from "@/lib/api"
|
||||
import { clientHref, ROUTES } from "@/lib/routes"
|
||||
document.addEventListener("alpine:init", () => {
|
||||
Alpine.data("accountPage", () => ({
|
||||
user: null,
|
||||
init() {
|
||||
const loc = this.$el.dataset.locale || "en"
|
||||
const u = getUser()
|
||||
if (!u) {
|
||||
window.location.href = clientHref(loc, ROUTES.login) + "?redirect=" + encodeURIComponent(clientHref(loc, ROUTES.account))
|
||||
return
|
||||
}
|
||||
this.user = u
|
||||
},
|
||||
logout() {
|
||||
logoutApi().finally(() => window.location.reload())
|
||||
}
|
||||
}))
|
||||
})
|
||||
</script>
|
||||
69
src/pages/en/login.astro
Normal file
69
src/pages/en/login.astro
Normal file
@ -0,0 +1,69 @@
|
||||
---
|
||||
import Layout from '@/layouts/Layout.astro'
|
||||
import { getI18n } from '@/i18n/utils'
|
||||
const { locale, t } = getI18n(Astro)
|
||||
const loginLabel = t('login')
|
||||
const promptLabel = t('login prompt')
|
||||
const accountLabel = t('username or email')
|
||||
const passwordLabel = t('password')
|
||||
const failLabel = t('login failed')
|
||||
---
|
||||
<Layout title={loginLabel}>
|
||||
<section class="mx-auto w-full max-w-md px-6 py-24">
|
||||
<h1 class="font-serif text-4xl tracking-tight uppercase mb-2">{loginLabel}</h1>
|
||||
<p class="text-[11px] font-mono uppercase tracking-widest text-zinc-400 mb-10">{promptLabel}</p>
|
||||
|
||||
<form x-data="loginForm()" data-locale={locale} data-fail-label={failLabel} @submit.prevent="submit()" class="space-y-8" novalidate>
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{accountLabel}</label>
|
||||
<input type="text" x-model="account" autocomplete="username" required
|
||||
class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-mono uppercase tracking-widest text-zinc-500 mb-2">{passwordLabel}</label>
|
||||
<input type="password" x-model="password" autocomplete="current-password" required
|
||||
class="w-full bg-transparent border-0 border-b border-black/30 rounded-none px-0 py-2 text-sm outline-none focus:border-black focus:ring-0" />
|
||||
</div>
|
||||
|
||||
<p x-show="error" x-text="error" x-cloak class="text-xs text-red-600 uppercase tracking-wide"></p>
|
||||
|
||||
<button type="submit" :disabled="loading"
|
||||
class="w-full border border-black py-3 text-[12px] font-bold uppercase tracking-[0.2em] transition-colors hover:bg-black hover:text-white disabled:opacity-40">
|
||||
<span x-show="!loading">{loginLabel}</span>
|
||||
<span x-show="loading" x-cloak>…</span>
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { login, getUser } from "@/lib/api"
|
||||
import { clientHref, ROUTES } from "@/lib/routes"
|
||||
document.addEventListener("alpine:init", () => {
|
||||
Alpine.data("loginForm", () => ({
|
||||
account: "",
|
||||
password: "",
|
||||
error: "",
|
||||
loading: false,
|
||||
init() {
|
||||
if (getUser()) {
|
||||
const loc = this.$el.dataset.locale || "en"
|
||||
window.location.href = clientHref(loc, ROUTES.account)
|
||||
}
|
||||
},
|
||||
submit() {
|
||||
this.error = ""
|
||||
this.loading = true
|
||||
login({ account: this.account, password: this.password })
|
||||
.then(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const redirect = params.get("redirect")
|
||||
const loc = this.$el.dataset.locale || "en"
|
||||
window.location.href = redirect || clientHref(loc, ROUTES.account)
|
||||
})
|
||||
.catch(() => { this.error = this.$el.dataset.failLabel || "login failed" })
|
||||
.finally(() => { this.loading = false })
|
||||
}
|
||||
}))
|
||||
})
|
||||
</script>
|
||||
Reference in New Issue
Block a user