This commit is contained in:
eric
2026-03-13 03:43:50 -05:00
parent e5d080c202
commit 857380aa01
29 changed files with 3595 additions and 580 deletions

View File

@@ -6,12 +6,39 @@ import { TopicEbookShowcase } from "./landing/TopicEbookShowcase";
type DashboardPageProps = {
userName: string | null;
userEmail?: string | null;
};
export function DashboardPage({ userName }: DashboardPageProps) {
function getStorage(key: string): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem(key);
}
function requiresEmailBinding(): boolean {
const userId = getStorage("userId");
const emailLinked = getStorage("emailLinked") === "1";
const userEmail = getStorage("userEmail");
const userName = getStorage("userName");
return (
!!userId &&
/^user\d+$/.test(userId) &&
!emailLinked &&
!userEmail &&
!userName?.includes("@")
);
}
export function DashboardPage({ userName, userEmail }: DashboardPageProps) {
const bindingRequired = requiresEmailBinding();
return (
<>
<WelcomeBlock userName={userName} />
<WelcomeBlock
userName={userName}
userEmail={userEmail}
bindingRequired={bindingRequired}
/>
<UnlockedStats />
<TopicEbookShowcase />
</>

View File

@@ -13,7 +13,11 @@ import { LoginModal } from "./landing/LoginModal";
type LandingPageProps = {
onJoin: () => void;
onVerify: (userId: string) => Promise<boolean>;
onVerifyByEmail?: (email: string, password: string) => Promise<boolean>;
onVerifyByEmail?: (
email: string,
password: string,
user_id?: string
) => Promise<boolean | { ok: boolean; error?: string }>;
onVerifySuccess: () => void;
};

View File

@@ -64,6 +64,14 @@ export function VipHeader({ isLoggedIn, userName, userEmail, onLogout }: VipHead
>
{getAvatarLetter(displayName)}
</button>
{isLoggedIn && (
<span
className={styles.vipTag}
title="VIP 会员"
>
VIP
</span>
)}
{open && (
<div className="absolute right-0 top-full z-50 mt-2 min-w-[120px] rounded-lg border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-800">
<span className="block px-4 py-2 text-sm text-slate-600 dark:text-slate-400 truncate max-w-[160px]">

View File

@@ -1,88 +1,279 @@
"use client";
import { useState, type FormEvent } from "react";
import { useEffect, useState, type FormEvent } from "react";
import { Copyable } from "../Copyable";
import styles from "../vip.module.css";
type WelcomeBlockProps = {
userName: string | null;
userEmail?: string | null;
bindingRequired?: boolean;
};
const DEFAULT_PASSWORD = "12345678";
function getStorage(key: string): string | null {
if (typeof window === "undefined") return null;
return localStorage.getItem(key);
}
/** 匿名 user_id 格式user + 数字 */
function isAnonymousUserId(val: string | null): boolean {
return !!val && /^user\d+$/.test(val);
function isAnonymousUserId(value: string | null): value is string {
return !!value && /^user\d+$/.test(value);
}
export function WelcomeBlock({ userName }: WelcomeBlockProps) {
const displayName = userName || getStorage("userName") || "会员";
export function WelcomeBlock({
userName,
userEmail,
bindingRequired = false,
}: WelcomeBlockProps) {
const userId = getStorage("userId");
const needLinkEmail = isAnonymousUserId(userId);
const storedUserName = getStorage("userName");
const storedUserEmail = getStorage("userEmail");
const emailLinked = getStorage("emailLinked");
const [dbEmail, setDbEmail] = useState<string | null>(null);
const [backendLinkedEmail, setBackendLinkedEmail] = useState<string | null>(null);
const [backendMemosAccount, setBackendMemosAccount] = useState<string | null>(null);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const [checkingLink, setCheckingLink] = useState(true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [linked, setLinked] = useState(false);
const handleLinkSubmit = async (e: FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
const displayName =
storedUserEmail || userEmail || userName || storedUserName || "会员";
const storedLinkedEmail =
storedUserEmail || (storedUserName?.includes("@") ? storedUserName : null);
const memosAccount =
getStorage("memosAccount") ||
backendMemosAccount ||
(isAnonymousUserId(userId) ? userId : null);
const pbEmail = (() => {
try {
if (password !== passwordConfirm) {
setError("两次密码不一致");
setLoading(false);
return;
}
if (password.length < 8) {
setError("密码至少 8 位");
setLoading(false);
return;
const raw = getStorage("pb_user");
if (!raw) return null;
const parsed = JSON.parse(raw) as { email?: string };
return parsed.email ?? null;
} catch {
return null;
}
})();
const alreadyLinked =
emailLinked === "1" ||
!!storedLinkedEmail ||
!!backendLinkedEmail ||
!!pbEmail;
const needLinkEmail =
bindingRequired &&
isAnonymousUserId(userId) &&
!alreadyLinked &&
!checkingLink;
useEffect(() => {
if (!userId || (alreadyLinked && memosAccount)) {
setCheckingLink(false);
return;
}
fetch(`/api/vip/linked-email?user_id=${encodeURIComponent(userId)}`, {
cache: "no-store",
})
.then((res) => res.json())
.then((data) => {
const linkedEmail = data?.email;
const linkedAnonymousUserId =
typeof data?.anonymousUserId === "string" &&
/^user\d+$/.test(data.anonymousUserId)
? data.anonymousUserId
: null;
if (linkedAnonymousUserId && typeof window !== "undefined") {
setBackendMemosAccount(linkedAnonymousUserId);
localStorage.setItem("memosAccount", linkedAnonymousUserId);
}
if (!linkedEmail || typeof window === "undefined") return;
setBackendLinkedEmail(linkedEmail);
localStorage.setItem("emailLinked", "1");
localStorage.setItem("userEmail", linkedEmail);
localStorage.setItem("userName", linkedEmail);
if (bindingRequired) {
window.location.reload();
}
})
.catch(() => {})
.finally(() => setCheckingLink(false));
}, [alreadyLinked, bindingRequired, memosAccount, userId]);
useEffect(() => {
if (storedLinkedEmail || pbEmail || backendLinkedEmail) return;
if (userEmail) {
setDbEmail(userEmail);
return;
}
const applyEmail = (nextEmail: string | null) => {
if (!nextEmail) return;
setDbEmail(nextEmail);
if (typeof window !== "undefined" && emailLinked === "1") {
localStorage.setItem("userEmail", nextEmail);
}
};
fetch("/api/auth/email", { credentials: "include", cache: "no-store" })
.then((res) => res.json())
.then((data) => {
if (data?.email) {
applyEmail(data.email);
return;
}
return fetch("/api/auth/me", {
credentials: "include",
cache: "no-store",
})
.then((res) => res.json())
.then((meData) => applyEmail(meData?.user?.email ?? null));
})
.catch(() => {});
}, [backendLinkedEmail, emailLinked, pbEmail, storedLinkedEmail, userEmail]);
const handleLinkSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!userId || !isAnonymousUserId(userId)) return;
setLoading(true);
setError(null);
try {
const normalizedEmail = email.trim().toLowerCase();
const res = await fetch("/api/auth/link-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: email.trim(),
password,
email: normalizedEmail,
password: DEFAULT_PASSWORD,
anonymousUserId: userId,
}),
});
const data = await res.json();
if (!data?.ok) {
setError(data?.error || "操作失败");
setLoading(false);
const data = await res.json().catch(() => ({}));
if (!res.ok || !data?.ok || !data?.token || !data?.record?.id) {
setError(data?.error || "绑定邮箱失败");
return;
}
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
pbSaveAuth(data.token, { id: data.record.id, email: data.record.email });
pbSaveAuth(data.token, {
id: data.record.id,
email: data.record.email,
});
await fetch("/api/auth/sync-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: data.token, record: data.record }),
body: JSON.stringify({
token: data.token,
record: data.record,
anonymousUserId: userId,
}),
credentials: "include",
});
if (typeof window !== "undefined") {
localStorage.setItem("userId", data.record.id);
localStorage.setItem("userName", data.record.email || data.record.id);
}
setLinked(true);
window.location.reload();
localStorage.setItem("memosAccount", userId);
localStorage.setItem("userId", data.record.id);
localStorage.setItem("userEmail", data.record.email || normalizedEmail);
localStorage.setItem("userName", data.record.email || normalizedEmail);
localStorage.setItem("emailLinked", "1");
localStorage.setItem("paidType", "vip");
window.location.href = "/";
} catch {
setError("操作失败");
setError("绑定邮箱失败");
} finally {
setLoading(false);
}
};
if (needLinkEmail && !linked) {
return (
const displayEmail =
storedLinkedEmail || pbEmail || backendLinkedEmail || dbEmail || userEmail || null;
return (
<>
{needLinkEmail ? (
<section
className={styles.section}
style={{ paddingTop: "1.5rem", paddingBottom: "0.5rem" }}
>
<div className={styles.loginCard} style={{ maxWidth: "420px" }}>
<div
style={{
fontSize: "1rem",
fontWeight: 600,
marginBottom: "0.35rem",
color: "var(--foreground)",
}}
>
VIP
</div>
<p
style={{
fontSize: "0.85rem",
color: "var(--muted-foreground)",
marginBottom: "0.9rem",
}}
>
{" "}
{DEFAULT_PASSWORD}
</p>
<form onSubmit={handleLinkSubmit}>
<input
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder="your@email.com"
required
disabled={loading}
style={{
width: "100%",
padding: "0.75rem 1rem",
fontSize: "1rem",
border: "1px solid var(--border)",
borderRadius: "8px",
background: "var(--background)",
color: "var(--foreground)",
marginBottom: "0.75rem",
}}
/>
{error ? (
<p
style={{
fontSize: "0.85rem",
color: "#ef4444",
marginBottom: "0.75rem",
}}
>
{error}
</p>
) : null}
<button
type="submit"
disabled={loading}
className={`${styles.btnPrimary} ${styles.btnLarge}`}
style={{ width: "100%" }}
>
{loading ? "处理中..." : "绑定邮箱并继续"}
</button>
</form>
</div>
</section>
) : null}
<section className={styles.section} style={{ paddingTop: "1.5rem" }}>
<h1
className="animate__animated animate__fadeInDown"
@@ -94,135 +285,56 @@ export function WelcomeBlock({ userName }: WelcomeBlockProps) {
animationFillMode: "both",
}}
>
<Copyable text={displayName}>{displayName}</Copyable>
</h1>
<p
className="animate__animated animate__fadeInDown"
style={{
fontSize: "0.95rem",
color: "var(--muted-foreground)",
margin: "0.25rem 0 1rem",
margin: "0.25rem 0 0",
animationDelay: "0.15s",
animationFillMode: "both",
}}
>
Memos 12345678
</p>
<form onSubmit={handleLinkSubmit} className={styles.loginCard} style={{ maxWidth: "400px" }}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="your@email.com"
required
disabled={loading}
style={{
width: "100%",
padding: "0.75rem 1rem",
fontSize: "1rem",
border: "1px solid var(--border)",
borderRadius: "8px",
background: "var(--background)",
color: "var(--foreground)",
marginBottom: "0.75rem",
}}
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="至少 8 位"
required
minLength={8}
disabled={loading}
style={{
width: "100%",
padding: "0.75rem 1rem",
fontSize: "1rem",
border: "1px solid var(--border)",
borderRadius: "8px",
background: "var(--background)",
color: "var(--foreground)",
marginBottom: "0.75rem",
}}
/>
<input
type="password"
value={passwordConfirm}
onChange={(e) => setPasswordConfirm(e.target.value)}
placeholder="再次输入密码"
required
minLength={8}
disabled={loading}
style={{
width: "100%",
padding: "0.75rem 1rem",
fontSize: "1rem",
border: "1px solid var(--border)",
borderRadius: "8px",
background: "var(--background)",
color: "var(--foreground)",
marginBottom: "0.75rem",
}}
/>
{error && (
<p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>{error}</p>
)}
<button
type="submit"
disabled={loading}
className={`${styles.btnPrimary} ${styles.btnLarge}`}
style={{ width: "100%" }}
>
{loading ? "处理中…" : "确认并关联"}
</button>
</form>
<div className={styles.loginCard}>
<div className={styles.loginCardTitle}></div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text="https://qun.hackrobot.cn">
qun.hackrobot.cn
</Copyable>
<a
href="https://qun.hackrobot.cn"
target="_blank"
rel="noopener noreferrer"
className={styles.loginCardLink}
>
</a>
</div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text={memosAccount || ""}>
<span className={styles.loginCardValue}>{memosAccount || "-"}</span>
</Copyable>
</div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text={DEFAULT_PASSWORD}>
<span className={styles.loginCardValue}>{DEFAULT_PASSWORD}</span>
</Copyable>
</div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text={displayEmail || ""}>
<span className={styles.loginCardValue}>{displayEmail || "-"}</span>
</Copyable>
</div>
</div>
</section>
);
}
return (
<section className={styles.section} style={{ paddingTop: "1.5rem" }}>
<h1
className="animate__animated animate__fadeInDown"
style={{
fontSize: "clamp(1.5rem, 4vw, 2rem)",
fontWeight: 600,
margin: 0,
animationDelay: "0.1s",
animationFillMode: "both",
}}
>
<Copyable text={displayName}>{displayName}</Copyable>
</h1>
<p
className="animate__animated animate__fadeInDown"
style={{
fontSize: "0.95rem",
color: "var(--muted-foreground)",
margin: "0.25rem 0 0",
animationDelay: "0.15s",
animationFillMode: "both",
}}
>
</p>
<div className={styles.loginCard}>
<div className={styles.loginCardTitle}></div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text="https://qun.hackrobot.cn">qun.hackrobot.cn</Copyable>
<a href="https://qun.hackrobot.cn" target="_blank" rel="noopener noreferrer" className={styles.loginCardLink}></a>
</div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text={displayName}><span className={styles.loginCardValue}>{displayName}</span></Copyable>
</div>
<div className={styles.loginCardRow}>
<span className={styles.loginCardLabel}></span>
<Copyable text="12345678"><span className={styles.loginCardValue}>12345678</span></Copyable>
</div>
</div>
</section>
</>
);
}

View File

@@ -1,16 +1,25 @@
"use client";
import { useState, useRef, useEffect, type FormEvent } from "react";
import { useEffect, useRef, useState, type FormEvent } from "react";
import styles from "../vip.module.css";
type LoginFormProps = {
onVerify: (userId: string) => Promise<boolean>;
onVerifyByEmail?: (email: string, password: string) => Promise<boolean>;
onVerifyByEmail?: (
email: string,
password: string,
user_id?: string
) => Promise<boolean | { ok: boolean; error?: string }>;
onSuccess: () => void;
autoFocus?: boolean;
};
export function LoginForm({ onVerify, onVerifyByEmail, onSuccess, autoFocus }: LoginFormProps) {
export function LoginForm({
onVerify,
onVerifyByEmail,
onSuccess,
autoFocus,
}: LoginFormProps) {
const [mode, setMode] = useState<"user_id" | "email">("user_id");
const [userId, setUserId] = useState("");
const [email, setEmail] = useState("");
@@ -30,6 +39,7 @@ export function LoginForm({ onVerify, onVerifyByEmail, onSuccess, autoFocus }: L
setError("请输入您的账号");
return;
}
setError(null);
setLoading(true);
try {
@@ -46,17 +56,26 @@ export function LoginForm({ onVerify, onVerifyByEmail, onSuccess, autoFocus }: L
const handleEmailSubmit = async (e: FormEvent) => {
e.preventDefault();
if (!onVerifyByEmail) return;
const trimmedEmail = email.trim();
if (!trimmedEmail || !password) {
setError("请输入邮箱和密码");
const trimmedPassword = password.trim();
if (!trimmedEmail) {
setError("请输入邮箱");
return;
}
if (!trimmedPassword) {
setError("请输入密码");
return;
}
setError(null);
setLoading(true);
try {
const ok = await onVerifyByEmail(trimmedEmail, password);
const result = await onVerifyByEmail(trimmedEmail, trimmedPassword);
const ok = typeof result === "object" ? result.ok : result;
const errMsg = typeof result === "object" ? result.error : undefined;
if (ok) onSuccess();
else setError("未找到该邮箱关联的会员记录,请确认账号正确");
else setError(errMsg || "邮箱或密码错误,或未找到关联的会员记录");
} catch {
setError("验证失败,请稍后重试");
} finally {
@@ -80,19 +99,34 @@ export function LoginForm({ onVerify, onVerifyByEmail, onSuccess, autoFocus }: L
<div className="mb-3 flex gap-2">
<button
type="button"
onClick={() => { setMode("user_id"); setError(null); }}
className={`flex-1 rounded-lg py-2 text-sm font-medium ${mode === "user_id" ? "bg-[var(--primary)] text-[var(--primary-foreground)]" : "bg-[var(--muted)] text-[var(--muted-foreground)]"}`}
onClick={() => {
setMode("user_id");
setError(null);
}}
className={`flex-1 rounded-lg py-2 text-sm font-medium ${
mode === "user_id"
? "bg-[var(--primary)] text-[var(--primary-foreground)]"
: "bg-[var(--muted)] text-[var(--muted-foreground)]"
}`}
>
</button>
<button
type="button"
onClick={() => { setMode("email"); setError(null); }}
className={`flex-1 rounded-lg py-2 text-sm font-medium ${mode === "email" ? "bg-[var(--primary)] text-[var(--primary-foreground)]" : "bg-[var(--muted)] text-[var(--muted-foreground)]"}`}
onClick={() => {
setMode("email");
setError(null);
}}
className={`flex-1 rounded-lg py-2 text-sm font-medium ${
mode === "email"
? "bg-[var(--primary)] text-[var(--primary-foreground)]"
: "bg-[var(--muted)] text-[var(--muted-foreground)]"
}`}
>
</button>
</div>
{mode === "user_id" ? (
<form onSubmit={handleUserIdSubmit}>
<input
@@ -100,12 +134,21 @@ export function LoginForm({ onVerify, onVerifyByEmail, onSuccess, autoFocus }: L
type="text"
value={userId}
onChange={(e) => setUserId(e.target.value)}
placeholder="例如user1234567890"
placeholder="例如user1773315608560"
disabled={loading}
style={inputStyle}
/>
{error && <p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>{error}</p>}
<button type="submit" disabled={loading} className={`${styles.btnPrimary} ${styles.btnLarge}`} style={{ width: "100%" }}>
{error && (
<p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>
{error}
</p>
)}
<button
type="submit"
disabled={loading}
className={`${styles.btnPrimary} ${styles.btnLarge}`}
style={{ width: "100%" }}
>
{loading ? "验证中..." : "验证并登录"}
</button>
</form>
@@ -124,20 +167,48 @@ export function LoginForm({ onVerify, onVerifyByEmail, onSuccess, autoFocus }: L
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="密码"
placeholder="请输入密码"
disabled={loading}
style={inputStyle}
/>
{error && <p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>{error}</p>}
<button type="submit" disabled={loading} className={`${styles.btnPrimary} ${styles.btnLarge}`} style={{ width: "100%" }}>
{error && (
<p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>
{error}
</p>
)}
<button
type="submit"
disabled={loading}
className={`${styles.btnPrimary} ${styles.btnLarge}`}
style={{ width: "100%" }}
>
{loading ? "验证中..." : "验证并登录"}
</button>
</form>
) : (
<form onSubmit={handleUserIdSubmit}>
<input ref={inputRef} type="text" value={userId} onChange={(e) => setUserId(e.target.value)} placeholder="例如user1234567890" disabled={loading} style={inputStyle} />
{error && <p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>{error}</p>}
<button type="submit" disabled={loading} className={`${styles.btnPrimary} ${styles.btnLarge}`} style={{ width: "100%" }}>{loading ? "验证中..." : "验证并登录"}</button>
<input
ref={inputRef}
type="text"
value={userId}
onChange={(e) => setUserId(e.target.value)}
placeholder="例如user1773315608560"
disabled={loading}
style={inputStyle}
/>
{error && (
<p style={{ fontSize: "0.85rem", color: "#ef4444", marginBottom: "0.75rem" }}>
{error}
</p>
)}
<button
type="submit"
disabled={loading}
className={`${styles.btnPrimary} ${styles.btnLarge}`}
style={{ width: "100%" }}
>
{loading ? "验证中..." : "验证并登录"}
</button>
</form>
)}
</>

View File

@@ -8,7 +8,11 @@ type LoginModalProps = {
open: boolean;
onClose: () => void;
onVerify: (userId: string) => Promise<boolean>;
onVerifyByEmail?: (email: string, password: string) => Promise<boolean>;
onVerifyByEmail?: (
email: string,
password: string,
user_id?: string
) => Promise<boolean | { ok: boolean; error?: string }>;
onSuccess: () => void;
};

View File

@@ -54,6 +54,20 @@
font-weight: 500;
}
.vipTag {
position: absolute;
right: -4px;
top: -2px;
font-size: 0.6rem;
font-weight: 700;
padding: 0.1rem 0.35rem;
background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
color: white;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
letter-spacing: 0.02em;
}
.main {
max-width: 1200px;
margin: 0 auto;