Ver código fonte

✨ feat(auth): 实现用户认证系统

- 添加AuthProvider认证上下文提供器,管理登录状态
- 实现登录/登出功能及token管理
- 创建ProtectedRoute组件保护需要认证的路由

✨ feat(routing): 添加路由系统和页面组件

- 实现路由配置,支持页面导航和路由保护
- 添加NotFoundPage和ErrorPage错误处理页面
- 创建MainLayout布局组件

✨ feat(ui): 完善用户界面和交互功能

- 更新HomePage添加关注和粉丝导航按钮
- 实现UserProfilePage用户资料页面
- 完善FollowPage关注/粉丝管理页面
yourname 4 meses atrás
pai
commit
981d35ca53

+ 43 - 0
src/client/home/components/ErrorPage.tsx

@@ -0,0 +1,43 @@
+import React from 'react';
+import { useRouteError, useNavigate } from 'react-router';
+import { Alert, Button } from 'antd';
+
+export const ErrorPage = () => {
+  const navigate = useNavigate();
+  const error = useRouteError() as any;
+  const errorMessage = error?.statusText || error?.message || '未知错误';
+  
+  return (
+    <div className="flex flex-col items-center justify-center flex-grow p-4"
+    >
+      <div className="max-w-3xl w-full">
+        <h1 className="text-2xl font-bold mb-4">发生错误</h1>
+        <Alert 
+          type="error"
+          message={error?.message || '未知错误'}
+          description={
+            error?.stack ? (
+              <pre className="text-xs overflow-auto p-2 bg-gray-100 dark:bg-gray-800 rounded">
+                {error.stack}
+              </pre>
+            ) : null
+          }
+          className="mb-4"
+        />
+        <div className="flex gap-4">
+          <Button 
+            type="primary" 
+            onClick={() => navigate(0)}
+          >
+            重新加载
+          </Button>
+          <Button 
+            onClick={() => navigate('/admin')}
+          >
+            返回首页
+          </Button>
+        </div>
+      </div>
+    </div>
+  );
+};

+ 26 - 0
src/client/home/components/NotFoundPage.tsx

@@ -0,0 +1,26 @@
+import React from 'react';
+import { useNavigate } from 'react-router';
+import { Button } from 'antd';
+
+export const NotFoundPage = () => {
+  const navigate = useNavigate();
+  
+  return (
+    <div className="flex flex-col items-center justify-center flex-grow p-4">
+      <div className="max-w-3xl w-full">
+        <h1 className="text-2xl font-bold mb-4">404 - 页面未找到</h1>
+        <p className="mb-6 text-gray-600 dark:text-gray-300">
+          您访问的页面不存在或已被移除
+        </p>
+        <div className="flex gap-4">
+          <Button 
+            type="primary" 
+            onClick={() => navigate('/admin')}
+          >
+            返回首页
+          </Button>
+        </div>
+      </div>
+    </div>
+  );
+};

+ 37 - 0
src/client/home/components/ProtectedRoute.tsx

@@ -0,0 +1,37 @@
+import React, { useEffect } from 'react';
+import { 
+  useNavigate,
+} from 'react-router';
+import { useAuth } from '../hooks/AuthProvider';
+
+
+
+
+
+export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
+  const { isAuthenticated, isLoading } = useAuth();
+  const navigate = useNavigate();
+  
+  useEffect(() => {
+    // 只有在加载完成且未认证时才重定向
+    if (!isLoading && !isAuthenticated) {
+      navigate('/admin/login', { replace: true });
+    }
+  }, [isAuthenticated, isLoading, navigate]);
+  
+  // 显示加载状态,直到认证检查完成
+  if (isLoading) {
+    return (
+      <div className="flex justify-center items-center h-screen">
+        <div className="loader ease-linear rounded-full border-4 border-t-4 border-gray-200 h-12 w-12"></div>
+      </div>
+    );
+  }
+  
+  // 如果未认证且不再加载中,不显示任何内容(等待重定向)
+  if (!isAuthenticated) {
+    return null;
+  }
+  
+  return children;
+};

+ 140 - 0
src/client/home/hooks/AuthProvider.tsx

