feat: port user profile feature from upstream
- GET /api/users?username= filter (admin) - GET /api/posts?user_id= filter - Add UserProfile page (profile card + user's posts), reachable via ?user=<username> - Clickable usernames on feed, post detail, replies
This commit is contained in:
1 parent
e6ba5507ae
commit
5ef8d4b1ff
9 files changed
+166
-17
No files matched your search
+12
-4
@@ -1,12 +1,14 @@
|
|||||||
// GET /api/posts, POST /api/posts
|
// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= 筛选
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser } from '@/lib/auth';
|
import { getUser } from '@/lib/auth';
|
||||||
|
|
||||||
export async function GET(req) {
|
export async function GET(req) {
|
||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
||||||
|
const userId = url.searchParams.get('user_id');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const r = await pool.query(`
|
let query = `
|
||||||
SELECT
|
SELECT
|
||||||
p.*,
|
p.*,
|
||||||
u.username,
|
u.username,
|
||||||
@@ -14,8 +16,14 @@ export async function GET(req) {
|
|||||||
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
|
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
|
||||||
FROM posts p
|
FROM posts p
|
||||||
JOIN users u ON p.user_id = u.id
|
JOIN users u ON p.user_id = u.id
|
||||||
ORDER BY ${sort} DESC
|
`;
|
||||||
`);
|
const params = [];
|
||||||
|
if (userId) {
|
||||||
|
query += ' WHERE p.user_id = $1';
|
||||||
|
params.push(userId);
|
||||||
|
}
|
||||||
|
query += ` ORDER BY ${sort} DESC`;
|
||||||
|
const r = await pool.query(query, params);
|
||||||
return Response.json(r.rows);
|
return Response.json(r.rows);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
|||||||
+13
-4
@@ -1,4 +1,4 @@
|
|||||||
// GET /api/users (admin)
|
// GET /api/users (admin) — 支持 ?username= 按用户名查询
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser, requireAdmin } from '@/lib/auth';
|
import { getUser, requireAdmin } from '@/lib/auth';
|
||||||
|
|
||||||
@@ -6,10 +6,19 @@ export async function GET(req) {
|
|||||||
const user = getUser(req);
|
const user = getUser(req);
|
||||||
const forbidden = await requireAdmin(user);
|
const forbidden = await requireAdmin(user);
|
||||||
if (forbidden) return forbidden;
|
if (forbidden) return forbidden;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const username = url.searchParams.get('username');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const r = await pool.query(
|
let query = 'SELECT id, username, avatar_url, bio, role, created_at FROM users';
|
||||||
'SELECT id, username, avatar_url, bio, role, created_at FROM users ORDER BY created_at DESC'
|
const params = [];
|
||||||
);
|
if (username) {
|
||||||
|
query += ' WHERE username = $1';
|
||||||
|
params.push(username);
|
||||||
|
}
|
||||||
|
query += ' ORDER BY created_at DESC';
|
||||||
|
const r = await pool.query(query, params);
|
||||||
return Response.json(r.rows);
|
return Response.json(r.rows);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
|
|||||||
+3
-1
@@ -10,10 +10,11 @@ import PostDetail from '@/components/PostDetail';
|
|||||||
import NewPost from '@/components/NewPost';
|
import NewPost from '@/components/NewPost';
|
||||||
import AdminPage from '@/components/AdminPage';
|
import AdminPage from '@/components/AdminPage';
|
||||||
import SettingsPage from '@/components/SettingsPage';
|
import SettingsPage from '@/components/SettingsPage';
|
||||||
|
import UserProfile from '@/components/UserProfile';
|
||||||
import Modals from '@/components/Modals';
|
import Modals from '@/components/Modals';
|
||||||
|
|
||||||
function HomeInner() {
|
function HomeInner() {
|
||||||
const { view, currentPostId } = useApp();
|
const { view, currentPostId, currentUsername } = useApp();
|
||||||
const [modal, setModal] = useState(null); // null | login | register | report
|
const [modal, setModal] = useState(null); // null | login | register | report
|
||||||
const [reportPostId, setReportPostId] = useState(null);
|
const [reportPostId, setReportPostId] = useState(null);
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ function HomeInner() {
|
|||||||
{/* 独立页面 */}
|
{/* 独立页面 */}
|
||||||
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
|
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
|
||||||
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} />}
|
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} />}
|
||||||
|
{view === 'user' && currentUsername && <UserProfile username={currentUsername} />}
|
||||||
{view === 'new' && <NewPost />}
|
{view === 'new' && <NewPost />}
|
||||||
{view === 'admin' && <AdminPage />}
|
{view === 'admin' && <AdminPage />}
|
||||||
{view === 'settings' && <SettingsPage />}
|
{view === 'settings' && <SettingsPage />}
|
||||||
|
|||||||
@@ -14,8 +14,9 @@ export default function AppProvider({ children }) {
|
|||||||
const [currentUser, setCurrentUser] = useState(null);
|
const [currentUser, setCurrentUser] = useState(null);
|
||||||
const [forumName, setForumName] = useState('Forumlify');
|
const [forumName, setForumName] = useState('Forumlify');
|
||||||
const [theme, setThemeState] = useState('light');
|
const [theme, setThemeState] = useState('light');
|
||||||
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages
|
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user
|
||||||
const [currentPostId, setCurrentPostId] = useState(null);
|
const [currentPostId, setCurrentPostId] = useState(null);
|
||||||
|
const [currentUsername, setCurrentUsername] = useState(null);
|
||||||
const [sort, setSort] = useState('latest');
|
const [sort, setSort] = useState('latest');
|
||||||
const [refreshKey, setRefreshKey] = useState(0);
|
const [refreshKey, setRefreshKey] = useState(0);
|
||||||
const loadedRef = useRef(false);
|
const loadedRef = useRef(false);
|
||||||
@@ -67,9 +68,13 @@ export default function AppProvider({ children }) {
|
|||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
const postParam = params.get('post');
|
const postParam = params.get('post');
|
||||||
const pageParam = params.get('page');
|
const pageParam = params.get('page');
|
||||||
|
const userParam = params.get('user');
|
||||||
if (postParam) {
|
if (postParam) {
|
||||||
setView('post');
|
setView('post');
|
||||||
setCurrentPostId(postParam);
|
setCurrentPostId(postParam);
|
||||||
|
} else if (userParam) {
|
||||||
|
setView('user');
|
||||||
|
setCurrentUsername(userParam);
|
||||||
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
|
} else if (pageParam && ['messages', 'settings', 'admin', 'new'].includes(pageParam)) {
|
||||||
setView(pageParam);
|
setView(pageParam);
|
||||||
}
|
}
|
||||||
@@ -95,11 +100,22 @@ export default function AppProvider({ children }) {
|
|||||||
const url = new URL(window.location);
|
const url = new URL(window.location);
|
||||||
url.searchParams.set('post', postId);
|
url.searchParams.set('post', postId);
|
||||||
url.searchParams.delete('page');
|
url.searchParams.delete('page');
|
||||||
|
url.searchParams.delete('user');
|
||||||
window.history.pushState({ page: 'post', postId }, '', url);
|
window.history.pushState({ page: 'post', postId }, '', url);
|
||||||
setView('post');
|
setView('post');
|
||||||
setCurrentPostId(postId);
|
setCurrentPostId(postId);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const openUser = useCallback((username) => {
|
||||||
|
const url = new URL(window.location);
|
||||||
|
url.searchParams.set('user', username);
|
||||||
|
url.searchParams.delete('page');
|
||||||
|
url.searchParams.delete('post');
|
||||||
|
window.history.pushState({ page: 'user', username }, '', url);
|
||||||
|
setView('user');
|
||||||
|
setCurrentUsername(username);
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 浏览器前进后退
|
// 浏览器前进后退
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onPop = (e) => {
|
const onPop = (e) => {
|
||||||
@@ -107,9 +123,13 @@ export default function AppProvider({ children }) {
|
|||||||
if (state.postId) {
|
if (state.postId) {
|
||||||
setView('post');
|
setView('post');
|
||||||
setCurrentPostId(state.postId);
|
setCurrentPostId(state.postId);
|
||||||
|
} else if (state.username) {
|
||||||
|
setView('user');
|
||||||
|
setCurrentUsername(state.username);
|
||||||
} else {
|
} else {
|
||||||
setView(state.page || 'feed');
|
setView(state.page || 'feed');
|
||||||
setCurrentPostId(null);
|
setCurrentPostId(null);
|
||||||
|
setCurrentUsername(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
window.addEventListener('popstate', onPop);
|
window.addEventListener('popstate', onPop);
|
||||||
@@ -152,6 +172,7 @@ export default function AppProvider({ children }) {
|
|||||||
theme, toggleTheme,
|
theme, toggleTheme,
|
||||||
view, navigate,
|
view, navigate,
|
||||||
currentPostId, openPost,
|
currentPostId, openPost,
|
||||||
|
currentUsername, openUser,
|
||||||
sort, setSort,
|
sort, setSort,
|
||||||
refreshKey, refresh,
|
refreshKey, refresh,
|
||||||
login, register, logout,
|
login, register, logout,
|
||||||
|
|||||||
+8
-2
@@ -12,7 +12,7 @@ function avatar(username) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Feed({ onOpenModal, onReport }) {
|
export default function Feed({ onOpenModal, onReport }) {
|
||||||
const { currentUser, sort, setSort, openPost, navigate, refreshKey } = useApp();
|
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
|
||||||
const [posts, setPosts] = useState(null);
|
const [posts, setPosts] = useState(null);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
@@ -72,7 +72,13 @@ export default function Feed({ onOpenModal, onReport }) {
|
|||||||
onClick={() => openPost(p.id)}>
|
onClick={() => openPost(p.id)}>
|
||||||
<div className="post-header">
|
<div className="post-header">
|
||||||
<img src={avatar(p.username)} className="post-avatar" alt="" />
|
<img src={avatar(p.username)} className="post-avatar" alt="" />
|
||||||
<span className="post-username">{p.username || '匿名用户'}</span>
|
<span
|
||||||
|
className="post-username"
|
||||||
|
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||||
|
onClick={(e) => { e.stopPropagation(); openUser(p.username); }}
|
||||||
|
>
|
||||||
|
{p.username || '匿名用户'}
|
||||||
|
</span>
|
||||||
<span className="post-time">{time}</span>
|
<span className="post-time">{time}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="post-title">{p.title || '无标题'}</div>
|
<div className="post-title">{p.title || '无标题'}</div>
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ function avatar(username) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PostDetail({ postId }) {
|
export default function PostDetail({ postId }) {
|
||||||
const { currentUser, navigate, refreshKey } = useApp();
|
const { currentUser, navigate, openUser, refreshKey } = useApp();
|
||||||
const [post, setPost] = useState(null);
|
const [post, setPost] = useState(null);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
@@ -63,7 +63,13 @@ export default function PostDetail({ postId }) {
|
|||||||
<div className="post-detail-card">
|
<div className="post-detail-card">
|
||||||
<div className="post-header">
|
<div className="post-header">
|
||||||
<img src={avatar(post.username)} className="post-avatar" alt="" />
|
<img src={avatar(post.username)} className="post-avatar" alt="" />
|
||||||
<span className="post-username">{post.username || '匿名用户'}</span>
|
<span
|
||||||
|
className="post-username"
|
||||||
|
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||||
|
onClick={() => openUser(post.username)}
|
||||||
|
>
|
||||||
|
{post.username || '匿名用户'}
|
||||||
|
</span>
|
||||||
<span className="post-time">{time}</span>
|
<span className="post-time">{time}</span>
|
||||||
{canDelete && (
|
{canDelete && (
|
||||||
<button className="btn-sm btn-danger" onClick={handleDelete}>
|
<button className="btn-sm btn-danger" onClick={handleDelete}>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ function avatar(username) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function ReplyList({ postId, onRefresh }) {
|
export default function ReplyList({ postId, onRefresh }) {
|
||||||
const { currentUser } = useApp();
|
const { currentUser, openUser } = useApp();
|
||||||
const [replies, setReplies] = useState([]);
|
const [replies, setReplies] = useState([]);
|
||||||
const [content, setContent] = useState('');
|
const [content, setContent] = useState('');
|
||||||
const [captcha, setCaptcha] = useState(null);
|
const [captcha, setCaptcha] = useState(null);
|
||||||
@@ -75,7 +75,13 @@ export default function ReplyList({ postId, onRefresh }) {
|
|||||||
<div key={r.id} className="reply-item">
|
<div key={r.id} className="reply-item">
|
||||||
<div className="reply-header">
|
<div className="reply-header">
|
||||||
<img src={avatar(r.username)} className="reply-avatar" alt="" />
|
<img src={avatar(r.username)} className="reply-avatar" alt="" />
|
||||||
<span className="reply-username">{r.username || '匿名用户'}</span>
|
<span
|
||||||
|
className="reply-username"
|
||||||
|
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||||
|
onClick={() => openUser(r.username)}
|
||||||
|
>
|
||||||
|
{r.username || '匿名用户'}
|
||||||
|
</span>
|
||||||
<span className="reply-time">{rTime}</span>
|
<span className="reply-time">{rTime}</span>
|
||||||
{currentUser && currentUser.id === r.user_id && (
|
{currentUser && currentUser.id === r.user_id && (
|
||||||
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>
|
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
// 用户主页:资料卡 + 该用户的帖子列表
|
||||||
|
import { useEffect, useState, useCallback } from 'react';
|
||||||
|
import { API } from '@/lib/api';
|
||||||
|
import { useApp } from './AppProvider';
|
||||||
|
import { Icon } from './Icons';
|
||||||
|
|
||||||
|
function avatar(username, size = 128) {
|
||||||
|
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||||
|
'&background=6366f1&color=fff&size=' + size;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function UserProfile({ username }) {
|
||||||
|
const { openPost } = useApp();
|
||||||
|
const [user, setUser] = useState(null);
|
||||||
|
const [posts, setPosts] = useState([]);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const users = await API.getUsersByUsername(username);
|
||||||
|
const u = users && users.length > 0 ? users[0] : null;
|
||||||
|
if (!u) {
|
||||||
|
setError('用户不存在');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setUser(u);
|
||||||
|
const userPosts = await API.getPosts('latest', u.id);
|
||||||
|
setPosts(userPosts || []);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || '加载失败');
|
||||||
|
}
|
||||||
|
}, [username]);
|
||||||
|
|
||||||
|
useEffect(() => { load(); }, [load]);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="page-slide active">
|
||||||
|
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!user) {
|
||||||
|
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-slide active">
|
||||||
|
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||||
|
<h2><Icon name="users" size={20} /> 用户主页</h2>
|
||||||
|
</div>
|
||||||
|
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||||
|
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
|
||||||
|
<img src={avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
|
||||||
|
<h2 style={{ margin: '16px 0 4px', fontSize: 24 }}>{user.username}</h2>
|
||||||
|
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
||||||
|
<span>📅 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
||||||
|
<span>📝 发了 {posts.length} 个帖子</span>
|
||||||
|
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}>🛡️ 管理员</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}>📝 发布的帖子</h3>
|
||||||
|
{posts.length === 0 ? (
|
||||||
|
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</div>
|
||||||
|
) : (
|
||||||
|
posts.map((p) => {
|
||||||
|
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||||
|
return (
|
||||||
|
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={() => openPost(p.id)}>
|
||||||
|
<div className="post-title" style={{ fontSize: 16, fontWeight: 600 }}>{p.title || '无标题'}</div>
|
||||||
|
<div className="post-content" style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
|
||||||
|
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 8 }}>{time}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+6
-1
@@ -48,7 +48,11 @@ export const API = {
|
|||||||
getMe() { return apiFetch('/auth/me'); },
|
getMe() { return apiFetch('/auth/me'); },
|
||||||
|
|
||||||
// 帖子
|
// 帖子
|
||||||
getPosts(sort) { return apiFetch('/posts?sort=' + (sort || 'latest')); },
|
getPosts(sort, userId) {
|
||||||
|
let q = '/posts?sort=' + (sort || 'latest');
|
||||||
|
if (userId) q += '&user_id=' + userId;
|
||||||
|
return apiFetch(q);
|
||||||
|
},
|
||||||
getPost(postId) { return apiFetch('/posts/' + postId); },
|
getPost(postId) { return apiFetch('/posts/' + postId); },
|
||||||
createPost(title, content, images) {
|
createPost(title, content, images) {
|
||||||
return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) });
|
return apiFetch('/posts', { method: 'POST', body: JSON.stringify({ title, content, images: images || [] }) });
|
||||||
@@ -64,6 +68,7 @@ export const API = {
|
|||||||
|
|
||||||
// 用户管理
|
// 用户管理
|
||||||
getUsers() { return apiFetch('/users'); },
|
getUsers() { return apiFetch('/users'); },
|
||||||
|
getUsersByUsername(username) { return apiFetch('/users?username=' + encodeURIComponent(username)); },
|
||||||
updateUserRole(userId, role) {
|
updateUserRole(userId, role) {
|
||||||
return apiFetch('/users/' + userId + '/role', { method: 'PUT', body: JSON.stringify({ role }) });
|
return apiFetch('/users/' + userId + '/role', { method: 'PUT', body: JSON.stringify({ role }) });
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in new issue
Block a user