;s
This commit is contained in:
@@ -1,14 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, type FormEvent } from "react";
|
||||
import { useCallback, useState, useEffect, type FormEvent } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import {
|
||||
pbLogin,
|
||||
pbRegister,
|
||||
emailLogin,
|
||||
googleLogin,
|
||||
pbSaveAuth,
|
||||
} from "@/app/lib/pocketbase";
|
||||
import { useTranslation } from "@/i18n/navigation";
|
||||
import { apiUrl } from "@/app/lib/api-client";
|
||||
import GoogleLoginButton from "./GoogleLoginButton";
|
||||
|
||||
interface AuthModalProps {
|
||||
isOpen: boolean;
|
||||
@@ -16,37 +17,16 @@ interface AuthModalProps {
|
||||
onSuccess: (email: string) => void;
|
||||
}
|
||||
|
||||
const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || "";
|
||||
|
||||
export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps) {
|
||||
const { t } = useTranslation("auth");
|
||||
const [mode, setMode] = useState<"login" | "register">("login");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [passwordConfirm, setPasswordConfirm] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
let result;
|
||||
if (mode === "register") {
|
||||
if (password !== passwordConfirm) {
|
||||
setError(t("passwordMismatch"));
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError(t("passwordMinLength"));
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
result = await pbRegister(email, password, passwordConfirm);
|
||||
} else {
|
||||
result = await pbLogin(email, password);
|
||||
}
|
||||
const finishAuth = useCallback(
|
||||
async (result: Awaited<ReturnType<typeof emailLogin>>, successEmail: string) => {
|
||||
pbSaveAuth(result.token, result.record);
|
||||
try {
|
||||
await fetch(apiUrl("/api/auth/sync-session"), {
|
||||
@@ -58,11 +38,22 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
onSuccess(email);
|
||||
onSuccess(successEmail);
|
||||
onClose();
|
||||
setEmail("");
|
||||
setPassword("");
|
||||
setPasswordConfirm("");
|
||||
},
|
||||
[onClose, onSuccess]
|
||||
);
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const normalizedEmail = email.trim();
|
||||
const result = await emailLogin(normalizedEmail);
|
||||
await finishAuth(result, normalizedEmail);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "操作失败");
|
||||
} finally {
|
||||
@@ -70,6 +61,19 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoogleCredential = useCallback(async (credential: string) => {
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await googleLogin(credential);
|
||||
await finishAuth(result, result.record.email);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Google 登录失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [finishAuth]);
|
||||
|
||||
const [mounted, setMounted] = useState(false);
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
@@ -95,10 +99,10 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
|
||||
</button>
|
||||
|
||||
<h2 className="text-xl font-bold text-gray-800 dark:text-gray-100">
|
||||
{mode === "login" ? t("login") : t("register")}
|
||||
{t("login")}
|
||||
</h2>
|
||||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
{mode === "login" ? t("loginHint") : t("registerHint")}
|
||||
{t("loginHint")}
|
||||
</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
|
||||
@@ -113,31 +117,6 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
|
||||
className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">{t("password")}</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={mode === "register" ? "至少 8 位" : "••••••••"}
|
||||
required
|
||||
minLength={mode === "register" ? 8 : 1}
|
||||
className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
{mode === "register" && (
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">{t("passwordConfirm")}</label>
|
||||
<input
|
||||
type="password"
|
||||
value={passwordConfirm}
|
||||
onChange={(e) => setPasswordConfirm(e.target.value)}
|
||||
placeholder="再次输入密码"
|
||||
required
|
||||
className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600 dark:bg-red-900/30 dark:text-red-400">{error}</p>
|
||||
)}
|
||||
@@ -146,41 +125,24 @@ export default function AuthModal({ isOpen, onClose, onSuccess }: AuthModalProps
|
||||
disabled={loading}
|
||||
className="w-full rounded-lg bg-[#ff4d4f] py-3 font-semibold text-white transition-colors hover:bg-[#ff3333] disabled:opacity-70"
|
||||
>
|
||||
{loading ? "处理中…" : mode === "login" ? t("login") : t("register")}
|
||||
{loading ? "处理中…" : t("submit")}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="mt-4 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
{mode === "login" ? (
|
||||
<>
|
||||
{t("noAccount")}{" "}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMode("register");
|
||||
setError(null);
|
||||
}}
|
||||
className="font-medium text-[#ff4d4f] hover:text-[#ff7a45]"
|
||||
>
|
||||
{t("signUpNow")}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{t("hasAccount")}{" "}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMode("login");
|
||||
setError(null);
|
||||
}}
|
||||
className="font-medium text-[#ff4d4f] hover:text-[#ff7a45]"
|
||||
>
|
||||
{t("goLogin")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
{GOOGLE_CLIENT_ID && (
|
||||
<>
|
||||
<div className="my-4 flex items-center gap-3">
|
||||
<div className="h-px flex-1 bg-gray-200 dark:bg-gray-700" />
|
||||
<span className="text-xs text-gray-400">or</span>
|
||||
<div className="h-px flex-1 bg-gray-200 dark:bg-gray-700" />
|
||||
</div>
|
||||
<GoogleLoginButton
|
||||
disabled={loading}
|
||||
onCredential={handleGoogleCredential}
|
||||
onError={setError}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
104
app/components/GoogleLoginButton.tsx
Normal file
104
app/components/GoogleLoginButton.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
google?: {
|
||||
accounts?: {
|
||||
id?: {
|
||||
initialize: (options: {
|
||||
client_id: string;
|
||||
callback: (response: { credential?: string }) => void;
|
||||
}) => void;
|
||||
renderButton: (
|
||||
parent: HTMLElement,
|
||||
options: {
|
||||
theme?: "outline" | "filled_blue" | "filled_black";
|
||||
size?: "large" | "medium" | "small";
|
||||
width?: number;
|
||||
text?: "signin_with" | "signup_with" | "continue_with" | "signin";
|
||||
shape?: "rectangular" | "pill" | "circle" | "square";
|
||||
}
|
||||
) => void;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const GOOGLE_SCRIPT_ID = "google-identity-services";
|
||||
const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || "";
|
||||
|
||||
function loadGoogleScript(): Promise<void> {
|
||||
if (typeof window === "undefined") return Promise.resolve();
|
||||
if (window.google?.accounts?.id) return Promise.resolve();
|
||||
const existing = document.getElementById(GOOGLE_SCRIPT_ID) as HTMLScriptElement | null;
|
||||
if (existing) {
|
||||
return new Promise((resolve, reject) => {
|
||||
existing.addEventListener("load", () => resolve(), { once: true });
|
||||
existing.addEventListener("error", () => reject(new Error("Google 登录加载失败")), { once: true });
|
||||
});
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
script.id = GOOGLE_SCRIPT_ID;
|
||||
script.src = "https://accounts.google.com/gsi/client";
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error("Google 登录加载失败"));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
export default function GoogleLoginButton({
|
||||
onCredential,
|
||||
onError,
|
||||
disabled = false,
|
||||
}: {
|
||||
onCredential: (credential: string) => void;
|
||||
onError?: (message: string) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!GOOGLE_CLIENT_ID || !ref.current) return;
|
||||
let cancelled = false;
|
||||
loadGoogleScript()
|
||||
.then(() => {
|
||||
if (cancelled || !ref.current || !window.google?.accounts?.id) return;
|
||||
ref.current.innerHTML = "";
|
||||
window.google.accounts.id.initialize({
|
||||
client_id: GOOGLE_CLIENT_ID,
|
||||
callback: (response) => {
|
||||
if (response.credential) onCredential(response.credential);
|
||||
else onError?.("Google 登录失败");
|
||||
},
|
||||
});
|
||||
window.google.accounts.id.renderButton(ref.current, {
|
||||
theme: "outline",
|
||||
size: "large",
|
||||
width: 304,
|
||||
text: "continue_with",
|
||||
shape: "rectangular",
|
||||
});
|
||||
setReady(true);
|
||||
})
|
||||
.catch((error) => onError?.(error instanceof Error ? error.message : "Google 登录加载失败"));
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [onCredential, onError]);
|
||||
|
||||
if (!GOOGLE_CLIENT_ID) return null;
|
||||
|
||||
return (
|
||||
<div className={disabled ? "pointer-events-none opacity-60" : ""}>
|
||||
<div ref={ref} className="flex min-h-10 justify-center" />
|
||||
{!ready && <div className="h-10 rounded-lg border border-gray-200 dark:border-gray-700" />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -150,9 +150,6 @@ export default function HeroSection() {
|
||||
(locale === "zh" ? "创建用户失败" : "Failed to create user")
|
||||
);
|
||||
}
|
||||
if (ensureData.is_new) {
|
||||
await fetch(apiUrl("/api/meetup/set-needs-password-change"), { method: "POST", credentials: "include" });
|
||||
}
|
||||
user_id = String(ensureData.user_id).trim();
|
||||
if (ensureData?.token && ensureData?.record) {
|
||||
await fetch(apiUrl("/api/auth/sync-session"), {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, type FormEvent } from "react";
|
||||
import { useCallback, useState, useEffect, type FormEvent } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useLocale } from "@/i18n/navigation";
|
||||
import {
|
||||
@@ -10,30 +10,67 @@ import {
|
||||
} from "@/app/lib/payment";
|
||||
import type { PayChannel, PayEnv } from "@/app/lib/payment";
|
||||
import { apiUrl } from "@/app/lib/api-client";
|
||||
import { googleLogin } from "@/app/lib/pocketbase";
|
||||
import GoogleLoginButton from "./GoogleLoginButton";
|
||||
|
||||
interface JoinModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
initialEmail?: string;
|
||||
/** 仅登录(已有 VIP 用户验证密码后直接登录,不跳转支付) */
|
||||
/** 仅登录(已有 VIP 用户直接邮箱登录,不跳转支付) */
|
||||
vipOnly?: boolean;
|
||||
}
|
||||
|
||||
const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || "";
|
||||
|
||||
export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly = false }: JoinModalProps) {
|
||||
const locale = useLocale();
|
||||
const [email, setEmail] = useState(initialEmail);
|
||||
const [password, setPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setEmail(initialEmail);
|
||||
setPassword("");
|
||||
setError(null);
|
||||
}
|
||||
}, [isOpen, initialEmail]);
|
||||
|
||||
const saveAuth = useCallback(async (token: string, record: Record<string, unknown>) => {
|
||||
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
|
||||
pbSaveAuth(token, record as { id: string; email: string; [key: string]: unknown });
|
||||
try {
|
||||
await fetch(apiUrl("/api/auth/sync-session"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token, record }),
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
/* local auth is already saved; backend cookie will be retried by the navbar */
|
||||
}
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent("auth:updated"));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const continueAfterAuth = useCallback((userId: string) => {
|
||||
if (vipOnly) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
const returnUrl = typeof window !== "undefined" ? `${window.location.origin}/${locale}/join/paid` : "/zh/join/paid";
|
||||
const env = getPayEnv();
|
||||
const channel: PayChannel = "wxpay";
|
||||
redirectToPay({
|
||||
user_id: userId,
|
||||
return_url: returnUrl,
|
||||
channel,
|
||||
device: getDeviceFromEnv(env),
|
||||
useJoinConfig: true,
|
||||
});
|
||||
}, [locale, onClose, vipOnly]);
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (loading) return;
|
||||
@@ -48,41 +85,15 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly
|
||||
const res = await fetch(apiUrl("/api/meetup/ensure-user"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email: em, password: password || undefined }),
|
||||
body: JSON.stringify({ email: em }),
|
||||
credentials: "include",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data?.ok) {
|
||||
throw new Error(data?.error || (locale === "zh" ? "操作失败" : "Operation failed"));
|
||||
}
|
||||
if (data.is_new) {
|
||||
await fetch(apiUrl("/api/meetup/set-needs-password-change"), { method: "POST", credentials: "include" });
|
||||
}
|
||||
const { pbSaveAuth } = await import("@/app/lib/pocketbase");
|
||||
pbSaveAuth(data.token, data.record);
|
||||
await fetch(apiUrl("/api/auth/sync-session"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: data.token, record: data.record }),
|
||||
credentials: "include",
|
||||
});
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent("auth:updated"));
|
||||
}
|
||||
if (vipOnly) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
const returnUrl = typeof window !== "undefined" ? `${window.location.origin}/${locale}/join/paid` : "/zh/join/paid";
|
||||
const env = getPayEnv();
|
||||
const channel: PayChannel = "wxpay";
|
||||
redirectToPay({
|
||||
user_id: data.user_id,
|
||||
return_url: returnUrl,
|
||||
channel,
|
||||
device: getDeviceFromEnv(env),
|
||||
useJoinConfig: true,
|
||||
});
|
||||
await saveAuth(data.token, data.record);
|
||||
continueAfterAuth(String(data.user_id));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "操作失败");
|
||||
} finally {
|
||||
@@ -90,6 +101,21 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoogleCredential = useCallback(async (credential: string) => {
|
||||
if (loading) return;
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await googleLogin(credential);
|
||||
await saveAuth(result.token, result.record);
|
||||
continueAfterAuth(result.record.id);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Google 登录失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [continueAfterAuth, loading, saveAuth]);
|
||||
|
||||
const [mounted, setMounted] = useState(false);
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
@@ -111,7 +137,7 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly
|
||||
</button>
|
||||
|
||||
<h2 className="text-xl font-bold text-gray-800 dark:text-gray-100">
|
||||
{vipOnly ? (locale === "zh" ? "验证密码登录" : "Verify password to login") : (locale === "zh" ? "加入游牧中国" : "Join Nomad China")}
|
||||
{vipOnly ? (locale === "zh" ? "邮箱登录" : "Email login") : (locale === "zh" ? "加入游牧中国" : "Join Nomad China")}
|
||||
</h2>
|
||||
|
||||
<form onSubmit={handleSubmit} className="mt-6 space-y-4">
|
||||
@@ -128,18 +154,6 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly
|
||||
className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{locale === "zh" ? "密码" : "Password"}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => { setPassword(e.target.value); setError(null); }}
|
||||
placeholder={locale === "zh" ? "请输入密码" : "Enter your password"}
|
||||
className="w-full rounded-lg border border-gray-200 px-4 py-2.5 text-gray-800 placeholder-gray-400 focus:border-[#ff4d4f] focus:outline-none focus:ring-1 focus:ring-[#ff4d4f] dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600 dark:bg-red-900/30 dark:text-red-400">{error}</p>
|
||||
)}
|
||||
@@ -151,6 +165,16 @@ export default function JoinModal({ isOpen, onClose, initialEmail = "", vipOnly
|
||||
{loading ? (locale === "zh" ? "处理中…" : "Processing…") : vipOnly ? (locale === "zh" ? "登录" : "Login") : (locale === "zh" ? "加入游牧中国 →" : "Join Nomad China →")}
|
||||
</button>
|
||||
</form>
|
||||
{GOOGLE_CLIENT_ID && (
|
||||
<>
|
||||
<div className="my-4 flex items-center gap-3">
|
||||
<div className="h-px flex-1 bg-gray-200 dark:bg-gray-700" />
|
||||
<span className="text-xs text-gray-400">or</span>
|
||||
<div className="h-px flex-1 bg-gray-200 dark:bg-gray-700" />
|
||||
</div>
|
||||
<GoogleLoginButton disabled={loading} onCredential={handleGoogleCredential} onError={setError} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user