@@ -0,0 +1,140 @@
+import React, { useState, useEffect, createContext, useContext } from 'react';
+
+import {
+  useQuery,
+  useQueryClient,
+} from '@tanstack/react-query';
+import axios from 'axios';
+import 'dayjs/locale/zh-cn';
+import type {
+  AuthContextType
+} from '@/share/types';
+import { authClient } from '@/client/api';
+import type { InferResponseType, InferRequestType } from 'hono/client';
+
+type User = InferResponseType<typeof authClient.me.$get, 200>;
+
+
+// 创建认证上下文
+const AuthContext = createContext<AuthContextType<User> | null>(null);
+
+// 认证提供器组件
+export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+  const [user, setUser] = useState<User | null>(null);
+  const [token, setToken] = useState<string | null>(localStorage.getItem('token'));
+  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
+  const queryClient = useQueryClient();
+
+  // 声明handleLogout函数
+  const handleLogout = async () => {
+    try {
+      // 如果已登录,调用登出API
+      if (token) {
+        await authClient.logout.$post();
+      }
+    } catch (error) {
+      console.error('登出请求失败:', error);
+    } finally {
+      // 清除本地状态
+      setToken(null);
+      setUser(null);
+      setIsAuthenticated(false);
+      localStorage.removeItem('token');
+      // 清除Authorization头
+      delete axios.defaults.headers.common['Authorization'];
+      console.log('登出时已删除全局Authorization头');
+      // 清除所有查询缓存
+      queryClient.clear();
+    }
+  };
+
+  // 使用useQuery检查登录状态
+  const { isLoading } = useQuery({
+    queryKey: ['auth', 'status', token],
+    queryFn: async () => {
+      if (!token) {
+        setIsAuthenticated(false);
+        setUser(null);
+        return null;
+      }
+
+      try {
+        // 设置全局默认请求头
+        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
+        // 使用API验证当前用户
+        const res = await authClient.me.$get();
+        if (res.status !== 200) {
+          const result = await res.json();
+          throw new Error(result.message)
+        }
+        const currentUser = await res.json();
+        setUser(currentUser);
+        setIsAuthenticated(true);
+        return { isValid: true, user: currentUser };
+      } catch (error) {
+        return { isValid: false };
+      }
+    },
+    enabled: !!token,
+    refetchOnWindowFocus: false,
+    retry: false
+  });
+
+  const handleLogin = async (username: string, password: string, latitude?: number, longitude?: number): Promise<void> => {
+    try {
+      // 使用AuthAPI登录
+      const response = await authClient.login.$post({
+        json: {
+          username,
+          password
+        }
+      })
+      if (response.status !== 200) {
+        const result = await response.json()
+        throw new Error(result.message);
+      }
+
+      const result = await response.json()
+
+      // 保存token和用户信息
+      const { token: newToken, user: newUser } = result;
+
+      // 设置全局默认请求头
+      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
+
+      // 保存状态
+      setToken(newToken);
+      setUser(newUser);
+      setIsAuthenticated(true);
+      localStorage.setItem('token', newToken);
+
+    } catch (error) {
+      console.error('登录失败:', error);
+      throw error;
+    }
+  };
+
+  return (
+    <AuthContext.Provider
+      value={{
+        user,
+        token,
+        login: handleLogin,
+        logout: handleLogout,
+        isAuthenticated,
+        isLoading
+      }}
+    >
+      {children}
+    </AuthContext.Provider>
+  );
+};
+
+// 使用上下文的钩子
+export const useAuth = () => {
+  const context = useContext(AuthContext);
+  if (!context) {
+    throw new Error('useAuth必须在AuthProvider内部使用');
+  }
+  return context;
+};

+ 51 - 33
src/client/home/index.tsx

@@ -1,51 +1,69 @@
 import { createRoot } from 'react-dom/client'
 import { getGlobalConfig } from '../utils/utils'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { AuthProvider } from './hooks/AuthProvider'
