This commit is contained in:
eric
2026-03-12 19:50:25 -05:00
parent ffa5043daf
commit 37d0883ce9
22 changed files with 688 additions and 236 deletions

View File

@@ -8,16 +8,27 @@ import { LessonMarkdown } from "./LessonMarkdown";
import { getLesson } from "@/config/lessons";
import { canWatchLesson } from "@/app/lib/course-payment";
import { useAuthAndVip } from "@/app/lib/useAuthAndVip";
import { getStoredToken, getStoredUser } from "@/app/lib/pocketbase";
import { setLastWatched, markCompleted } from "@/app/lib/learning";
import { DOWNLOAD_CONFIG } from "@/config/course";
import Header from "@/app/components/Header";
import AuthModal from "@/app/components/AuthModal";
import {
getPayEnv,
getRecommendedChannel,
mustUseWxPay,
redirectToPay,
getDeviceFromEnv,
} from "@/app/lib/payment";
export default function LessonPage() {
const params = useParams();
const router = useRouter();
const { t } = useTranslation("community");
const { vip } = useAuthAndVip();
const { user, vip } = useAuthAndVip();
const [toast, setToast] = useState(false);
const [authOpen, setAuthOpen] = useState(false);
const [payRedirecting, setPayRedirecting] = useState(false);
const moduleIndex = Number(params.moduleIndex);
const lessonIndex = Number(params.lessonIndex);
@@ -29,6 +40,57 @@ export default function LessonPage() {
if (lesson && unlocked) setLastWatched(moduleIndex, lessonIndex, lesson.name);
}, [moduleIndex, lessonIndex, lesson?.name, unlocked]);
const startPay = (userId: string) => {
const env = getPayEnv();
const channel = mustUseWxPay(env) ? "wxpay" : getRecommendedChannel(env);
const device = getDeviceFromEnv(env);
const returnUrl = `${window.location.origin}${window.location.pathname}`;
redirectToPay({
user_id: userId,
return_url: returnUrl,
channel,
device,
useJoinConfig: true,
});
};
const handleEnroll = async () => {
if (payRedirecting) return;
setPayRedirecting(true);
try {
if (user?.id) {
startPay(user.id);
return;
}
const meRes = await fetch("/api/auth/me", { credentials: "include" });
const meData = await meRes.json().catch(() => ({}));
if (meData?.user?.id) {
startPay(meData.user.id);
return;
}
const storedUser = getStoredUser();
const storedToken = getStoredToken();
if (storedUser?.id && storedToken) {
await fetch("/api/auth/sync-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: storedToken, record: storedUser }),
credentials: "include",
}).catch(() => null);
startPay(storedUser.id);
return;
}
setAuthOpen(true);
} finally {
setPayRedirecting(false);
}
};
if (!lesson || isNaN(moduleIndex) || isNaN(lessonIndex)) {
return (
<div className="min-h-screen bg-[var(--background)]">
@@ -36,14 +98,12 @@ export default function LessonPage() {
<main className="pt-20 pb-16">
<div className="mx-auto max-w-4xl px-4 py-16 text-center">
<h1 className="mb-4 text-2xl font-bold"></h1>
<p className="mb-6 text-[var(--muted-foreground)]">
</p>
<p className="mb-6 text-[var(--muted-foreground)]"></p>
<Link
href="/course"
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
>
</Link>
</div>
</main>
@@ -56,7 +116,6 @@ export default function LessonPage() {
<Header />
<main className="pt-14 pb-16 md:pt-16">
<div className="mx-auto max-w-4xl px-4 sm:px-6">
{/* 返回导航 */}
<nav className="mb-6 flex items-center gap-2 text-sm">
<button
type="button"
@@ -74,7 +133,6 @@ export default function LessonPage() {
</Link>
</nav>
{/* 标题 */}
<h1 className="mb-2 flex items-center gap-2 text-xl font-bold sm:text-2xl md:text-3xl">
{lesson.name}
{isFreeTrial && (
@@ -83,11 +141,8 @@ export default function LessonPage() {
</span>
)}
</h1>
<p className="mb-8 text-sm text-[var(--muted-foreground)]">
{lesson.duration}
</p>
<p className="mb-8 text-sm text-[var(--muted-foreground)]"> {lesson.duration}</p>
{/* 视频播放器 / 锁定 overlay */}
<div className="relative mb-12">
{unlocked ? (
<VideoPlayer
@@ -102,18 +157,19 @@ export default function LessonPage() {
<div className="aspect-video flex flex-col items-center justify-center gap-4 bg-zinc-900">
<span className="text-6xl">🔒</span>
<p className="text-lg text-white/90"></p>
<Link
href="/join"
className="rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90"
<button
type="button"
onClick={handleEnroll}
disabled={payRedirecting}
className="rounded-full bg-[var(--accent)] px-6 py-3 font-medium text-[var(--accent-foreground)] transition hover:opacity-90 disabled:opacity-70"
>
</Link>
{payRedirecting ? "跳转支付中..." : "立即报名"}
</button>
</div>
</div>
)}
</div>
{/* 配套文档 - 仅解锁后显示 */}
{unlocked && (
<div className="relative rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm md:rounded-2xl md:p-8">
<h2 className="mb-6 flex items-center gap-2 text-lg font-semibold">
@@ -126,7 +182,6 @@ export default function LessonPage() {
</div>
)}
{/* 网盘下载 */}
{DOWNLOAD_CONFIG.enabled && unlocked && (
<div className="mt-8 rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm md:rounded-2xl md:p-8">
<h2 className="mb-4 flex items-center gap-2 text-lg font-semibold">
@@ -135,9 +190,7 @@ export default function LessonPage() {
</svg>
{DOWNLOAD_CONFIG.title}
</h2>
<p className="mb-4 text-sm text-[var(--muted-foreground)]">
</p>
<p className="mb-4 text-sm text-[var(--muted-foreground)]"></p>
<a
href={DOWNLOAD_CONFIG.url}
target="_blank"
@@ -161,6 +214,14 @@ export default function LessonPage() {
{t("updating")}
</div>
)}
<AuthModal
isOpen={authOpen}
onClose={() => setAuthOpen(false)}
onSuccess={() => {
setAuthOpen(false);
void handleEnroll();
}}
/>
</div>
);
}

View File

@@ -0,0 +1,45 @@
import { NextRequest, NextResponse } from "next/server";
import { getPocketBaseConfig } from "@/config/services.config";
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
export async function POST(request: NextRequest) {
const body = await request.json().catch(() => ({}));
const identity = String(body?.identity || body?.email || "").trim();
const password = String(body?.password || "");
if (!identity || !password) {
return NextResponse.json({ ok: false, error: "Missing identity or password" }, { status: 400 });
}
const pb = getPocketBaseConfig();
const pbRes = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity, password }),
});
const pbData = await pbRes.json().catch(() => ({}));
if (!pbRes.ok || !pbData?.token || !pbData?.record?.id) {
return NextResponse.json(
{ ok: false, error: pbData?.message || "Login failed" },
{ status: pbRes.status || 401 }
);
}
const payload = JSON.stringify({
token: pbData.token,
userId: pbData.record.id,
email: pbData.record.email ?? identity,
});
const encoded = Buffer.from(payload, "utf-8").toString("base64url");
const res = NextResponse.json({
ok: true,
token: pbData.token,
record: pbData.record,
user: { id: pbData.record.id, email: pbData.record.email ?? identity },
});
res.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return res;
}

View File

@@ -1,15 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { getAuthCookieDomain } from "@/config/domain.config";
const COOKIE_NAME = "pb_session";
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
export async function POST(request: NextRequest) {
const domain = getAuthCookieDomain(request);
const res = NextResponse.json({ ok: true });
res.cookies.set(COOKIE_NAME, "", {
...(domain && { domain }),
path: "/",
maxAge: 0,
});
res.cookies.set(COOKIE_NAME, "", getCookieOptions(true, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return res;
}

View File

@@ -1,13 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { getPocketBaseConfig } from "@/config/services.config";
import { getAuthCookieDomain } from "@/config/domain.config";
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
export async function GET(request: NextRequest) {
const cookie = request.cookies.get(COOKIE_NAME)?.value;
const domain = getAuthCookieDomain(request);
if (!cookie) {
return NextResponse.json({ ok: true, user: null });
}
@@ -17,18 +13,18 @@ export async function GET(request: NextRequest) {
if (!token || !userId) return NextResponse.json({ ok: true, user: null });
const pb = getPocketBaseConfig();
const res = await fetch(`${pb.url}/api/users/refresh`, {
const res = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/auth-refresh`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const r = NextResponse.json({ ok: true, user: null });
r.cookies.set(COOKIE_NAME, "", { ...(domain && { domain }), path: "/", maxAge: 0 });
r.cookies.set(COOKIE_NAME, "", getCookieOptions(true, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return r;
}
const data = await res.json();
const newToken = data.token;
const newRecord = data.record;
// 刷新成功:回写新 token 到 Cookie保持登录态长期有效
if (newToken && newRecord?.id) {
const newPayload = JSON.stringify({
token: newToken,
@@ -41,14 +37,7 @@ export async function GET(request: NextRequest) {
user: { id: newRecord.id, email: newRecord.email ?? email },
token: newToken,
});
r.cookies.set(COOKIE_NAME, encoded, {
...(domain && { domain }),
path: "/",
maxAge: COOKIE_MAX_AGE,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
httpOnly: true,
});
r.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return r;
}
return NextResponse.json({

View File

@@ -0,0 +1,62 @@
import { NextRequest, NextResponse } from "next/server";
import { getPocketBaseConfig } from "@/config/services.config";
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
export async function POST(request: NextRequest) {
const body = await request.json().catch(() => ({}));
const email = String(body?.email || "").trim();
const password = String(body?.password || "");
const passwordConfirm = String(body?.passwordConfirm || "");
if (!email || !password || !passwordConfirm) {
return NextResponse.json(
{ ok: false, error: "Missing email/password/passwordConfirm" },
{ status: 400 }
);
}
const pb = getPocketBaseConfig();
const createRes = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/records`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, passwordConfirm }),
});
const createData = await createRes.json().catch(() => ({}));
if (!createRes.ok) {
return NextResponse.json(
{ ok: false, error: createData?.message || "Register failed" },
{ status: createRes.status || 400 }
);
}
const loginRes = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity: email, password }),
});
const loginData = await loginRes.json().catch(() => ({}));
if (!loginRes.ok || !loginData?.token || !loginData?.record?.id) {
return NextResponse.json(
{ ok: false, error: loginData?.message || "Auto login failed after register" },
{ status: loginRes.status || 401 }
);
}
const payload = JSON.stringify({
token: loginData.token,
userId: loginData.record.id,
email: loginData.record.email ?? email,
});
const encoded = Buffer.from(payload, "utf-8").toString("base64url");
const res = NextResponse.json({
ok: true,
token: loginData.token,
record: loginData.record,
user: { id: loginData.record.id, email: loginData.record.email ?? email },
});
res.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return res;
}

View File

@@ -1,8 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { getAuthCookieDomain } from "@/config/domain.config";
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365; // 365 天,登录态持续有效直至用户主动退出
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
export async function POST(request: NextRequest) {
const body = await request.json().catch(() => ({}));
@@ -19,15 +16,7 @@ export async function POST(request: NextRequest) {
});
const encoded = Buffer.from(payload, "utf-8").toString("base64url");
const domain = getAuthCookieDomain(request);
const res = NextResponse.json({ ok: true });
res.cookies.set(COOKIE_NAME, encoded, {
...(domain && { domain }),
path: "/",
maxAge: COOKIE_MAX_AGE,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
httpOnly: true,
});
res.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
return res;
}

