mirror of
https://github.com/snowykami/neo-blog.git
synced 2025-09-26 02:56:22 +00:00
feat: 实现用户认证上下文,重构相关组件以支持用户状态管理
This commit is contained in:
@ -25,8 +25,8 @@ const (
|
||||
EnvKeyPasswordSalt = "PASSWORD_SALT" // 环境变量:密码盐
|
||||
EnvKeyTokenDuration = "TOKEN_DURATION" // 环境变量:令牌有效期
|
||||
EnvKeyMaxReplyDepth = "MAX_REPLY_DEPTH" // 环境变量:最大回复深度
|
||||
EnvKeyTokenDurationDefault = 300 // Token有效时长
|
||||
EnvKeyRefreshTokenDurationDefault = 604800 // refresh token有效时长
|
||||
EnvKeyTokenDurationDefault = 30 // Token有效时长
|
||||
EnvKeyRefreshTokenDurationDefault = 6000000 // refresh token有效时长
|
||||
EnvKeyRefreshTokenDuration = "REFRESH_TOKEN_DURATION" // 环境变量:刷新令牌有效期
|
||||
EnvKeyRefreshTokenDurationWithRemember = "REFRESH_TOKEN_DURATION_WITH_REMEMBER" // 环境变量:记住我刷新令牌有效期
|
||||
KVKeyEmailVerificationCode = "email_verification_code:" // KV存储:邮箱验证码
|
||||
|
@ -47,14 +47,20 @@ export async function ListOidcConfigs(): Promise<BaseResponse<OidcConfig[]>> {
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function getLoginUser(token: string = ''): Promise<BaseResponse<User>> {
|
||||
export async function getLoginUser(
|
||||
{ token = '', refreshToken = '' }: { token?: string, refreshToken?: string } = {}
|
||||
): Promise<BaseResponse<User>> {
|
||||
if (token) {
|
||||
const cookieParts = [`token=${token}`]
|
||||
if (refreshToken) cookieParts.push(`refresh_token=${refreshToken}`)
|
||||
const res = await axiosClient.get<BaseResponse<User>>('/user/me', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
headers: { Cookie: cookieParts.join('; ') },
|
||||
})
|
||||
return res.data
|
||||
}
|
||||
const res = await axiosClient.get<BaseResponse<User>>('/user/me')
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function getUserById(id: number): Promise<BaseResponse<User>> {
|
||||
const res = await axiosClient.get<BaseResponse<User>>(`/user/u/${id}`)
|
||||
|
@ -7,29 +7,22 @@ import {
|
||||
} from "@/components/ui/sidebar"
|
||||
|
||||
import { useToLogin } from "@/hooks/use-route"
|
||||
import { useEffect, useState } from "react"
|
||||
import { User } from "@/models/user"
|
||||
import { getLoginUser } from "@/api/user"
|
||||
import { useEffect } from "react"
|
||||
import { useAuth } from "@/contexts/auth-context"
|
||||
|
||||
export default function ConsoleLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const { user } = useAuth();
|
||||
const toLogin = useToLogin();
|
||||
|
||||
useEffect(() => {
|
||||
getLoginUser().then(res => {
|
||||
setUser(res.data);
|
||||
}).catch(() => {
|
||||
setUser(null);
|
||||
if (!user) {
|
||||
toLogin();
|
||||
});
|
||||
}, [toLogin]);
|
||||
if (user === null) {
|
||||
return null;
|
||||
}
|
||||
}, [user, toLogin]);
|
||||
|
||||
return (
|
||||
<SidebarProvider
|
||||
|
@ -1,12 +1,14 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { DeviceProvider } from "@/contexts/device-context";
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import { AuthProvider } from "@/contexts/auth-context";
|
||||
import config from "@/config";
|
||||
import { getFirstLocale } from '@/i18n/request';
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
|
||||
import { getLoginUser } from "@/api/user";
|
||||
import "./globals.css";
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
@ -27,6 +29,10 @@ export default async function RootLayout({
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const token = (await cookies()).get("token")?.value || "";
|
||||
const refreshToken = (await cookies()).get("refresh_token")?.value || "";
|
||||
const user = await getLoginUser({token, refreshToken}).then(res => res.data).catch(() => null);
|
||||
|
||||
return (
|
||||
<html lang={await getFirstLocale() || "en"} className="h-full">
|
||||
<body
|
||||
@ -35,7 +41,9 @@ export default async function RootLayout({
|
||||
<Toaster richColors position="top-center" offset={80} />
|
||||
<DeviceProvider>
|
||||
<NextIntlClientProvider>
|
||||
<AuthProvider initialUser={user}>
|
||||
{children}
|
||||
</AuthProvider>
|
||||
</NextIntlClientProvider>
|
||||
</DeviceProvider>
|
||||
</body>
|
||||
|
@ -1,6 +1,4 @@
|
||||
"use client"
|
||||
|
||||
import { User } from "@/models/user";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
@ -12,9 +10,10 @@ import { Separator } from "@/components/ui/separator";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { CommentInput } from "./comment-input";
|
||||
import { CommentItem } from "./comment-item";
|
||||
import { useAuth } from "@/contexts/auth-context";
|
||||
import config from "@/config";
|
||||
import "./style.css";
|
||||
import { getLoginUser } from "@/api/user";
|
||||
|
||||
|
||||
|
||||
export function CommentSection(
|
||||
@ -29,7 +28,6 @@ export function CommentSection(
|
||||
}
|
||||
) {
|
||||
const t = useTranslations('Comment')
|
||||
const [loginUser, setLoginUser] = useState<User | null>(null);
|
||||
const [comments, setComments] = useState<Comment[]>([]);
|
||||
const [activeInput, setActiveInput] = useState<{ id: number; type: 'reply' | 'edit' } | null>(null);
|
||||
const [page, setPage] = useState(1); // 当前页码
|
||||
@ -37,14 +35,7 @@ export function CommentSection(
|
||||
const [needLoadMore, setNeedLoadMore] = useState(true); // 是否需要加载更多,当最后一次获取的评论数小于分页大小时设为false
|
||||
|
||||
// 获取登录用户信息
|
||||
useEffect(() => {
|
||||
getLoginUser().then(res => {
|
||||
setLoginUser(res.data);
|
||||
console.log("login user:", res.data);
|
||||
}).catch(() => {
|
||||
setLoginUser(null);
|
||||
});
|
||||
}, []);
|
||||
const {user} = useAuth();
|
||||
// 加载0/顶层评论
|
||||
useEffect(() => {
|
||||
listComments({
|
||||
@ -118,7 +109,7 @@ export function CommentSection(
|
||||
<Separator className="my-16" />
|
||||
<div className="font-bold text-2xl">{t("comment")} ({totalCommentCount})</div>
|
||||
<CommentInput
|
||||
user={loginUser}
|
||||
user={user}
|
||||
onCommentSubmitted={onCommentSubmitted}
|
||||
/>
|
||||
<div className="mt-4">
|
||||
@ -127,7 +118,7 @@ export function CommentSection(
|
||||
<div key={comment.id} className="" style={{ animationDelay: `${idx * 60}ms` }}>
|
||||
<Separator className="my-2" />
|
||||
<CommentItem
|
||||
loginUser={loginUser}
|
||||
loginUser={user}
|
||||
comment={comment}
|
||||
parentComment={null}
|
||||
onCommentDelete={onCommentDelete}
|
||||
|
@ -1,12 +1,7 @@
|
||||
"use client"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
import {
|
||||
IconChartBar,
|
||||
IconDashboard,
|
||||
IconFolder,
|
||||
IconInnerShadowTop,
|
||||
IconListDetails,
|
||||
IconUsers,
|
||||
} from "@tabler/icons-react"
|
||||
|
||||
import { NavMain } from "@/components/console/nav-main"
|
||||
@ -22,52 +17,39 @@ import {
|
||||
} from "@/components/ui/sidebar"
|
||||
import config from "@/config"
|
||||
import Link from "next/link"
|
||||
import { getLoginUser } from "@/api/user"
|
||||
import { User } from "@/models/user"
|
||||
import { Folder, Gauge, MessageCircle, Newspaper, Users } from "lucide-react"
|
||||
|
||||
const data = {
|
||||
navMain: [
|
||||
{
|
||||
title: "大石坝",
|
||||
url: "/console",
|
||||
icon: IconDashboard,
|
||||
icon: Gauge,
|
||||
},
|
||||
{
|
||||
title: "文章管理",
|
||||
url: "/console/post",
|
||||
icon: IconListDetails,
|
||||
icon: Newspaper,
|
||||
},
|
||||
{
|
||||
title: "评论管理",
|
||||
url: "/console/comment",
|
||||
icon: IconChartBar,
|
||||
icon: MessageCircle,
|
||||
},
|
||||
{
|
||||
title: "文件管理",
|
||||
url: "/console/file",
|
||||
icon: IconFolder,
|
||||
icon: Folder,
|
||||
},
|
||||
{
|
||||
title: "用户管理",
|
||||
url: "/console/user",
|
||||
icon: IconUsers,
|
||||
icon: Users,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
const [loginUser, setLoginUser] = useState<User | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getLoginUser().then(resp => {
|
||||
setLoginUser(resp.data);
|
||||
});
|
||||
}, [])
|
||||
|
||||
if (!loginUser) {
|
||||
return null; // 或者返回一个加载指示器
|
||||
}
|
||||
|
||||
return (
|
||||
<Sidebar collapsible="offcanvas" {...props}>
|
||||
<SidebarHeader>
|
||||
@ -89,7 +71,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
<NavMain items={data.navMain} />
|
||||
</SidebarContent>
|
||||
<SidebarFooter>
|
||||
<NavUser user={loginUser} />
|
||||
<NavUser />
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
)
|
||||
|
@ -1,7 +1,5 @@
|
||||
"use client"
|
||||
|
||||
import { type Icon } from "@tabler/icons-react"
|
||||
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
@ -10,6 +8,9 @@ import {
|
||||
SidebarMenuItem,
|
||||
} from "@/components/ui/sidebar"
|
||||
import Link from "next/link"
|
||||
import type { LucideProps } from "lucide-react";
|
||||
import { ComponentType, SVGProps } from "react"
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
export function NavMain({
|
||||
items,
|
||||
@ -17,9 +18,12 @@ export function NavMain({
|
||||
items: {
|
||||
title: string
|
||||
url: string
|
||||
icon?: Icon
|
||||
icon?: ComponentType<SVGProps<SVGSVGElement> & LucideProps>;
|
||||
}[]
|
||||
}) {
|
||||
const pathname = usePathname() ?? "/"
|
||||
console.log("pathname", pathname)
|
||||
|
||||
return (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupContent className="flex flex-col gap-2">
|
||||
@ -27,7 +31,7 @@ export function NavMain({
|
||||
{items.map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<Link href={item.url}>
|
||||
<SidebarMenuButton tooltip={item.title}>
|
||||
<SidebarMenuButton tooltip={item.title} isActive={pathname===item.url}>
|
||||
{item.icon && <item.icon />}
|
||||
<span>{item.title}</span>
|
||||
</SidebarMenuButton>
|
||||
|
@ -35,10 +35,10 @@ import { getFallbackAvatarFromUsername } from "@/utils/common/username"
|
||||
export function NavUser({
|
||||
user,
|
||||
}: {
|
||||
user: User
|
||||
user?: User
|
||||
}) {
|
||||
const { isMobile } = useSidebar()
|
||||
|
||||
if (!user) return null
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
|
@ -8,9 +8,7 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { User } from "@/models/user";
|
||||
import { useEffect, useState } from "react";
|
||||
import { getLoginUser, userLogout } from "@/api/user";
|
||||
import { userLogout } from "@/api/user";
|
||||
import Link from "next/link";
|
||||
import { toast } from "sonner";
|
||||
import { useToLogin } from "@/hooks/use-route";
|
||||
@ -18,17 +16,11 @@ import { CircleUser } from "lucide-react";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { getGravatarFromUser } from "@/utils/common/gravatar";
|
||||
import { getFallbackAvatarFromUsername } from "@/utils/common/username";
|
||||
import { useAuth } from "@/contexts/auth-context";
|
||||
|
||||
export function AvatarWithDropdownMenu() {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const {user} = useAuth();
|
||||
const toLogin = useToLogin();
|
||||
useEffect(() => {
|
||||
getLoginUser().then(res => {
|
||||
setUser(res.data);
|
||||
}).catch(() => {
|
||||
setUser(null);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleLogout = () => {
|
||||
userLogout().then(() => {
|
||||
|
38
web/src/contexts/auth-context.tsx
Normal file
38
web/src/contexts/auth-context.tsx
Normal file
@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, useMemo } from "react";
|
||||
import type { User } from "@/models/user";
|
||||
import { userLogout } from "@/api/user";
|
||||
|
||||
type AuthContextValue = {
|
||||
user: User | null;
|
||||
setUser: (u: User | null) => void;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({
|
||||
children,
|
||||
initialUser = null,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
initialUser?: User | null;
|
||||
}) {
|
||||
const [user, setUser] = useState<User | null>(initialUser);
|
||||
|
||||
const logout = async () => {
|
||||
setUser(null);
|
||||
await userLogout();
|
||||
};
|
||||
const value = useMemo(() => ({ user, setUser, logout }), [user]);
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useAuth must be used within an AuthProvider");
|
||||
}
|
||||
return ctx;
|
||||
}
|
@ -26,7 +26,8 @@ export async function getUserLocales(): Promise<string[]> {
|
||||
const cookieStore = await cookies();
|
||||
try {
|
||||
const token = cookieStore.get('token')?.value || '';
|
||||
const user = (await getLoginUser(token)).data;
|
||||
const refreshToken = cookieStore.get('refresh_token')?.value || '';
|
||||
const user = (await getLoginUser({token, refreshToken})).data;
|
||||
locales.push(user.language);
|
||||
locales.push(user.language.split('-')[0]);
|
||||
} catch {
|
||||
|
@ -12,7 +12,6 @@ import type { User } from '@/models/user';
|
||||
|
||||
export function getGravatarUrl({ email, size, proxy }: { email: string, size?: number, proxy?: string }): string {
|
||||
const hash = md5(email.trim().toLowerCase());
|
||||
console.log(`https://${proxy ? proxy : "www.gravatar.com"}/avatar/${hash}?s=${size}&d=identicon`)
|
||||
return `https://${proxy ? proxy : "www.gravatar.com"}/avatar/${hash}?s=${size}&d=identicon`;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user