+import { RouterProvider } from 'react-router-dom'
+import { router } from './routes'
 
 const Home = () => {
   return (
-    
+
     <div className="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
-    <div className="max-w-md w-full space-y-8">
-      {/* 系统介绍区域 */}
-      <div className="text-center">
-        <h1 className="text-4xl font-bold text-gray-900 mb-4">
-          {getGlobalConfig('APP_NAME')}
-        </h1>
-        <p className="text-lg text-gray-600 mb-8">
-          全功能应用Starter
-        </p>
-        <p className="text-base text-gray-500 mb-8">
-          这是一个基于Hono和React的应用Starter,提供了用户认证、文件管理、图表分析、地图集成和主题切换等常用功能。
-        </p>
-      </div>
+      <div className="max-w-md w-full space-y-8">
+        {/* 系统介绍区域 */}
+        <div className="text-center">
+          <h1 className="text-4xl font-bold text-gray-900 mb-4">
+            {getGlobalConfig('APP_NAME')}
+          </h1>
+          <p className="text-lg text-gray-600 mb-8">
+            全功能应用Starter
+          </p>
+          <p className="text-base text-gray-500 mb-8">
+            这是一个基于Hono和React的应用Starter,提供了用户认证、文件管理、图表分析、地图集成和主题切换等常用功能。
+          </p>
+        </div>
+
+        {/* 管理入口按钮 */}
+        <div className="space-y-4">
+          <a
+            href="/admin"
+            className="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-lg font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
+          >
+            进入管理后台
+          </a>
+
+          {/* 移动端入口按钮 */}
+          <a
+            href="/mobile"
+            className="w-full flex justify-center py-3 px-4 border border-blue-600 rounded-md shadow-sm text-lg font-medium text-blue-600 bg-white hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
+          >
+            进入移动端
+          </a>
 
-      {/* 管理入口按钮 */}
-      <div className="space-y-4">
-        <a
-          href="/admin"
-          className="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-lg font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
-        >
-          进入管理后台
-        </a>
-        
-        {/* 移动端入口按钮 */}
-        <a
-          href="/mobile"
-          className="w-full flex justify-center py-3 px-4 border border-blue-600 rounded-md shadow-sm text-lg font-medium text-blue-600 bg-white hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
-        >
-          进入移动端
-        </a>
-        
+        </div>
       </div>
     </div>
-  </div>
   )
 }
 
+// 创建QueryClient实例
+const queryClient = new QueryClient();
+
+// 应用入口组件
+const App = () => {
+  return (
+    <QueryClientProvider client={queryClient}>
+      <AuthProvider>
+        <RouterProvider router={router} />
+      </AuthProvider>
+    </QueryClientProvider>
+  )
+};
+
 const rootElement = document.getElementById('root')
 if (rootElement) {
   const root = createRoot(rootElement)
   root.render(
-    <Home />
+    <App />
   )
 }

+ 14 - 0
src/client/home/layouts/MainLayout.tsx

@@ -0,0 +1,14 @@
+import React, { useState, useEffect, useMemo } from 'react';
+import {
+  Outlet
+} from 'react-router';
+
+/**
+ * 主布局组件
+ * 包含侧边栏、顶部导航和内容区域
+ */
+export const MainLayout = () => {
+  return (
+    <Outlet />
+  );
+};

+ 1 - 1
src/client/home/pages/FollowPage.tsx

@@ -3,7 +3,7 @@ import { Layout, Card, List, Avatar, Button, Input, Typography, Spin, Empty } fr
 import { SearchOutlined, UserAddOutlined, UserDeleteOutlined } from '@ant-design/icons';
 import { useNavigate, useLocation } from 'react-router-dom';
 import { userClient } from '@/client/api';
-import { useAuth } from '@/client/admin/hooks/AuthProvider';
+import { useAuth } from '@/client/home/hooks/AuthProvider';
 import type { UserEntity } from '@/server/modules/users/user.entity';
 
 const { Content } = Layout;

+ 10 - 2
src/client/home/pages/HomePage.tsx

@@ -1,7 +1,8 @@
 import React, { useEffect, useState } from 'react';
 import { Layout, List, Card, Avatar, Button, Input, Space, Typography, Spin, Empty } from 'antd';
 import { UserOutlined, MessageOutlined, HeartOutlined, SendOutlined } from '@ant-design/icons';