View File

@@ -1,11 +1,7 @@
"use client";
import { useState, type FormEvent } from "react";
import {
pbLogin,
pbRegister,
pbSaveAuth,
} from "@/app/lib/pocketbase";
import { pbSaveAuth } from "@/app/lib/pocketbase";
interface AuthModalProps {
isOpen: boolean;
@@ -13,6 +9,14 @@ interface AuthModalProps {
onSuccess: (email: string) => void;
}
type AuthResult = {
ok: boolean;
token?: string;
record?: { id: string; email?: string; [key: string]: unknown };
error?: string;
message?: string;
};
export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps) {
const [mode, setMode] = useState<"login" | "register">("login");
const [email, setEmail] = useState("");
@@ -27,40 +31,45 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
setLoading(true);
try {
let result;
if (mode === "register") {
if (password !== passwordConfirm) {
setError("两次密码不一致");
setError("Passwords do not match");
setLoading(false);
return;
}
if (password.length < 8) {
setError("密码至少 8 位");
setError("Password must be at least 8 characters");
setLoading(false);
return;
}
result = await pbRegister(email, password, passwordConfirm);
} else {
result = await pbLogin(email, password);
}
pbSaveAuth(result.token, result.record);
try {
await fetch("/api/auth/sync-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: result.token, record: result.record }),
credentials: "include",
});
} catch {
/* ignore */
const endpoint = mode === "login" ? "/api/auth/login" : "/api/auth/register";
const payload =
mode === "login"
? { identity: email, password }
: { email, password, passwordConfirm };
const res = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(payload),
});
const data = (await res.json().catch(() => ({}))) as AuthResult;
if (!res.ok || !data?.ok || !data?.token || !data?.record) {
throw new Error(data?.error || data?.message || "Authentication failed");
}
pbSaveAuth(data.token, { id: data.record.id, email: data.record.email ?? email });
onSuccess(email);
onClose();
setEmail("");
setPassword("");
setPasswordConfirm("");
} catch (err) {
setError(err instanceof Error ? err.message : "操作失败");
setError(err instanceof Error ? err.message : "Authentication failed");
} finally {
setLoading(false);
}
@@ -70,32 +79,26 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
return (
<div className="fixed inset-0 z-[100] flex items-center justify-center">
<div
className="absolute inset-0 bg-black/50"
onClick={onClose}
aria-hidden
/>
<div className="absolute inset-0 bg-black/50" onClick={onClose} aria-hidden />
<div className="relative w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl">
<button
onClick={onClose}
className="absolute right-4 top-4 text-slate-400 hover:text-slate-600"
aria-label="关闭"
aria-label="Close"
>
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<h2 className="text-xl font-bold text-slate-800">
{mode === "login" ? "登录" : "注册"}
</h2>
<h2 className="text-xl font-bold text-slate-800">{mode === "login" ? "Login" : "Register"}</h2>
<p className="mt-1 text-sm text-slate-500">
{mode === "login" ? "使用邮箱密码登录" : "创建新账号"}
{mode === "login" ? "Use email and password" : "Create a new account"}
</p>
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
<div>
<label className="mb-1 block text-sm font-medium text-slate-700"></label>
<label className="mb-1 block text-sm font-medium text-slate-700">Email</label>
<input
type="email"
value={email}
@@ -106,12 +109,12 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-slate-700"></label>
<label className="mb-1 block text-sm font-medium text-slate-700">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="至少 8 位"
placeholder="At least 8 characters"
required
minLength={mode === "register" ? 8 : 1}
className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-slate-800 placeholder-slate-400 focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
@@ -119,33 +122,31 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
</div>
{mode === "register" && (
<div>
<label className="mb-1 block text-sm font-medium text-slate-700"></label>
<label className="mb-1 block text-sm font-medium text-slate-700">Confirm Password</label>
<input
type="password"
value={passwordConfirm}
onChange={(e) => setPasswordConfirm(e.target.value)}
placeholder="再次输入密码"
placeholder="Enter password again"
required
className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-slate-800 placeholder-slate-400 focus:border-sky-500 focus:outline-none focus:ring-1 focus:ring-sky-500"
/>
</div>
)}
{error && (
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>
)}
{error && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>}
<button
type="submit"
disabled={loading}
className="w-full rounded-lg bg-sky-500 py-3 font-semibold text-white transition-colors hover:bg-sky-600 disabled:opacity-70"
>
{loading ? "处理中…" : mode === "login" ? "登录" : "注册"}
{loading ? "Processing..." : mode === "login" ? "Login" : "Register"}
</button>
</form>
<p className="mt-4 text-center text-sm text-slate-500">
{mode === "login" ? (
<>
{" "}
No account?{" "}
<button
type="button"
onClick={() => {
@@ -154,12 +155,12 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
}}
className="font-medium text-sky-500 hover:text-sky-600"
>
Register
</button>
</>
) : (
<>
{" "}
Already have an account?{" "}
<button
type="button"
onClick={() => {
@@ -168,7 +169,7 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
}}
className="font-medium text-sky-500 hover:text-sky-600"
>
Login
</button>
</>
)}

View File

@@ -4,6 +4,7 @@ import { useState } from "react";
import { Link, useTranslation } from "@/i18n/navigation";
import { TOPIC_IDS } from "@/config";
import type { ResourceData } from "@/app/lib/theme-data";
import { useCrossSiteUrls } from "@/app/lib/useCrossSiteUrls";
import ResourceNavigation from "./ResourceNavigation";
const mainModuleKeys = ["destinations", "vipEntry", "appDownload"] as const;
@@ -18,11 +19,6 @@ const linkIcons: Record<string, string> = {
cloudPhone: "☁️",
unmannedLive: "📺",
};
const linkHrefs: Record<string, { href: string; newTab?: boolean }> = {
destinations: { href: "https://meetup.hackrobot.cn/", newTab: true },
vipEntry: { href: "https://vip.hackrobot.cn/", newTab: true },
appDownload: { href: "/app" },
};
type CommunityProps = {
resourceData?: ResourceData;
@@ -31,6 +27,12 @@ type CommunityProps = {
export default function Community({ resourceData }: CommunityProps) {
const { t } = useTranslation("community");
const [toast, setToast] = useState(false);
const { meetupUrl, vipUrl } = useCrossSiteUrls();
const linkHrefs: Record<string, { href: string; newTab?: boolean }> = {
destinations: { href: meetupUrl, newTab: true },
vipEntry: { href: vipUrl, newTab: true },
appDownload: { href: "/app" },
};
const showUpdating = () => {
setToast(true);

View File

@@ -1,46 +1,47 @@
"use client";
import { Link, useTranslation } from "@/i18n/navigation";
const footerSections = [
{
titleKey: "guide" as const,
links: [
{ labelKey: "roadmap" as const, href: "#roadmap" },
{ labelKey: "tools" as const, href: "#tools" },
{ labelKey: "destinations" as const, href: "https://meetup.hackrobot.cn/", openInNewTab: true },
],
},
{
titleKey: "resources" as const,
links: [
{ labelKey: "remoteJobs" as const, href: "#" },
{ labelKey: "visa" as const, href: "#" },
{ labelKey: "coliving" as const, href: "#" },
{ labelKey: "insurance" as const, href: "#" },
],
},
{
titleKey: "community" as const,
links: [
{ labelKey: "discord" as const, href: "#" },
{ labelKey: "wechat" as const, href: "https://vip.hackrobot.cn/", openInNewTab: true },
{ labelKey: "jike" as const, href: "#" },
],
},
{
titleKey: "about" as const,
links: [
{ labelKey: "aboutUs" as const, href: "/about", internal: true },
{ labelKey: "recruit" as const, href: "/jobs", internal: true },
{ labelKey: "privacy" as const, href: "/privacy", internal: true, openInNewTab: true },
{ labelKey: "contact" as const, href: "#" },
],
},
];
import { useCrossSiteUrls } from "@/app/lib/useCrossSiteUrls";
export default function Footer() {
const { t } = useTranslation("footer");
const { meetupUrl, vipUrl } = useCrossSiteUrls();
const footerSections = [
{
titleKey: "guide" as const,
links: [
{ labelKey: "roadmap" as const, href: "#roadmap" },
{ labelKey: "tools" as const, href: "#tools" },
{ labelKey: "destinations" as const, href: meetupUrl, openInNewTab: true },
],
},
{
titleKey: "resources" as const,
links: [
{ labelKey: "remoteJobs" as const, href: "#" },
{ labelKey: "visa" as const, href: "#" },
{ labelKey: "coliving" as const, href: "#" },
{ labelKey: "insurance" as const, href: "#" },
],
},
{
titleKey: "community" as const,
links: [
{ labelKey: "discord" as const, href: "#" },
{ labelKey: "wechat" as const, href: vipUrl, openInNewTab: true },
{ labelKey: "jike" as const, href: "#" },
],
},
{
titleKey: "about" as const,
links: [
{ labelKey: "aboutUs" as const, href: "/about", internal: true },
{ labelKey: "recruit" as const, href: "/jobs", internal: true },
{ labelKey: "privacy" as const, href: "/privacy", internal: true, openInNewTab: true },
{ labelKey: "contact" as const, href: "#" },
],
},
];
return (
<footer className="border-t border-slate-100 bg-white dark:border-slate-800 dark:bg-slate-900">
<div className="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8 lg:py-16">

View File

@@ -3,17 +3,11 @@
import { useState, useEffect } from "react";
import { Link, useLocale, usePathname, useRouter, useTranslation } from "@/i18n/navigation";
import { getStoredUserEmail } from "@/app/lib/pocketbase";
import { useCrossSiteUrls } from "@/app/lib/useCrossSiteUrls";
import AuthModal from "./AuthModal";
import ThemeToggle from "./ThemeToggle";
import UserAvatar from "./UserAvatar";
const navLinks = [
{ labelKey: "roadmap" as const, href: "#roadmap" },
{ labelKey: "tools" as const, href: "#tools" },
{ labelKey: "community" as const, href: "https://vip.hackrobot.cn/", external: true },
{ labelKey: "resources" as const, href: "#resources" },
];
export default function Header() {
const { t } = useTranslation("common");
const { t: tNav } = useTranslation("nav");
@@ -24,6 +18,13 @@ export default function Header() {
const [scrolled, setScrolled] = useState(false);
const [authOpen, setAuthOpen] = useState(false);
const [userEmail, setUserEmail] = useState<string | null>(null);
const { vipUrl } = useCrossSiteUrls();
const navLinks = [
{ labelKey: "roadmap" as const, href: "#roadmap" },
{ labelKey: "tools" as const, href: "#tools" },
{ labelKey: "community" as const, href: vipUrl, external: true },
{ labelKey: "resources" as const, href: "#resources" },
];
useEffect(() => {
let mounted = true;

View File

@@ -1,9 +1,6 @@
"use client";
import { useState } from "react";
import { Link, useTranslation, useRouter } from "@/i18n/navigation";
import { useAuthAndVip } from "@/app/lib/useAuthAndVip";
import AuthModal from "@/app/components/AuthModal";
import { Link, useTranslation } from "@/i18n/navigation";
const days = [
{ day: 1, icon: "👋", color: "bg-sky-500" },
@@ -17,9 +14,6 @@ const days = [
export default function Roadmap() {
const { t } = useTranslation("roadmap");
const router = useRouter();
const { user, vip, loading, refetch } = useAuthAndVip();
const [authOpen, setAuthOpen] = useState(false);
return (
<section id="roadmap" className="bg-slate-50 py-20 sm:py-28 dark:bg-slate-900">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
@@ -90,20 +84,8 @@ export default function Roadmap() {
</span>
</Link>
<button
type="button"
onClick={async () => {
if (loading) return;
if (!user) {
setAuthOpen(true);
return;
}
if (!vip) {
router.replace("/join");
return;
}
router.replace("/course");
}}
<Link
href="/course"
className="group flex w-full flex-col overflow-hidden rounded-2xl border-2 border-amber-200 bg-gradient-to-br from-amber-50 to-orange-50/50 p-8 text-left shadow-md transition-all hover:border-amber-300 hover:shadow-lg dark:border-amber-800 dark:from-amber-900/20 dark:to-orange-900/10 dark:hover:border-amber-700"
>
<div className="mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-r from-amber-500 to-orange-500 text-3xl shadow-lg shadow-amber-200/50 dark:shadow-amber-900/30">
@@ -121,19 +103,9 @@ export default function Roadmap() {
<span className="mt-6 inline-flex items-center gap-2 self-start rounded-full bg-amber-500 px-6 py-3 font-semibold text-white transition group-hover:bg-amber-600 dark:bg-amber-600 dark:group-hover:bg-amber-500">
{t("course.cta")}
</span>
</button>
</Link>
</div>
</div>
<AuthModal
isOpen={authOpen}
onClose={() => setAuthOpen(false)}
onSuccess={async () => {
setAuthOpen(false);
const { vip: isVip } = await refetch();
router.replace(isVip ? "/course" : "/join");
}}
/>
</div>
</section>
);

View File

@@ -3,20 +3,79 @@
import { Link } from "@/i18n/navigation";
import { CTA_CONFIG } from "@/config/course";
import { useAuthAndVip } from "@/app/lib/useAuthAndVip";
import { getStoredToken, getStoredUser } from "@/app/lib/pocketbase";
import AuthModal from "@/app/components/AuthModal";
import {
getPayEnv,
getRecommendedChannel,
mustUseWxPay,
redirectToPay,
getDeviceFromEnv,
} from "@/app/lib/payment";
import { useState } from "react";
export function CTASection() {
const { user, vip } = useAuthAndVip();
const paid = !!user && vip;
const [authOpen, setAuthOpen] = useState(false);
const [payRedirecting, setPayRedirecting] = useState(false);
const startPay = (userId: string) => {
const env = getPayEnv();
const channel = mustUseWxPay(env) ? "wxpay" : getRecommendedChannel(env);
const device = getDeviceFromEnv(env);
const returnUrl = `${window.location.origin}/course/0/0`;
redirectToPay({
user_id: userId,
return_url: returnUrl,
channel,
device,
useJoinConfig: true,
});
};
const handleEnroll = async () => {
if (payRedirecting) return;
setPayRedirecting(true);
try {
if (user?.id) {
startPay(user.id);
return;
}
const meRes = await fetch("/api/auth/me", { credentials: "include" });
const meData = await meRes.json().catch(() => ({}));
if (meData?.user?.id) {
startPay(meData.user.id);
return;
}
const storedUser = getStoredUser();
const storedToken = getStoredToken();
if (storedUser?.id && storedToken) {
await fetch("/api/auth/sync-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: storedToken, record: storedUser }),
credentials: "include",
}).catch(() => null);
startPay(storedUser.id);
return;
}
setAuthOpen(true);
} finally {
setPayRedirecting(false);
}
};
return (
<section className="border-t border-[var(--border)] py-16 sm:py-20 md:py-24">
<div className="mx-auto max-w-3xl px-4 text-center sm:px-6">
<h2 className="mb-4 text-xl font-bold sm:text-2xl md:text-3xl">
{CTA_CONFIG.title}
</h2>
<p className="mb-6 text-[var(--muted-foreground)] sm:mb-8">
{CTA_CONFIG.subtitle}
</p>
<h2 className="mb-4 text-xl font-bold sm:text-2xl md:text-3xl">{CTA_CONFIG.title}</h2>
<p className="mb-6 text-[var(--muted-foreground)] sm:mb-8">{CTA_CONFIG.subtitle}</p>
<div className="mb-8 flex flex-wrap justify-center gap-4 text-sm text-[var(--muted-foreground)] sm:mb-10 sm:gap-6">
{CTA_CONFIG.badges.map((b, i) => (
<span
@@ -36,14 +95,24 @@ export function CTASection() {
</Link>
) : (
<Link
href="/join"
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition hover:opacity-95 sm:px-10"
<button
type="button"
onClick={handleEnroll}
disabled={payRedirecting}
className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition hover:opacity-95 disabled:opacity-70 sm:px-10"
>
</Link>
{payRedirecting ? "跳转支付中..." : "立即报名 →"}
</button>
)}
</div>
<AuthModal
isOpen={authOpen}
onClose={() => setAuthOpen(false)}
onSuccess={() => {
setAuthOpen(false);
void handleEnroll();
}}
/>
</section>
);
}

View File

@@ -4,7 +4,16 @@ import { useState, useEffect } from "react";
import { Link } from "@/i18n/navigation";
import { HERO_CONFIG, CURRICULUM_CONFIG } from "@/config/course";
import { useAuthAndVip } from "@/app/lib/useAuthAndVip";
import { getStoredToken, getStoredUser } from "@/app/lib/pocketbase";
import { getLastWatched, getProgress } from "@/app/lib/learning";
import AuthModal from "@/app/components/AuthModal";
import {
getPayEnv,
getRecommendedChannel,
mustUseWxPay,
redirectToPay,
getDeviceFromEnv,
} from "@/app/lib/payment";
const TOTAL_LESSONS = CURRICULUM_CONFIG.modules.reduce((s, m) => s + m.lessons.length, 0);
@@ -12,6 +21,8 @@ export function CourseHero() {
const { user, vip } = useAuthAndVip();
const [last, setLast] = useState<ReturnType<typeof getLastWatched>>(null);
const [progress, setProgress] = useState({ completed: 0, percent: 0 });
const [authOpen, setAuthOpen] = useState(false);
const [payRedirecting, setPayRedirecting] = useState(false);
useEffect(() => {
setLast(getLastWatched());
@@ -26,6 +37,57 @@ export function CourseHero() {
const paid = !!user && vip;
const startPay = (userId: string) => {
const env = getPayEnv();
const channel = mustUseWxPay(env) ? "wxpay" : getRecommendedChannel(env);
const device = getDeviceFromEnv(env);
const returnUrl = `${window.location.origin}/course/0/0`;
redirectToPay({
user_id: userId,
return_url: returnUrl,
channel,
device,
useJoinConfig: true,
});
};
const handleEnroll = async () => {
if (payRedirecting) return;
setPayRedirecting(true);
try {
if (user?.id) {
startPay(user.id);
return;
}
const meRes = await fetch("/api/auth/me", { credentials: "include" });
const meData = await meRes.json().catch(() => ({}));
if (meData?.user?.id) {
startPay(meData.user.id);
return;
}
const storedUser = getStoredUser();
const storedToken = getStoredToken();
if (storedUser?.id && storedToken) {
await fetch("/api/auth/sync-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: storedToken, record: storedUser }),
credentials: "include",
}).catch(() => null);
startPay(storedUser.id);
return;
}
setAuthOpen(true);
} finally {
setPayRedirecting(false);
}
};
return (
<section className="relative overflow-hidden pt-24 pb-16 sm:pt-28 sm:pb-20 md:pt-32 md:pb-24">
<div className="absolute inset-0 bg-[radial-gradient(ellipse_80%_50%_at_50%_-20%,var(--gradient-accent),transparent)] animate-gradient" />
@@ -39,12 +101,8 @@ export function CourseHero() {
<div className="mb-10 flex flex-wrap justify-center gap-6 sm:mb-12 sm:gap-8">
{HERO_CONFIG.stats.map((s) => (
<div key={s.label} className="text-center transition-transform duration-300 hover:scale-105">
<div className="text-2xl font-bold text-[var(--accent)] sm:text-3xl md:text-4xl">
{s.value}
</div>
<div className="mt-1 text-xs text-[var(--muted-foreground)] sm:text-sm">
{s.label}
</div>
<div className="text-2xl font-bold text-[var(--accent)] sm:text-3xl md:text-4xl">{s.value}</div>
<div className="mt-1 text-xs text-[var(--muted-foreground)] sm:text-sm">{s.label}</div>
</div>
))}
</div>
@@ -64,12 +122,14 @@ export function CourseHero() {
</Link>
) : (
<Link
href="/join"
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
<button
type="button"
onClick={handleEnroll}
disabled={payRedirecting}
className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 disabled:opacity-70 sm:px-10"
>
</Link>
{payRedirecting ? "跳转支付中..." : "立即报名 →"}
</button>
)}
</div>
{paid && progress.completed > 0 && (
@@ -79,14 +139,19 @@ export function CourseHero() {
<span>{progress.completed}/{TOTAL_LESSONS} </span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-[var(--muted)]">
<div
className="h-full rounded-full bg-[var(--accent)] transition-all"
style={{ width: `${progress.percent}%` }}
/>
<div className="h-full rounded-full bg-[var(--accent)] transition-all" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
</div>
<AuthModal
isOpen={authOpen}
onClose={() => setAuthOpen(false)}
onSuccess={() => {
setAuthOpen(false);
void handleEnroll();
}}
/>
</section>
);
}

View File

@@ -47,9 +47,7 @@ export default function RootLayout({
}>) {
return (
<html lang="zh-CN" suppressHydrationWarning>
<body
className="antialiased font-sans"
>
<body className="antialiased font-sans">
<ThemeScript />
<ThemeProvider>{children}</ThemeProvider>
</body>

34
app/lib/auth-cookie.ts Normal file
View File

@@ -0,0 +1,34 @@
/**
* 认证 Cookie 配置
* 生产环境设置 AUTH_COOKIE_DOMAIN 实现跨子域 SSO如 .hackrobot.cn
* 本地开发不设置 domain避免 IP 访问时 cookie 失效
*/
const COOKIE_NAME = "pb_session";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
export { COOKIE_NAME, COOKIE_MAX_AGE };
/** 从请求 Host 头提取 hostname不含端口 */
export function getHostFromRequest(request: { headers: { get: (k: string) => string | null } }): string {
const host = request.headers.get("host") || request.headers.get("x-forwarded-host") || "";
return host.split(",")[0].trim().replace(/:\d+$/, "");
}
export function getCookieOptions(clear = false, requestHost?: string) {
const isProd = process.env.NODE_ENV === "production";
const domain = process.env.AUTH_COOKIE_DOMAIN?.trim();
const opts: Record<string, unknown> = {
path: "/",
maxAge: clear ? 0 : COOKIE_MAX_AGE,
secure: isProd,
sameSite: "lax" as const,
httpOnly: true,
};
if (domain && isProd) {
opts.domain = domain;
} else if (!isProd && requestHost && /^(\d{1,3}\.){3}\d{1,3}$/.test(requestHost)) {
opts.domain = requestHost;
}
return opts;
}

View File

@@ -9,9 +9,12 @@ type LocaleLinkProps = React.ComponentProps<typeof NextLink>;
export function LocaleLink({ href, ...props }: LocaleLinkProps) {
const locale = useLocale();
const hrefStr = typeof href === "string" ? href : href.pathname ?? "/";
const localeHref = hrefStr.startsWith("/")
? `/${locale}${hrefStr === "/" ? "" : hrefStr}`
: hrefStr;
const localeHref =
hrefStr.startsWith("/api/") || hrefStr.startsWith("/_next")
? hrefStr
: hrefStr.startsWith("/")
? `/${locale}${hrefStr === "/" ? "" : hrefStr}`
: hrefStr;
return <NextLink href={localeHref} {...props} />;
}

View File

@@ -27,7 +27,6 @@ export function useAuthAndVip(): AuthAndVipState {
let newUser = meData?.user ?? null;
let newVip = vipData?.vip === true;
// 与 Header 一致API 无用户时,尝试从 localStorage 恢复(如 cookie 未同步、localhost 开发等)
if (!newUser) {
const storedUser = getStoredUser();
const storedToken = getStoredToken();

View File

@@ -0,0 +1,5 @@
import { MEETUP_URL, VIP_URL } from "@/config/domain.config";
export function useCrossSiteUrls(): { meetupUrl: string; vipUrl: string } {
return { meetupUrl: MEETUP_URL, vipUrl: VIP_URL };
}