Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
fix(web): keep auto login session
Sakura3140363cfafd
diff --git a/project/aitoearn-web/src/api/channels/channel.api.ts b/project/aitoearn-web/src/api/channels/channel.api.tsindex a01a178e..31528da2 100644--- a/project/aitoearn-web/src/api/channels/channel.api.ts+++ b/project/aitoearn-web/src/api/channels/channel.api.ts@@ -50,7 +50,6 @@ export function startChannelOAuthLoginApi(redirectUri: params?.redirectUri,inviteCode: params?.inviteCode,},- skipAuthLogout: true,})}@@ -61,7 +60,6 @@ export function startChannelOAuthLoginApi(*/export function getChannelPlatformsApi(options?: ChannelPlatformListOptions) {return http.get<PlatformMetadataVo[]>('v2/channels/platforms', undefined, true, {- skipAuthLogout: true,...(options?.fresh ? { cache: 'no-store' } : {}),})}diff --git a/project/aitoearn-web/src/app/[lng]/layout.tsx b/project/aitoearn-web/src/app/[lng]/layout.tsxindex 496f5722..ef6f18b4 100644--- a/project/aitoearn-web/src/app/[lng]/layout.tsx+++ b/project/aitoearn-web/src/app/[lng]/layout.tsx@@ -12,6 +12,8 @@ import { ChannelManager } from '@/components/ChannelManager'import { Providers } from '../layout/Providers'import '../globals.css'+export const dynamic = 'force-dynamic'+export async function generateMetadata({ params }: { params: Promise<{ lng: string }> }) {let { lng } = await paramsif (!languages.includes(lng))@@ -54,6 +56,7 @@ export default async function RootLayout({}>) {const { lng } = await paramsconst platformMetadata = await getPlatformMetadataInitialData()+ const autoLoginToken = process.env.AUTO_LOGIN_TOKEN?.trim() || undefinedreturn (<html lang={lng} dir={dir(lng)} suppressHydrationWarning>@@ -78,7 +81,7 @@ export default async function RootLayout({}}/><Script src="https://r.wdfl.co/rw.js" data-rewardful="ded70f" strategy="afterInteractive" />- <Providers lng={lng} platformMetadata={platformMetadata ?? []}>+ <Providers lng={lng} platformMetadata={platformMetadata ?? []} autoLoginToken={autoLoginToken}>{/* 全局频道管理弹框 */}<ChannelManager /><p className="hidden">Impact-Site-Verification: f9836212-462a-482f-9232-8a877970eacf</p>diff --git a/project/aitoearn-web/src/app/i18n/locales/de/common.json b/project/aitoearn-web/src/app/i18n/locales/de/common.jsonindex b6f3b044..88018658 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/common.json@@ -1,6 +1,5 @@{"profile": "Profil",- "logout": "Abmelden","unknownUser": "Unbekannter Benutzer","docs": "Dokumentation","login": "Anmelden",diff --git a/project/aitoearn-web/src/app/i18n/locales/de/settings.json b/project/aitoearn-web/src/app/i18n/locales/de/settings.jsonindex 911a3160..abf861fe 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/settings.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/settings.json@@ -16,7 +16,6 @@"profile": {"totalIncome": "Guthaben","currentBalance": "Aktuelles Guthaben",- "logout": "Abmelden","edit": "Bearbeiten","editName": "Spitznamen bearbeiten","changeAvatar": "Avatar ändern",diff --git a/project/aitoearn-web/src/app/i18n/locales/en/common.json b/project/aitoearn-web/src/app/i18n/locales/en/common.jsonindex 1655073c..3befb7ba 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/common.json@@ -1,6 +1,5 @@{"profile": "Profile",- "logout": "Logout","unknownUser": "Unknown User","docs": "Docs","login": "Login",diff --git a/project/aitoearn-web/src/app/i18n/locales/en/plugin.json b/project/aitoearn-web/src/app/i18n/locales/en/plugin.jsonindex 24d2ef30..8a3168ab 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/plugin.json@@ -127,7 +127,7 @@"permissionDescription": "Plugin is installed but requires necessary permissions to work properly. Please grant the required permissions in your browser extension settings.","siteAccessRequiredTitle": "Site access permission is required","siteAccessRequiredDescription": "Site access is not granted, so the extension cannot work on AiToEarn pages. You can fix it in either way:",- "siteAccessStepReauthorize": "Log out and authorize the extension again.",+ "siteAccessStepReauthorize": "Authorize the extension again.","siteAccessStepExtensionSettings": "Open your browser extension manager, find “AiToEarn Extension”, click “Details”, then set “Site access” to “On all sites”.","checkPermission": "Check Permission Again","sync": "Sync",diff --git a/project/aitoearn-web/src/app/i18n/locales/en/settings.json b/project/aitoearn-web/src/app/i18n/locales/en/settings.jsonindex 61692f44..fbaf8e77 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/settings.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/settings.json@@ -17,7 +17,6 @@"profile": {"totalIncome": "Balance","currentBalance": "Current Credits",- "logout": "Logout","edit": "Edit","editName": "Edit nickname","changeAvatar": "Change avatar",diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/common.json b/project/aitoearn-web/src/app/i18n/locales/fr/common.jsonindex 3db97603..ba607af6 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/common.json@@ -1,6 +1,5 @@{"profile": "Profil",- "logout": "Déconnexion","unknownUser": "Utilisateur inconnu","docs": "Documentation","login": "Connexion",diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/settings.json b/project/aitoearn-web/src/app/i18n/locales/fr/settings.jsonindex bdb87b54..40cd7a2e 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/settings.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/settings.json@@ -16,7 +16,6 @@"profile": {"totalIncome": "Solde","currentBalance": "Crédits actuels",- "logout": "Déconnexion","edit": "Modifier","editName": "Modifier le pseudo","changeAvatar": "Changer l'avatar",diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/common.json b/project/aitoearn-web/src/app/i18n/locales/ja/common.jsonindex 4234e5cd..a9f9cc3b 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/common.json@@ -1,6 +1,5 @@{"profile": "プロフィール",- "logout": "ログアウト","unknownUser": "不明なユーザー","docs": "ドキュメント","login": "ログイン",diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/settings.json b/project/aitoearn-web/src/app/i18n/locales/ja/settings.jsonindex f0a34169..55b20d2f 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/settings.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/settings.json@@ -16,7 +16,6 @@"profile": {"totalIncome": "残高","currentBalance": "現在のクレジット",- "logout": "ログアウト","edit": "編集","editName": "ニックネームを編集","changeAvatar": "アバターを変更",diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/common.json b/project/aitoearn-web/src/app/i18n/locales/ko/common.jsonindex 9629cffe..5c8f79f8 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/common.json@@ -1,6 +1,5 @@{"profile": "프로필",- "logout": "로그아웃","unknownUser": "알 수 없는 사용자","docs": "문서","login": "로그인",diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/settings.json b/project/aitoearn-web/src/app/i18n/locales/ko/settings.jsonindex 39dcf50d..49a202f3 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/settings.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/settings.json@@ -16,7 +16,6 @@"profile": {"totalIncome": "잔액","currentBalance": "현재 크레딧",- "logout": "로그아웃","edit": "편집","editName": "닉네임 편집","changeAvatar": "아바타 변경",diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.jsonindex 0f76a67a..c58f0496 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.json@@ -1,6 +1,5 @@{"profile": "个人中心",- "logout": "退出登录","unknownUser": "未知用户","docs": "帮助文档","login": "登录",diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.jsonindex 7886dff9..cb22e593 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.json@@ -127,7 +127,7 @@"permissionDescription": "插件已安装,但需要授予必需的权限才能正常使用。请在浏览器扩展设置中授权插件所需权限。","siteAccessRequiredTitle": "需要授予站点访问权限","siteAccessRequiredDescription": "当前未授予站点访问权限,插件无法在 AiToEarn 页面正常使用。你可以通过以下方式处理:",- "siteAccessStepReauthorize": "退出登录后重新授权插件。",+ "siteAccessStepReauthorize": "重新授权插件。","siteAccessStepExtensionSettings": "进入浏览器管理扩展,找到 “AiToEarn Extension”,点击 “详细信息”,在 “站点访问权限” 中选择 “在所有站点上”。","checkPermission": "重新检查权限","sync": "同步",diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/settings.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/settings.jsonindex bdabc4af..f195e14b 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/settings.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/settings.json@@ -17,7 +17,6 @@"profile": {"totalIncome": "累计收入","currentBalance": "当前余额",- "logout": "退出登录","edit": "编辑","editName": "编辑昵称","changeAvatar": "更换头像",diff --git a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsx b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsxindex 2fad8041..9d2151c5 100644--- a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsx+++ b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsx@@ -12,7 +12,6 @@ import {BookOpen,ChevronRight,FileText,- LogOut,ScrollText,Settings,Shield,@@ -109,14 +108,8 @@ function LoggedInMenuContent({}) {const { t } = useTransClient(['common'])const userInfo = useUserStore(state => state.userInfo)- const logout = useUserStore(state => state.logout)const starCount = useGitHubStars()- const handleLogout = () => {- logout()- onClose()- }-const handleOpenSettings = () => {onOpenSettings()onClose()@@ -194,18 +187,6 @@ function LoggedInMenuContent({<div data-testid="sidebar-settings-entry"><MenuItem icon={Settings} label={t('common:settings')} onClick={handleOpenSettings} /></div>-- <div className="my-1 h-px bg-border" />-- {/* 退出登录 */}- <div data-testid="sidebar-logout-entry">- <MenuItem- icon={LogOut}- label={t('common:logout')}- onClick={handleLogout}- className="text-destructive hover:bg-destructive/10 hover:text-destructive"- />- </div></div></>)diff --git a/project/aitoearn-web/src/app/layout/MobileNav/index.tsx b/project/aitoearn-web/src/app/layout/MobileNav/index.tsxindex 6ed69285..bf54257e 100644--- a/project/aitoearn-web/src/app/layout/MobileNav/index.tsx+++ b/project/aitoearn-web/src/app/layout/MobileNav/index.tsx@@ -4,14 +4,13 @@*/'use client'-import { LogOut, Settings } from 'lucide-react'+import { Settings } from 'lucide-react'import { useState } from 'react'import { useShallow } from 'zustand/react/shallow'import { useTransClient } from '@/app/i18n/client'import { useNavigationLogic } from '@/app/layout/shared'import { useChannelManagerStore } from '@/components/ChannelManager'import { useSettingsModalStore } from '@/store/settingsModal'-import { useUserStore } from '@/store/user'import { cn } from '@/utils/className'import { MobileBottomBar, MobileNavList, MobileTopBar } from './components'import { MobileUserSection } from './components/MobileUserSection'@@ -22,13 +21,6 @@ function MobileNav() {const { openSettings } = useSettingsModalStore()const { t } = useTransClient('common')- const { token, logout } = useUserStore(- useShallow(state => ({- token: state.token,- logout: state.logout,- })),- )-// 频道管理器const { openModal } = useChannelManagerStore(useShallow(state => ({@@ -43,11 +35,6 @@ function MobileNav() {const handleClose = () => setIsOpen(false)- const handleLogout = () => {- handleClose()- logout()- }-const actionItemClassName= 'flex w-full items-center gap-3 px-4 py-3 rounded-lg text-base font-medium text-muted-foreground transition-all hover:bg-brand-cyan/10 hover:text-brand-cyan cursor-pointer'@@ -105,23 +92,6 @@ function MobileNav() {</span><span>{t('settings')}</span></button>-- {/* 退出登录 - 仅登录时显示 */}- {token && (- <>- <div className="my-1 h-px bg-border" />- <button- onClick={handleLogout}- className={actionItemClassName}- data-testid="mobile-logout-btn"- >- <span className="flex items-center justify-center">- <LogOut size={20} />- </span>- <span>{t('logout')}</span>- </button>- </>- )}</div></div></div>diff --git a/project/aitoearn-web/src/app/layout/Providers.tsx b/project/aitoearn-web/src/app/layout/Providers.tsxindex eec3da70..57fb8da2 100644--- a/project/aitoearn-web/src/app/layout/Providers.tsx+++ b/project/aitoearn-web/src/app/layout/Providers.tsx@@ -9,7 +9,7 @@ import type { PlatformMetadataVo } from '@/api/channels/channel.types'import { GoogleOAuthProvider } from '@react-oauth/google'import { ThemeProvider } from 'next-themes'import { usePathname } from 'next/navigation'-import { createContext, useContext, useEffect, useLayoutEffect, useRef } from 'react'+import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react'import { useShallow } from 'zustand/shallow'import ConfigManagerDialog from '@/app/layout/ConfigManagerDialog'import LoginDialog from '@/app/layout/LoginDialog'@@ -35,15 +35,18 @@ export function Providers({children,lng,platformMetadata,+ autoLoginToken,}: {children: React.ReactNodelng: stringplatformMetadata: PlatformMetadataVo[]+ autoLoginToken?: string}) {const pathname = usePathname()const publicRoute = isPublicPage(pathname)// 用于追踪是否已经在当前路由弹出过登录框,避免重复弹出const hasPromptedRef = useRef(false)+ const [authInitialized, setAuthInitialized] = useState(false)const { _hasHydrated, token } = useUserStore(useShallow(state => ({@@ -75,8 +78,9 @@ export function Providers({return}- useUserStore.getState().appInit()- }, [_hasHydrated])+ useUserStore.getState().appInit(autoLoginToken)+ setAuthInitialized(true)+ }, [_hasHydrated, autoLoginToken])useEffect(() => {useUserStore.getState().setLang(lng)@@ -85,7 +89,7 @@ export function Providers({// 未登录用户访问非公开页面时,跳转到登录页useEffect(() => {// 等待持久化数据同步完成- if (!_hasHydrated) {+ if (!_hasHydrated || !authInitialized) {return}@@ -109,7 +113,7 @@ export function Providers({// 在当前页面弹出登录框,不跳转hasPromptedRef.current = trueuseLoginDialogStore.getState().openLoginDialog({ fromGuard: true })- }, [_hasHydrated, token, pathname, publicRoute])+ }, [_hasHydrated, authInitialized, token, pathname, publicRoute])// 拦截 @react-oauth/google 的脚本加载,添加 ?hl= 参数以设置按钮语言useLayoutEffect(() => {diff --git a/project/aitoearn-web/src/app/layout/SettingsModal/tabs/ProfileTab.tsx b/project/aitoearn-web/src/app/layout/SettingsModal/tabs/ProfileTab.tsxindex ce941e44..8afd3adc 100644--- a/project/aitoearn-web/src/app/layout/SettingsModal/tabs/ProfileTab.tsx+++ b/project/aitoearn-web/src/app/layout/SettingsModal/tabs/ProfileTab.tsx@@ -4,7 +4,7 @@'use client'-import { Camera, LogOut } from 'lucide-react'+import { Camera } from 'lucide-react'import { useRef, useState } from 'react'import { useShallow } from 'zustand/shallow'import { updateUserInfoApi } from '@/api/auth/auth.api'@@ -22,16 +22,15 @@ interface ProfileTabProps {onClose: () => void}-export function ProfileTab({ onClose }: ProfileTabProps) {+export function ProfileTab(_props: ProfileTabProps) {const { t } = useTransClient('settings')const { t: tCommon } = useTransClient('common')const fileInputRef = useRef<HTMLInputElement>(null)- const { userInfo, getUserInfo, logout } = useUserStore(+ const { userInfo, getUserInfo } = useUserStore(useShallow(state => ({userInfo: state.userInfo,getUserInfo: state.getUserInfo,- logout: state.logout,})),)@@ -141,12 +140,6 @@ export function ProfileTab({ onClose }: ProfileTabProps) {}}- const handleLogout = () => {- logout()- toast.success(tCommon('logout'))- onClose()- }-return (<div className="w-full space-y-6">{/* 用户信息卡片 */}@@ -247,16 +240,6 @@ export function ProfileTab({ onClose }: ProfileTabProps) {</a></div>- {/* 退出登录按钮 */}- <Button- variant="ghost"- className="h-11 w-full justify-center gap-2 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"- onClick={handleLogout}- >- <LogOut size={18} />- <span>{t('profile.logout')}</span>- </Button>-{/* 头像裁剪弹窗 */}<AvatarCropModalopen={cropModalOpen}diff --git a/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.ts b/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.tsindex 48e05661..3c7136da 100644--- a/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.ts+++ b/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.ts@@ -109,11 +109,6 @@ async function getAuthUrl(platform: PlatType, spaceId?: string): Promise<AuthUrltry {const res = await startChannelAccountAuthApi(platform, { groupId: spaceId })- if (res?.code === 1) {- useUserStore.getState().logout()- return null- }-if (res?.code === 0 && res.data?.url && res.data.sessionId) {return {url: res.data.url,@@ -154,11 +149,6 @@ async function checkAuthStatus(try {const res = await getChannelAccountAuthStatusApi(platform, sessionId)- if (res?.code === 1) {- useUserStore.getState().logout()- return null- }-if (res?.code === 0 && res.data) {return {status: res.data.status,diff --git a/project/aitoearn-web/src/store/user/index.ts b/project/aitoearn-web/src/store/user/index.tsindex 274b2a5c..90cb0fd5 100644--- a/project/aitoearn-web/src/store/user/index.ts+++ b/project/aitoearn-web/src/store/user/index.ts@@ -60,14 +60,6 @@ function getState(): IUserStore {return lodash.cloneDeep(state)}-function getDevelopmentAutoLoginToken() {- if (process.env.NODE_ENV !== 'development')- return undefined-- const token = process.env.NEXT_PUBLIC_AUTO_LOGIN_TOKEN?.trim()- return token || undefined-}-export const useUserStore = createPersistStore({...getState(),@@ -91,8 +83,7 @@ export const useUserStore = createPersistStore(setUserInfo(userInfo: UserInfo) {set({ userInfo })},- appInit() {- const autoLoginToken = getDevelopmentAutoLoginToken()+ appInit(autoLoginToken?: string) {if (!_get().token && autoLoginToken) {methods.setToken(autoLoginToken)}@@ -133,15 +124,6 @@ export const useUserStore = createPersistStore(setDefaultPlanId(planId: string | undefined) {set({ defaultPlanId: planId })},- clearLoginStatus() {- const hasEverLoggedIn = _get().hasEverLoggedIn- set({ ...getState(), hasEverLoggedIn })- useAccountStore.getState().clear()- },- logout() {- methods.clearLoginStatus()- window.location.href = '/'- },}return methodsdiff --git a/project/aitoearn-web/src/utils/request/client.ts b/project/aitoearn-web/src/utils/request/client.tsindex 0fcd7662..323013ec 100644--- a/project/aitoearn-web/src/utils/request/client.ts+++ b/project/aitoearn-web/src/utils/request/client.ts@@ -21,10 +21,9 @@ interface ApiErrorIssue {type RequestParamsWithSilent = RequestParams & {silent?: boolean // 是否静默处理错误,不显示提示authToken?: string // 临时指定本次请求使用的 token- skipAuthLogout?: boolean // 401/用户不存在时不触发全局登出}-export type RequestOptions = Pick<RequestParamsWithSilent, 'authToken' | 'skipAuthLogout' | 'cache'>+export type RequestOptions = Pick<RequestParamsWithSilent, 'authToken' | 'cache'>const fetchService = new FetchService({baseURL: `${process.env.NEXT_PUBLIC_API_URL}/`,@@ -157,22 +156,7 @@ export async function request<T>(params: RequestParamsWithSilent) {// 使用项目的静态翻译方法(只使用国际化字段,不再使用硬编码回退)const networkBusy = directTrans('common', 'networkBusy')- // 未登录拦截- if (data.code === 401 && (!useUserStore.getState().token || params.skipAuthLogout)) {- return data- }-- // 已登录、但是登录过期- if (data.code === 401) {- useUserStore.getState().logout()- return data- }-- // 用户未找到,登出- if (data.code === 12000) {- if (!params.skipAuthLogout) {- useUserStore.getState().logout()- }+ if (data.code === 401 || data.code === 12000) {return data}