-import { useAuth } from '@/client/admin/hooks/AuthProvider';
+import { useAuth } from '@/client/home/hooks/AuthProvider';
+import { useNavigate } from 'react-router-dom';
 import { postClient } from '@/client/api';
 import type { PostEntity } from '@/server/modules/posts/post.entity';
 
@@ -13,6 +14,7 @@ const HomePage: React.FC = () => {
   const [loading, setLoading] = useState(true);
   const [content, setContent] = useState('');
   const { user } = useAuth();
+  const navigate = useNavigate();
 
   // 获取首页内容流
   const fetchPosts = async () => {
@@ -78,7 +80,13 @@ const HomePage: React.FC = () => {
       <Header style={{ position: 'fixed', zIndex: 1, width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
         <Title level={3} style={{ color: 'white', margin: 0 }}>社交媒体平台</Title>
         <div style={{ display: 'flex', alignItems: 'center' }}>
-          <Avatar icon={<UserOutlined />} style={{ marginRight: 16 }} />
+          <Button type="text" style={{ color: 'white', marginRight: 16 }} onClick={() => navigate('/follow?type=following')}>
+            关注
+          </Button>
+          <Button type="text" style={{ color: 'white', marginRight: 16 }} onClick={() => navigate('/follow?type=followers')}>
+            粉丝
+          </Button>
+          <Avatar icon={<UserOutlined />} style={{ marginRight: 16 }} onClick={() => navigate(`/users/${user?.id}`)} />
           <Text style={{ color: 'white' }}>{user?.username}</Text>
         </div>
       </Header>

+ 1 - 2
src/client/home/pages/UserProfilePage.tsx

@@ -3,7 +3,7 @@ import { Layout, Card, Avatar, Button, Typography, List, Spin, Tabs, Divider, Ba
 import { UserOutlined, EditOutlined, HeartOutlined, UserAddOutlined, UserDeleteOutlined } from '@ant-design/icons';
 import { useParams, useNavigate } from 'react-router-dom';
 import { userClient } from '@/client/api';
-import { useAuth } from '@/client/admin/hooks/AuthProvider';
+import { useAuth } from '@/client/home/hooks/AuthProvider';
 import type { UserEntity } from '@/server/modules/users/user.entity';
 
 const { Content } = Layout;
@@ -11,7 +11,6 @@ const { Title, Text, Paragraph } = Typography;
 const { TabPane } = Tabs;
 
 const UserProfilePage: React.FC = () => {
-    return null;
   const [user, setUser] = useState<UserEntity | null>(null);
   const [loading, setLoading] = useState(true);
   const [isFollowing, setIsFollowing] = useState(false);

+ 55 - 0
src/client/home/routes.tsx

@@ -0,0 +1,55 @@
+import React from 'react';
+import { createBrowserRouter, Navigate } from 'react-router';
+import { ProtectedRoute } from './components/ProtectedRoute';
+import { ErrorPage } from './components/ErrorPage';
+import { NotFoundPage } from './components/NotFoundPage';
+import HomePage from './pages/HomePage';
+import LoginPage from './pages/LoginPage';
+import { MainLayout } from './layouts/MainLayout';
+import UserProfilePage from './pages/UserProfilePage';
+import FollowPage from './pages/FollowPage';
+
+export const router = createBrowserRouter([
+  {
+    path: '/',
+    element: <HomePage />
+  },
+  {
+    path: '/login',
+    element: <LoginPage />
+  },
+  {
+    path: '/admin',
+    element: (
+      <ProtectedRoute>
+        <MainLayout />
+      </ProtectedRoute>
+    ),
+    children: [
+      // {
+      //   index: true,
+      //   element: <Navigate to="/admin/dashboard" />
+      // },
+      {
+        path: 'follow',
+        element: <FollowPage />,
+        errorElement: <ErrorPage />
+      },
+      {
+        path: 'users/:id',
+        element: <UserProfilePage />,
+        errorElement: <ErrorPage />
+      },
+      {
+        path: '*',
+        element: <NotFoundPage />,
+        errorElement: <ErrorPage />
+      },
+    ],
+  },
+  {
+    path: '*',
+    element: <NotFoundPage />,
+    errorElement: <ErrorPage />
+  },
+]);