refactor(auth): unify Facebook and Google login into AuthPlatform class

Replace the separate FacebookLogin and GoogleLogin classes with a single
AuthPlatform class that takes a provider name ("facebook" | "google") as a
constructor argument. This consolidates duplicate OAuth sign-in logic behind
one entry point while preserving the existing NextAuth flow.

- Add new src/lib/auth/auth_platform.ts exporting AuthPlatform and
  AuthProvider type
- Update auth-facebook-panel.tsx and splash-button.tsx to use the new API
- Rename initialContext → initialState in the auth machine for consistency
- Update inline docs and comments to reference AuthPlatform

No behavioral change for end users; both providers still route through
NextAuth's signIn() with the same callbacks and cookies.
This commit is contained in:
2026-06-10 18:58:15 +08:00
parent 744e23fc29
commit 47591be41c
30 changed files with 111 additions and 117 deletions
@@ -7,13 +7,13 @@
* 视觉规格(与 Dart 对齐):
* - Spacer → logo120h)→ Spacer → Facebook 主按钮 → 链接 → Spacer → 法律
* - Facebook 主按钮:46px 白胶囊 + Facebook "f" 图标(#1877f2+ "Login with Facebook"
* - 社交登录走 NextAuth`new FacebookLogin().signIn()` / `new GoogleLogin().signIn()`
* - 社交登录走 NextAuth`new AuthPlatform("facebook").signIn()` / `new AuthPlatform("google").signIn()`
* - "Other Sign-in Options" 链接打开底部弹层
* - 弹层 Email 按钮 → 触发 `onSwitchToEmail`(父级派发 `AuthPanelModeChanged`
*/
import { useState } from "react";
import { FacebookLogin, GoogleLogin } from "@/lib/auth/nextauth";
import { AuthPlatform } from "@/lib/auth/nextauth";
import { AuthErrorMessage } from "./auth-error-message";
import { AuthLegalText } from "./auth-legal-text";
@@ -33,7 +33,7 @@ export function AuthFacebookPanel({ onSwitchToEmail }: AuthFacebookPanelProps) {
setBusy("facebook");
setError(null);
try {
await new FacebookLogin().signIn();
await new AuthPlatform("facebook").signIn();
} catch (e) {
setError(e instanceof Error ? e.message : "Facebook login failed");
} finally {
@@ -45,7 +45,7 @@ export function AuthFacebookPanel({ onSwitchToEmail }: AuthFacebookPanelProps) {
setBusy("google");
setError(null);
try {
await new GoogleLogin().signIn();
await new AuthPlatform("google").signIn();
} catch (e) {
setError(e instanceof Error ? e.message : "Google login failed");
} finally {
+3 -3
View File
@@ -11,7 +11,7 @@
* - 消费 `useChatDispatch` / `useUserDispatch`(登录成功后初始化)
* - 自管路由跳转(已登录 / 登录成功 → /chat)
* - Skip 用 `<Link>` 保留 SPA 体验
* - 社交登录按钮走 `new FacebookLogin().signIn()`NextAuth 流程)
* - 社交登录按钮走 `new AuthPlatform("facebook").signIn()`NextAuth 流程)
*/
import Link from "next/link";
import { useRouter } from "next/navigation";
@@ -20,7 +20,7 @@ import { useEffect, useRef } from "react";
import { useAuthState } from "@/stores/auth/auth-context";
import { useChatDispatch } from "@/stores/chat/chat-context";
import { useUserDispatch } from "@/stores/user/user-context";
import { FacebookLogin } from "@/lib/auth/nextauth";
import { AuthPlatform } from "@/lib/auth/nextauth";
import { ROUTES } from "@/router/routes";
import { LoadingIndicator } from "@/app/_components/core/loading-indicator";
import styles from "./splash-button.module.css";
@@ -53,7 +53,7 @@ export function SplashButton() {
const handleFacebookLogin = async () => {
try {
await new FacebookLogin().signIn();
await new AuthPlatform("facebook").signIn();
} catch (e) {
console.error("[splash-button] Facebook login failed", e);
}
+31
View File
@@ -0,0 +1,31 @@
"use client";
/**
* AuthPlatform 统一 OAuth 登录入口
*
* 合并自原 FacebookLogin / GoogleLogin 两个类。
* 构造时传入 provider 名,调用 signIn() 触发 NextAuth OAuth 流程。
*
* 用法:
* await new AuthPlatform("facebook").signIn()
* await new AuthPlatform("google").signIn()
*
* NextAuth 流程:
* 1. NextAuth 重定向到 provider OAuth 授权页
* 2. 用户授权 → 回调 /api/auth/callback/{provider}
* 3. NextAuth 写 next-auth.session-token (httpOnly) cookie
* 4. 重定向到 callbackUrl (默认 /chat)
*
* **不**做任何持久化(不写 unstorage / 不调后端 / 不设自定义 cookie)。
* 原始 Dart: nextauth-helpers.{facebookLogin, googleLogin}()
*/
import { signIn } from "next-auth/react";
export type AuthProvider = "facebook" | "google";
export class AuthPlatform {
constructor(private readonly provider: AuthProvider) {}
async signIn(): Promise<void> {
await signIn(this.provider);
}
}
-20
View File
@@ -1,20 +0,0 @@
"use client";
/**
* Facebook 登录(NextAuth OAuth 流程触发器)
*
* 调用 `signIn("facebook")` 触发 NextAuth 的 OAuth 流程:
* 1. NextAuth 重定向到 Facebook OAuth 授权页
* 2. 用户授权 → Facebook 回调 /api/auth/callback/facebook
* 3. NextAuth 写 `next-auth.session-token` (httpOnly) cookie
* 4. 重定向到 callbackUrl (默认 /chat)
*
* **不**做任何持久化(不写 unstorage / 不调后端 / 不设自定义 cookie)。
* 原始 Dart: nextauth-helpers.facebookLogin()
*/
import { signIn } from "next-auth/react";
export class FacebookLogin {
async signIn(): Promise<void> {
await signIn("facebook");
}
}
-20
View File
@@ -1,20 +0,0 @@
"use client";
/**
* Google 登录(NextAuth OAuth 流程触发器)
*
* 调用 `signIn("google")` 触发 NextAuth 的 OAuth 流程:
* 1. NextAuth 重定向到 Google OAuth 授权页
* 2. 用户授权 → Google 回调 /api/auth/callback/google
* 3. NextAuth 写 `next-auth.session-token` (httpOnly) cookie
* 4. 重定向到 callbackUrl (默认 /chat)
*
* **不**做任何持久化(不写 unstorage / 不调后端 / 不设自定义 cookie)。
* 原始 Dart: nextauth-helpers.googleLogin()
*/
import { signIn } from "next-auth/react";
export class GoogleLogin {
async signIn(): Promise<void> {
await signIn("google");
}
}
+4 -5
View File
@@ -2,14 +2,14 @@
* NextAuth v4 配置(单一来源)
*
* 极简模式:参考 `auth.js` 官方示例的**精神**(不做任何持久化),但保留 v4 语法:
* - 客户端点击登录按钮 → `new GoogleLogin().signIn()` / `new FacebookLogin().signIn()`
* - 客户端点击登录按钮 → `new AuthPlatform("google").signIn()` / `new AuthPlatform("facebook").signIn()`
* - NextAuth 重定向到 Google / Facebook OAuth
* - OAuth 回调 → NextAuth 写 `next-auth.session-token` (httpOnly) cookie
* - 重定向到 callbackUrl (默认 /chat)
* - 业务 token 持久化(unstorage / 后端 / 自定义 cookie**全部不在本轮 scope**
*
* 导出 `GET` / `POST` 给 `src/app/api/auth/[...nextauth]/route.ts` 引用。
* 客户端通过 `src/lib/auth/{google_login,facebook_login,logout,auth_gate}.ts` 触发。
* 客户端通过 `src/lib/auth/{auth_platform,logout}.ts` 触发。
*/
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
@@ -43,8 +43,7 @@ export { handler as GET, handler as POST };
// 每个 class 一个独立文件,详见同目录的子模块。
// 这里 re-export 仅为消费者提供 `@/lib/auth/nextauth` 单点导入。
// 注:上方 `next-auth` 是 server-only,本文件编译时会被 Next.js 切分到 server bundle
// 客户端 import `GoogleLogin` / `FacebookLogin` / `Logout` 时不会拉入。
// 客户端 import `AuthPlatform` / `Logout` 时不会拉入。
// ============================================================
export { GoogleLogin } from "./google_login";
export { FacebookLogin } from "./facebook_login";
export { AuthPlatform, type AuthProvider } from "./auth_platform";
export { Logout } from "./logout";
@@ -1,11 +1,11 @@
/**
* Auth Context +
* Auth State +
*/
import type { AuthMode } from "@/models/auth/auth-mode";
import type { AuthPanelMode } from "@/models/auth/auth-panel-mode";
import type { LoginType } from "@/models/auth/login-type";
export interface AuthContext {
export interface AuthState {
/** 当前面板模式(Facebook / Email */
authPanelMode: AuthPanelMode;
/** 内部登录模式(login / register */
@@ -18,7 +18,7 @@ export interface AuthContext {
loginType: LoginType;
}
export const initialContext: AuthContext = {
export const initialState: AuthState = {
authPanelMode: "facebook",
authMode: "login",
email: "",
+1 -1
View File
@@ -7,4 +7,4 @@
* - Context 形状与初始值由 `auth-context.ts` 导出
* - `AuthState` 由 `auth-context.tsx` 导出(保持原 API 兼容)
*/
export type { AuthEvent } from "./auth-events";
export type { AuthEvent } from "./machine/auth-events";
+3 -2
View File
@@ -6,7 +6,8 @@
* - 事件联合位于 auth-events.ts
* - machine / 类型 / React 入口分别由对应文件导出
*/
export * from "./auth-state";
export * from "./auth-context";
export * from "./auth-events";
export * from "./auth-machine";
export * from "./machine/auth-events";
export * from "./machine/auth-machine";
export * from "./auth-types";
@@ -18,12 +18,12 @@ import {
import { useMachine } from "@xstate/react";
import { authMachine } from "./auth-machine";
import type { AuthEvent, AuthContext as MachineContext } from "./auth-machine";
import type { AuthEvent, AuthState as MachineContext } from "./auth-machine";
/**
* State AuthState
*/
export interface AuthState {
interface AuthState {
authPanelMode: MachineContext["authPanelMode"];
authMode: MachineContext["authMode"];
email: string;
@@ -4,8 +4,8 @@
* Dart: lib/ui/auth/bloc/auth_bloc.dart + auth_state.dart + auth_event.dart
*
* NextAuth `@/lib/auth/nextauth`
* / + reset `new GoogleLogin().signIn()` /
* `new FacebookLogin().signIn()`
* / + reset `new AuthPlatform("google").signIn()` /
* `new AuthPlatform("facebook").signIn()`
*/
import { setup, fromPromise, assign } from "xstate";
@@ -14,12 +14,12 @@ import { authRepository } from "@/data/repositories/auth_repository";
import { AuthStorage } from "@/data/storage/auth/auth_storage";
import { Result } from "@/utils/result";
import { AuthContext, initialContext } from "./auth-context";
import { AuthState, initialState } from "../auth-state";
import type { AuthEvent } from "./auth-events";
// 重新导出 Context / Event 类型,保持 machine 文件的公共 API 不变
export type { AuthContext } from "./auth-context";
export { initialContext } from "./auth-context";
// 重新导出 State / Event 类型,保持 machine 文件的公共 API 不变
export type { AuthState } from "../auth-state";
export { initialState } from "../auth-state";
export type { AuthEvent } from "./auth-events";
// ============================================================
@@ -73,7 +73,7 @@ const emailRegisterThenLoginActor = fromPromise<
// ============================================================
export const authMachine = setup({
types: {
context: {} as AuthContext,
context: {} as AuthState,
events: {} as AuthEvent,
},
actors: {
@@ -83,7 +83,7 @@ export const authMachine = setup({
}).createMachine({
id: "auth",
initial: "idle",
context: initialContext,
context: initialState,
states: {
idle: {
on: {
@@ -109,11 +109,11 @@ export const authMachine = setup({
}),
},
AuthReset: {
actions: assign(() => initialContext),
actions: assign(() => initialState),
},
AuthEmailLoginSubmitted: "loadingEmailLogin",
AuthEmailRegisterSubmitted: "loadingEmailRegister",
// 社交登录已迁移到 NextAuth + GoogleLogin / FacebookLogin
// 社交登录已迁移到 NextAuth + AuthPlatform
// 状态机保留事件以兼容旧调用方(实际不再触发)
AuthGoogleLoginSubmitted: {},
AuthFacebookLoginSubmitted: {},
+3 -3
View File
@@ -20,13 +20,13 @@ import {
} from "react";
import { useMachine } from "@xstate/react";
import { chatMachine } from "./chat-machine";
import type { ChatEvent, ChatContext as MachineContext } from "./chat-machine";
import { chatMachine } from "./machine/chat-machine";
import type { ChatEvent, ChatState as MachineContext } from "./machine/chat-machine";
/**
* 对外暴露的 State 形状(保持与原 ChatState 兼容)
*/
export interface ChatState {
interface ChatState {
messages: MachineContext["messages"];
isReplyingAI: boolean;
isGuest: boolean;
+1 -1
View File
@@ -8,5 +8,5 @@
* - `ChatState` 由 `chat-context.tsx` 导出(保持原 API 兼容)
* - `GuestChatQuota` 仍由 `chat-machine.ts` 导出(业务常量,与上下文配对紧密)
*/
export type { ChatEvent } from "./chat-events";
export type { ChatEvent } from "./machine/chat-events";
export { GuestChatQuota } from "./chat-machine";
+2 -1
View File
@@ -11,7 +11,8 @@
* 注:chat-side-effects.ts 暂未删除(其中 WebSocket 长生命周期逻辑
* 待下一轮迁移到 fromCallback actor)。
*/
export * from "./machine/chat-state";
export * from "./chat-context";
export * from "./chat-events";
export * from "./machine/chat-events";
export * from "./chat-types";
export { chatMachine } from "./chat-machine";
@@ -23,8 +23,8 @@ import { AuthStorage } from "@/data/storage/auth/auth_storage";
import { formatDate } from "@/utils/date";
import { Result } from "@/utils/result";
import { ChatContext, initialContext } from "./chat-context";
import type { ChatEvent } from "./chat-events";
import { ChatState, initialState } from "./chat-state";
import type { ChatEvent } from "./machine/chat-events";
/** 游客配额阈值(与 Dart `GuestChatQuota` 保持一致) */
export const GuestChatQuota = {
@@ -32,10 +32,10 @@ export const GuestChatQuota = {
quotaExhausted: 0,
} as const;
// 重新导出 Context / Event 类型,保持 machine 文件的公共 API 不变
export type { ChatContext } from "./chat-context";
export { initialContext } from "./chat-context";
export type { ChatEvent } from "./chat-events";
// 重新导出 State / Event 类型,保持 machine 文件的公共 API 不变
export type { ChatState } from "./chat-state";
export { initialState } from "./chat-state";
export type { ChatEvent } from "./machine/chat-events";
// ============================================================
// Helpers
@@ -146,7 +146,7 @@ const loadMoreHistoryActor = fromPromise<
// ============================================================
export const chatMachine = setup({
types: {
context: {} as ChatContext,
context: {} as ChatState,
events: {} as ChatEvent,
},
actors: {
@@ -230,7 +230,7 @@ export const chatMachine = setup({
}).createMachine({
id: "chat",
initial: "idle",
context: initialContext,
context: initialState,
states: {
idle: {
on: {
@@ -1,11 +1,11 @@
/**
* Chat Context +
* Chat State +
*
* GuestChatQuota chat-machine.ts
*/
import type { UiMessage } from "@/models/chat/ui-message";
export interface ChatContext {
export interface ChatState {
messages: UiMessage[];
isReplyingAI: boolean;
isGuest: boolean;
@@ -17,7 +17,7 @@ export interface ChatContext {
historyOffset: number;
}
export const initialContext: ChatContext = {
export const initialState: ChatState = {
messages: [],
isReplyingAI: false,
isGuest: true,
+2 -1
View File
@@ -8,7 +8,8 @@
* - Context 形状与初始值位于 sidebar-context.ts
* - 事件联合位于 sidebar-events.ts
*/
export * from "./sidebar-state";
export * from "./sidebar-context";
export * from "./sidebar-events";
export * from "./sidebar-types";
export { sidebarMachine } from "./sidebar-machine";
export { sidebarMachine } from "./machine/sidebar-machine";
@@ -11,7 +11,7 @@
*/
import { setup, assign } from "xstate";
import { SidebarContext, initialContext } from "./sidebar-context";
import { SidebarState, initialState } from "../sidebar-state";
import type { SidebarEvent } from "./sidebar-events";
/**
@@ -36,9 +36,9 @@ export const BottomNavItem = {
export type BottomNavItem = (typeof BottomNavItem)[keyof typeof BottomNavItem];
// 重新导出 Context / Event 类型,保持 machine 文件的公共 API 不变
export type { SidebarContext } from "./sidebar-context";
export { initialContext } from "./sidebar-context";
// 重新导出 State / Event 类型,保持 machine 文件的公共 API 不变
export type { SidebarState } from "../sidebar-state";
export { initialState } from "../sidebar-state";
export type { SidebarEvent } from "./sidebar-events";
// ============================================================
@@ -46,7 +46,7 @@ export type { SidebarEvent } from "./sidebar-events";
// ============================================================
export const sidebarMachine = setup({
types: {
context: {} as SidebarContext,
context: {} as SidebarState,
events: {} as SidebarEvent,
},
actions: {
@@ -73,7 +73,7 @@ export const sidebarMachine = setup({
}).createMachine({
id: "sidebar",
initial: "idle",
context: initialContext,
context: initialState,
states: {
/**
* Sidebar idle
@@ -1,18 +1,18 @@
/**
* Sidebar Context +
* Sidebar State +
*
* SidebarPage / BottomNavItem sidebar-machine.ts /
*/
import { SidebarPage, BottomNavItem } from "./sidebar-machine";
import { SidebarPage, BottomNavItem } from "./machine/sidebar-machine";
export interface SidebarContext {
export interface SidebarState {
currentPage: SidebarPage;
selectedBottomNavItem: BottomNavItem;
characterName: string;
characterProgress: number;
}
export const initialContext: SidebarContext = {
export const initialState: SidebarState = {
currentPage: SidebarPage.DefaultView,
selectedBottomNavItem: BottomNavItem.None,
characterName: "Luna",
+4 -4
View File
@@ -17,16 +17,16 @@ import {
} from "react";
import { useMachine } from "@xstate/react";
import { sidebarMachine } from "./sidebar-machine";
import { sidebarMachine } from "./machine/sidebar-machine";
import type {
SidebarContext as MachineContext,
SidebarState as MachineContext,
SidebarEvent,
} from "./sidebar-machine";
} from "./machine/sidebar-machine";
/**
* 对外暴露的 State 形状(保持与原 SidebarState 兼容)
*/
export interface SidebarState {
interface SidebarState {
currentPage: MachineContext["currentPage"];
selectedBottomNavItem: MachineContext["selectedBottomNavItem"];
characterName: string;
+1 -1
View File
@@ -8,5 +8,5 @@
* - Context 形状由 `sidebar-context.ts` 导出
* - SidebarState 由 `sidebar-context.tsx` 导出(保持原 API 兼容)
*/
export { SidebarPage, BottomNavItem } from "./sidebar-machine";
export { SidebarPage, BottomNavItem } from "./machine/sidebar-machine";
export type { SidebarEvent } from "./sidebar-events";
+2 -1
View File
@@ -8,7 +8,8 @@
* - Context 形状与初始值位于 user-context.ts
* - 事件联合位于 user-events.ts
*/
export * from "./machine/user-state";
export * from "./user-context";
export * from "./user-events";
export * from "./machine/user-events";
export * from "./user-types";
export { userMachine } from "./user-machine";
@@ -17,13 +17,13 @@ import { authRepository } from "@/data/repositories/auth_repository";
import { UserStorage } from "@/data/storage/user/user_storage";
import { Result } from "@/utils/result";
import { UserContext, initialContext } from "./user-context";
import type { UserEvent } from "./user-events";
import { UserState, initialState } from "./machine/user-state";
import type { UserEvent } from "./machine/user-events";
// 重新导出 Context / Event 类型,保持 machine 文件的公共 API 不变
export type { UserContext } from "./user-context";
export { initialContext } from "./user-context";
export type { UserEvent } from "./user-events";
// 重新导出 State / Event 类型,保持 machine 文件的公共 API 不变
export type { UserState } from "./machine/user-state";
export { initialState } from "./machine/user-state";
export type { UserEvent } from "./machine/user-events";
// ============================================================
// Helpers
@@ -102,7 +102,7 @@ const userLogoutActor = fromPromise<void>(async () => {
// ============================================================
export const userMachine = setup({
types: {
context: {} as UserContext,
context: {} as UserState,
events: {} as UserEvent,
},
actors: {
@@ -136,7 +136,7 @@ export const userMachine = setup({
}).createMachine({
id: "user",
initial: "idle",
context: initialContext,
context: initialState,
states: {
idle: {
on: {
@@ -1,9 +1,9 @@
/**
* User Context +
* User State +
*/
import type { UserView } from "@/models/user/user";
export interface UserContext {
export interface UserState {
currentUser: UserView | null;
pronouns: string;
coinBalance: number;
@@ -11,7 +11,7 @@ export interface UserContext {
avatarUrl: string | null;
}
export const initialContext: UserContext = {
export const initialState: UserState = {
currentUser: null,
pronouns: "He",
coinBalance: 45,
+2 -2
View File
@@ -18,12 +18,12 @@ import {
import { useMachine } from "@xstate/react";
import { userMachine } from "./user-machine";
import type { UserContext as MachineContext, UserEvent } from "./user-machine";
import type { UserState as MachineContext, UserEvent } from "./user-machine";
/**
* 对外暴露的 State 形状(保持与原 UserState 兼容)
*/
export interface UserState {
interface UserState {
currentUser: MachineContext["currentUser"];
pronouns: string;
coinBalance: number;
+1 -1
View File
@@ -7,4 +7,4 @@
* - Context 形状与初始值由 `user-context.ts` 导出
* - `UserState` 由 `user-context.tsx` 导出(保持原 API 兼容)
*/
export type { UserEvent } from "./user-events";
export type { UserEvent } from "./machine/user-events";