update
Some checks failed
deploy / deploy (push) Has been cancelled

This commit is contained in:
toom1996
2026-08-31 19:59:36 +08:00
parent 0d13748d7e
commit 97b023bbbd
13 changed files with 654 additions and 51 deletions

View File

@ -0,0 +1,29 @@
# 2026-08-31 工作日志
## 账号体系:登录/注册/个人中心/硬门禁(全链路落地)
- 用户决策:①视觉沿用站点黑白极简编辑风;②硬门禁(未登录一碰筛选/翻页弹登录框);③仅预置内部账号,不开放注册。
- 现状诊断:此前登录注册是半成品——前端 Login/Signup 链接与 `#auth-slot` 被注释、无 login/register 页面、api.ts 删了 `saveSession`;后端 `/auth/register|/login` 已下线、JWT 签发器被注释、`users` 表从未创建。
- 后端:恢复 `jwt.Manager.Generate`;`user_repository` 加 `FindByAccount`(username|email,忽略 is_deleted);`auth_service` 加 `Login`(bcrypt 校验→签发);`auth_handler` 加 `Login`;路由挂 `POST /api/v1/auth/login`(公开)。`go build ./internal/...` 通过;seed 建 users 表 + 预置 admin,实测登录返回 token(180) 成功(LOGIN_OK)。
- 前端:api.ts 恢复 `saveSession` + 新增 `login()`;routes 加 `account`;dictionary 加登录/账户文案;`Layout` 接回 `#auth-slot`(仅 Login 链接,去 Signup,footer 已登录显示 Hi+Logout);新建 `login.astro` / `account.astro`(en/cn,黑白极简,Alpine 表单);RunwayLooks/StreetSnaps 加 `requireLogin` 拦截 + 内嵌登录弹窗,首屏 init 不拦。
- 验证:`npm run build` EXIT=0;后端 login 实测 LOGIN_OK;seed 创建 admin / admin@studio.local。
- 默认账号 admin / Studio#2026!Admin(env `SEED_ADMIN_PASSWORD` 可改,务必改默认密码)。
## 收尾验证(17:40 续)
- 启动 Astro dev server(npx astro dev --background,http://localhost:4321),预览 /en/login 渲染正常。
- 复查 account.astro:未登录重定向走 Alpine `init()` 客户端 `getUser()`(非服务端),无"服务端读不到 localStorage 导致永远重定向"的坑。
- i18n 键核对齐全(login prompt / please log in / sign out / my collections / my history / coming soon 等均在 dictionary.ts)。
- 后端现状::8090 已有实例在跑(端口被占,新 go run 起不来属预期)。实测登录 POST /api/v1/auth/login(account=admin)→ STATUS=200 返回合法 JWT + user{id:7,username:admin,email:admin@studio.local}。此前 curl 报 400 是 PowerShell 把密码里 `#`/`!` 吞掉所致,非代码问题。
- 结论:登录/门禁全链路验证通过(构建过、页面渲染、API 200 签 token、BASE_API=localhost:8090 已就位)。硬门禁 UX 行为按 requireLogin 代码逻辑确认,未做浏览器点击自动化。
## JWT 双令牌 + 踢下线(19:35 续)
- 用户问"JWT 怎么做刷新 token、能不能踢下线"→ 落地双令牌方案:access 2h(无状态)+ refresh 30d(落库 refresh_tokens,SHA256 存哈希)。
- 后端:`config.JWT` 加 `RefreshExpireHours`;`AuthService` 加 `Refresh/Logout/RevokeAllByRefresh`;新增 `RefreshTokenRepository` + `model.RefreshToken`;`dto.LoginResponse` 改 `{access_token,refresh_token,expires_in,user}`;handler 加 `Refresh/Logout/LogoutAll`;router 挂 `/auth/refresh|/logout|/logout-all`;`main` 装配 `refreshRepo`。建表 `scripts/sql/006_create_refresh_tokens.sql` + 迁移脚本 `scripts/migrate_refresh/main.go`(go run 建表成功)。
- 前端 `api.ts`:saveSession 存 fa_token/fa_refresh/fa_user;新增 refreshSession、authedFetch(fetchMe 遇 401 静默刷新)、logout(吊销+清态)、logoutAll(踢下线+清态);Layout/account 登出改调 logout()。组件 login() 调用兼容(仅 await 成功)。
- 验证:`go build -o bin/server.exe ./cmd/server` EXIT=0;杀旧 8090 进程、起新后端;Node 端到端脚本 ALL_OK:login(200,expires_in=7200) → refresh(200) → logout-all(revoked:1) → 再 refresh=401。前端 `npm run build` EXIT=0。
- 说明:refresh 复用不轮换;"普通踢"=吊销 refresh,已签发 access 2h 内仍有效(非即时);即时吊销需另加 token_version,未做。默认账号仍为 admin/Studio#2026!Admin。
## 登录互斥(同账号单会话,19:59 续)
- 用户澄清动机:做踢下线是因为"不希望同一账号被不同的人同时登录"。原 `Login` 只新发 refresh、不吊销旧的,导致同账号可并存多条会话,与诉求相反。
- 改动 `auth_service.Login`:签发前先 `RevokeAllByUser(userID)` 吊销该用户全部既有 refresh,仅保留本次新签发的这一条 → 同账号同一时刻只有一条活性会话。
- 重建 `bin/server.exe` EXIT=0;重启 :8090(杀旧进程 PID 7368 → 起新 PID 1776)。Node 互斥测试 MUTEX_OK:同账号二次 login 后,首次 refresh=401(被顶掉)、二次 refresh=200(有效)。
- 残留边界:redis/access 为无状态 JWT(2h),被顶掉的旧会话其已签发的 access 在 2h 内仍有效,到期后才被弹回登录;要访问令牌即时失效需 token_version 方案(未做)。logout-all 手动端点保留(可用于"登出其他设备"按钮/管理员强踢)。

View File

@ -46,5 +46,24 @@
- **详情页统一 `/item`**:走秀 lookbook 与街拍详情全部收口到 `src/pages/{locale}/item/[id].astro`,服务端按 `getSsrArticle(id)` → `getSsrStreetSnap(id)` 回落渲染(先 runway 后 street)。`ROUTES.article` 与 `ROUTES.streetSnap` 均指向 `/item/${id}`(`runway-looks/[id]`、`street-snaps/[id]`、`article.astro(?id=)` 等旧详情页均已删除)。列表页回链仍指向列表 `/runway-looks`、`/street-snaps`。 - **详情页统一 `/item`**:走秀 lookbook 与街拍详情全部收口到 `src/pages/{locale}/item/[id].astro`,服务端按 `getSsrArticle(id)` → `getSsrStreetSnap(id)` 回落渲染(先 runway 后 street)。`ROUTES.article` 与 `ROUTES.streetSnap` 均指向 `/item/${id}`(`runway-looks/[id]`、`street-snaps/[id]`、`article.astro(?id=)` 等旧详情页均已删除)。列表页回链仍指向列表 `/runway-looks`、`/street-snaps`。
- **列表页共享资源**:两个列表组件(RunwayLooks / StreetSnaps)同构,抽成 `src/styles/look-grid.css`(卡片/网格/分页/侧栏/spinner/骨架/动画)+ `src/lib/looks-grid.ts`(`SPIN_SVG`、`makeCardSlots(images,count,opts)`、`buildPageList(total,cur)`);品牌筛选弹窗 `src/components/BrandModal.astro`(仅 RunwayLooks 用,`openBrandModal/confirmBrandModal` 等由页面脚本驱动)。卡片标记因在 Alpine `x-for` 内客户端渲染,**不能**提成 Astro 组件。 - **列表页共享资源**:两个列表组件(RunwayLooks / StreetSnaps)同构,抽成 `src/styles/look-grid.css`(卡片/网格/分页/侧栏/spinner/骨架/动画)+ `src/lib/looks-grid.ts`(`SPIN_SVG`、`makeCardSlots(images,count,opts)`、`buildPageList(total,cur)`);品牌筛选弹窗 `src/components/BrandModal.astro`(仅 RunwayLooks 用,`openBrandModal/confirmBrandModal` 等由页面脚本驱动)。卡片标记因在 Alpine `x-for` 内客户端渲染,**不能**提成 Astro 组件。
## 账号体系(2026-08-31)
- 决策:仅预置内部账号,**不开放注册**(前端无注册入口,避免垃圾账号/撞库)。账号由 seed 脚本预置。
- 默认内部账号:`admin` / `admin@studio.local` / 密码 `Studio#2026!Admin`(env `SEED_ADMIN_PASSWORD` 可覆盖;**务必改默认密码**)。
- **双令牌 JWT(2026-08-31 落地)**:access token 短命(默认 **2h**,无状态 JWT,仅前端请求用)+ refresh token 长命(默认 **30d**,随机串只存 SHA256 哈希落库 `refresh_tokens`)。纯无状态 JWT 无法吊销,故 refresh 必须落库才能做踢下线。
- 接口(均在 `/api/v1/auth/`,除 /me 外均公开、无需 Bearer):
- `POST /login` → `{access_token, refresh_token, expires_in(秒), user}`(login 返回结构已从 `{token,user}` 改为双 token,前端已同步)。**登录即顶旧会话**:签发前先吊销该用户全部既有 refresh,保证同账号同一时刻只有一条活性会话(用户明确诉求:不希望同一账号被不同人同时登录)。
- `POST /refresh` → `{access_token, expires_in}`(用 refresh_token 换 access;**refresh 复用、不轮换**)。
- `POST /logout` → `{ok:true}`(吊销当前 refresh,单设备登出)。
- `POST /logout-all` → `{revoked:N}`(按 refresh 反查用户,吊销其全部 refresh = **踢下线/全设备登出**)。
- `GET /me`(Bearer 校验)保留。
- 后端改动:`config.JWT` 新增 `RefreshExpireHours`(env `JWT_REFRESH_EXPIRE_HOURS`);`AuthService` 加 `Refresh/Logout/RevokeAllByRefresh`;`RefreshTokenRepository`(Create/FindByHash/Revoke/RevokeAllByUser/DeleteExpired);`model.RefreshToken`(gorm 表 `refresh_tokens`)。
- 建表:`scripts/sql/006_create_refresh_tokens.sql`;一键建表脚本 `scripts/migrate_refresh/main.go`(`go run ./scripts/migrate_refresh`,DSN 默认 root:root@127.0.0.1:3306/db_dev,可由 `DB_DSN` 覆盖)。
- 前端 `api.ts`(2026-08-31 改):`saveSession(access,refresh,user)` 存 `fa_token`/`fa_refresh`/`fa_user`;新增 `refreshSession()`(POST /auth/refresh,刷新 access、复用 refresh);`fetchMe()` 走 `authedFetch`(遇 401 静默 refresh 一次再重试);`logout()`(吊销当前 refresh 再清本地)、`logoutAll()`(踢下线再清本地)。`clearSession()` 一并清三键。
- 踢下线效果:**普通踢**=吊销 refresh,已签发 access 在 2h 窗口内仍有效,到期后才被弹回登录(非即时,内部工具足够);未做 `token_version` 即时吊销方案(如需访问令牌即时失效再加 `users.token_version` 并在 `middleware.Auth` 比对)。
- 验证(2026-08-31):`go build -o bin/server.exe ./cmd/server` EXIT=0;端到端 Node 脚本确认 login→refresh→logout-all(revoked:1)→再 refresh=401(ALL_OK);同账号二次 login 后首次 refresh 返回 401、二次 refresh 返回 200(MUTEX_OK,互斥登录生效)。前端 `npm run build` EXIT=0。
- **硬门禁(用户拍板)**:RunwayLooks / StreetSnaps 的筛选与翻页入口调 `requireLogin()`,未登录则弹出内嵌登录表单(`showLoginModal`);登录成功后 `loadPage(1)` 按当前筛选刷新。首屏 `init()` 的 `loadPage(1)` 不拦(保证未登录能看到第一页)。
- 页面:`src/pages/{en,cn}/login.astro`(黑白极简风,Alpine 表单,登录后跳 `?redirect=` 或 /account)、`account.astro`(资料+登出+收藏/历史占位,未登录跳 /login?redirect=/account)。
- 视觉:登录/个人中心沿用站点黑白极简编辑风(monospace + 细线下划线输入框 + Georgia 衬线大标题 + hover:opacity-60)。
## 部署(Docker + Gitea Actions) ## 部署(Docker + Gitea Actions)
- 交付文件:前端 Dockerfile / nginx.conf / docker-compose.yml / deploy.sh / .gitea/workflows/deploy.yml / .env.example / DEPLOY.md;后端 Dockerfile。nginx 拦截 `/api/v1/ssg/` 404;健康检查 `/api/v1/public/brands`。 - 交付文件:前端 Dockerfile / nginx.conf / docker-compose.yml / deploy.sh / .gitea/workflows/deploy.yml / .env.example / DEPLOY.md;后端 Dockerfile。nginx 拦截 `/api/v1/ssg/` 404;健康检查 `/api/v1/public/brands`。

View File

@ -9,30 +9,34 @@
> test@0.0.1 build > test@0.0.1 build
> astro build > astro build
19:01:18 [@astrojs/node] Enabling sessions with filesystem storage 17:37:35 [@astrojs/node] Enabling sessions with filesystem storage
19:01:18 [types] Generated 92ms 17:37:35 [types] Generated 106ms
19:01:18 [build] output: "static" 17:37:35 [build] output: "static"
19:01:18 [build] mode: "server" 17:37:35 [build] mode: "server"
19:01:18 [build] directory: D:\project\frontend_v2\dist\ 17:37:35 [build] directory: D:\project\frontend_v2\dist\
19:01:18 [build] adapter: @astrojs/node 17:37:35 [build] adapter: @astrojs/node
19:01:18 [build] Collecting build info... 17:37:35 [build] Collecting build info...
19:01:18 [build] ✓ Completed in 191ms. 17:37:35 [build] ✓ Completed in 207ms.
19:01:18 [build] Building server entrypoints... 17:37:35 [build] Building server entrypoints...
19:01:19 [vite] ✓ built in 802ms 17:37:37 [vite] ✓ built in 1.65s
19:01:19 [vite] ✓ built in 392ms 17:37:38 [vite] ✓ built in 865ms
19:01:20 [vite] ✓ built in 282ms 17:37:39 [vite] ✓ built in 676ms
 prerendering static routes   prerendering static routes 
19:01:20 ├─ /cn/runway-looks/index.html (+48ms) 17:37:39 ├─ /cn/account/index.html (+67ms)
19:01:20 ├─ /cn/street-snaps/index.html (+9ms) 17:37:39 ├─ /cn/login/index.html (+16ms)
19:01:20 ├─ /cn/index.html (+35ms) 17:37:39 ├─ /cn/runway-looks/index.html (+344ms)
19:01:20 ├─ /en/runway-looks/index.html (+15ms) 17:37:39 ├─ /cn/street-snaps/index.html (+22ms)
19:01:20 ├─ /en/street-snaps/index.html (+7ms) 17:37:39 ├─ /cn/index.html (+75ms)
19:01:20 ├─ /en/index.html (+24ms) 17:37:39 ├─ /en/account/index.html (+18ms)
19:01:20 ├─ /index.html (+20ms) 17:37:39 ├─ /en/login/index.html (+12ms)
19:01:20 ✓ Completed in 183ms. 17:37:39 ├─ /en/runway-looks/index.html (+23ms)
17:37:39 ├─ /en/street-snaps/index.html (+19ms)
17:37:39 ├─ /en/index.html (+47ms)
17:37:39 ├─ /index.html (+41ms)
17:37:39 ✓ Completed in 746ms.
 
19:01:20 [build] Rearranging server assets... 17:37:39 [build] Rearranging server assets...
19:01:20 [build] ✓ Completed in 1.78s. 17:37:39 [build] ✓ Completed in 4.10s.
19:01:20 [build] Server built in 1.98s 17:37:39 [build] Server built in 4.33s
19:01:20 [build] Complete! 17:37:39 [build] Complete!

View File

@ -8,6 +8,15 @@ import "@/styles/look-grid.css"
const { locale, t, getRelativeLocaleUrl } = getI18n(Astro) 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 个、按热度顺序排列。 // 热门品牌:走 SSG 专属接口 /api/v1/ssg/brands/hot,后端固定返回热度前 30 个、按热度顺序排列。
// 侧栏 filter 展示前 10 个(模板内 slice(0,10)),品牌弹窗 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"> <header class="showshead">
<div> <div>
@ -252,7 +261,31 @@ const seasonOptions: { value: string; label: string }[] = [
<!-- 品牌筛选弹窗:抽成独立组件 BrandModal.astro(状态由本页 showsPage 提供) --> <!-- 品牌筛选弹窗:抽成独立组件 BrandModal.astro(状态由本页 showsPage 提供) -->
<BrandModal /> <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> </div>
@ -262,7 +295,7 @@ const seasonOptions: { value: string; label: string }[] = [
<script> <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 { clientHref, ROUTES } from "@/lib/routes"
import { SPIN_SVG, makeCardSlots, buildPageList } from "@/lib/looks-grid" import { SPIN_SVG, makeCardSlots, buildPageList } from "@/lib/looks-grid"
@ -301,6 +334,13 @@ const seasonOptions: { value: string; label: string }[] = [
lastPage: 1, lastPage: 1,
reqToken: 0, reqToken: 0,
// 登录门禁弹窗状态(硬门禁:未登录点筛选/翻页时弹出内联登录表单)
showLoginModal: false,
loginModalAccount: "",
loginModalPassword: "",
loginModalError: "",
loginModalLoading: false,
init() { init() {
this.locale = this.$el.dataset.locale || 'en'; this.locale = this.$el.dataset.locale || 'en';
// 支持从 header 下拉深链 ?collection=xxx 直接进入对应分类(与侧栏 COLLECTION 筛选一致) // 支持从 header 下拉深链 ?collection=xxx 直接进入对应分类(与侧栏 COLLECTION 筛选一致)
@ -353,6 +393,7 @@ const seasonOptions: { value: string; label: string }[] = [
}, },
refreshFilter() { refreshFilter() {
if (!this.requireLogin()) return
this.loadPage(1) this.loadPage(1)
}, },
@ -441,6 +482,34 @@ const seasonOptions: { value: string; label: string }[] = [
this.refreshFilter() 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 加载(分页:每次整页替换,不追加) // API 加载(分页:每次整页替换,不追加)
async loadPage(page: number) { async loadPage(page: number) {
const myToken = ++this.reqToken const myToken = ++this.reqToken
@ -478,6 +547,7 @@ const seasonOptions: { value: string; label: string }[] = [
}, },
goPage(p: number) { goPage(p: number) {
if (!this.requireLogin()) return
if (this.loading) return if (this.loading) return
if (p < 1 || p > this.lastPage || p === this.page) return if (p < 1 || p > this.lastPage || p === this.page) return
this.loadPage(p) this.loadPage(p)

View File

@ -7,6 +7,15 @@ import "@/styles/look-grid.css"
const { locale, t } = getI18n(Astro) 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 年(含当年),末项兜底 // 年份筛选:近 10 年(含当年),末项兜底
const currentYear = new Date().getFullYear() const currentYear = new Date().getFullYear()
const yearFloor = currentYear - 9 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"> <header class="snapshead">
<div> <div>
@ -88,7 +97,7 @@ const cityOptions: { value: string; label: string }[] = [
<div class="snapsg-b" x-show="!collapsedGroups.year"> <div class="snapsg-b" x-show="!collapsedGroups.year">
<ul class="snapschecks snapschecks--flat"> <ul class="snapschecks snapschecks--flat">
{yearOptions.map((o) => ( {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> </ul>
</div> </div>
@ -105,7 +114,7 @@ const cityOptions: { value: string; label: string }[] = [
<div class="snapsg-b" x-show="!collapsedGroups.sort"> <div class="snapsg-b" x-show="!collapsedGroups.sort">
<ul class="snapschecks snapschecks--flat"> <ul class="snapschecks snapschecks--flat">
{sortOptions.map((o) => ( {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> </ul>
</div> </div>
@ -122,13 +131,13 @@ const cityOptions: { value: string; label: string }[] = [
<div class="snapsg-b" x-show="!collapsedGroups.city"> <div class="snapsg-b" x-show="!collapsedGroups.city">
<ul class="snapschecks snapschecks--flat"> <ul class="snapschecks snapschecks--flat">
{cityOptions.map((o) => ( {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> </ul>
</div> </div>
</section> </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> </div>
</aside> </aside>
@ -210,6 +219,33 @@ const cityOptions: { value: string; label: string }[] = [
</nav> </nav>
</main> </main>
</div> </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> </div>
<script id="snaps-year-opts" type="application/json" set:html={JSON.stringify({ yearOptions, sortOptions, cityOptions })}></script> <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> <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 { clientHref, ROUTES } from "@/lib/routes"
import { SPIN_SVG, makeCardSlots, buildPageList } from "@/lib/looks-grid" import { SPIN_SVG, makeCardSlots, buildPageList } from "@/lib/looks-grid"
@ -247,6 +283,13 @@ const cityOptions: { value: string; label: string }[] = [
lastPage: 1, lastPage: 1,
reqToken: 0, reqToken: 0,
// 登录门禁弹窗状态(硬门禁:未登录点筛选/翻页时弹出内联登录表单)
showLoginModal: false,
loginModalAccount: "",
loginModalPassword: "",
loginModalError: "",
loginModalLoading: false,
init() { init() {
this.locale = this.$el.dataset.locale || 'en' this.locale = this.$el.dataset.locale || 'en'
// 支持从 header 下拉深链 ?city=xxx 直接进入对应地区(与侧栏 City 筛选一致) // 支持从 header 下拉深链 ?city=xxx 直接进入对应地区(与侧栏 City 筛选一致)
@ -267,6 +310,34 @@ const cityOptions: { value: string; label: string }[] = [
this.loadPage(1) 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 的可见性都依赖它) // 已激活筛选 chips(顶部 pills + 侧栏 Clear all 的可见性都依赖它)
get pills() { get pills() {
const out: { label: string; clear: () => void }[] = [] const out: { label: string; clear: () => void }[] = []
@ -331,6 +402,7 @@ const cityOptions: { value: string; label: string }[] = [
}, },
goPage(p: number) { goPage(p: number) {
if (!this.requireLogin()) return
if (this.loading) return if (this.loading) return
if (p < 1 || p > this.lastPage || p === this.page) return if (p < 1 || p > this.lastPage || p === this.page) return
this.loadPage(p) this.loadPage(p)

View File

@ -40,6 +40,22 @@ export const dict: Record<string, TranslationEntry> = {
'signup': { cn: '注册' }, '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 ── // ── 控件 / Controls ──
'back to index': { cn: '返回首页' }, 'back to index': { cn: '返回首页' },

View File

@ -141,10 +141,9 @@ const headers = {
))} ))}
</ul> </ul>
</div> </div>
<!-- <div class="flex items-center gap-2" id="auth-slot" data-hi-label={hiLabel} data-logout-label={logoutLabel}> <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">{t('Login')}</a> <a href={href(locale, ROUTES.login)} class="hover:opacity-60 transition-opacity duration-200 uppercase tracking-[0.5px] text-[13px]">{t('Login')}</a>
<a href={href(locale, ROUTES.register)} class="hover:opacity-60 transition-opacity duration-200">{t('Signup')}</a> </div>
</div> -->
</div> </div>
</nav> </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"> <footer class="relative z-[1] bg-white mt-20 pt-10 border-t-2 border-black text-black w-full font-sans">
<script> <script>
import { getUser, fetchMe, clearSession } from "@/lib/api" import { getUser, fetchMe, logout } from "@/lib/api"
const slot = document.getElementById("auth-slot") const slot = document.getElementById("auth-slot")
const hiLabel = slot?.dataset.hiLabel ?? "Hi" const hiLabel = slot?.dataset.hiLabel ?? "Hi"
const logoutLabel = slot?.dataset.logoutLabel ?? "Logout" const logoutLabel = slot?.dataset.logoutLabel ?? "Logout"
@ -162,7 +161,7 @@ const headers = {
if (!user) return // 未登录:保留 SSR 渲染的 Login/Signup(已带语言前缀,无需重写) 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>` 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") 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() const cached = getUser()
if (cached) render(cached) if (cached) render(cached)

View File

@ -284,11 +284,12 @@ export async function getBrands(opts?: {
} }
// ===================== 账号体系(/api/auth/*) ===================== // ===================== 账号体系(/api/auth/*) =====================
// 说明:当前前端只用「取当前用户 + 登出」两个能力(顶栏已登录态)。 // 双令牌:access_token(短命,请求鉴权)+ refresh_token(长命,落库可吊销)。
// 登录/注册的表单提交暂未接入,相关接口函数已移除,避免无人调用的死代码。 // 登录写两者;fetchMe 等受保护请求遇 401 自动用 refresh 续期一次;登出吊销 refresh。
const BASE_API_URL = (BASE_API || "").replace(/\/$/, "") 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" const USER_KEY = "fa_user"
// 注意:getUser / clearSession 只读写 localStorage,不发网络请求。 // 注意: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 { export function clearSession(): void {
if (typeof localStorage === "undefined") return if (typeof localStorage === "undefined") return
localStorage.removeItem(TOKEN_KEY) localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(REFRESH_KEY)
localStorage.removeItem(USER_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> { export async function fetchMe(): Promise<AuthUser | null> {
if (typeof localStorage === "undefined") return null if (typeof localStorage === "undefined") return null
const token = localStorage.getItem(TOKEN_KEY) if (!getAccessToken()) return null
if (!token) return null
try { try {
// 接口:GET /api/auth/me(需 Bearer token,客户端运行期 base 走 BASE_API) const res = await authedFetch(`${BASE_API_URL}/api/v1/auth/me?locale=${encodeURIComponent(currentLocale())}`)
const res = await fetch(`${BASE_API_URL}/api/v1/auth/me?locale=${encodeURIComponent(currentLocale())}`, {
headers: { Authorization: `Bearer ${token}` },
})
if (!res.ok) { if (!res.ok) {
clearSession() clearSession()
return null return null
@ -329,9 +386,59 @@ export async function fetchMe(): Promise<AuthUser | null> {
} }
} }
// 注:saveSession(登录/注册成功后写 token+user 进 localStorage)已移除—— // 登录:POST /api/v1/auth/login(公开端点)。成功后写 access+refresh+user 进 localStorage。
// 站点没有登录注册入口,后端 POST /auth/register、POST /auth/login 也已下线。 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 构建期) ===================== // ===================== SSG 构建专用(/api/ssg/*,仅 Node 构建期) =====================

View File

@ -13,6 +13,7 @@ export const ROUTES = {
portfolio: '/portfolio', portfolio: '/portfolio',
login: '/login', login: '/login',
register: '/register', register: '/register',
account: '/account',
runwayLooks: '/runway-looks', runwayLooks: '/runway-looks',
// 街拍 // 街拍
streetSnaps: '/street-snaps', streetSnaps: '/street-snaps',

View 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
View 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>

View 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
View 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>