重构认证逻辑,优化登录和用户信息获取流程,新增全局缓存支持

This commit is contained in:
2025-04-23 19:00:53 +08:00
parent 22d3b8f3e3
commit 9473413def
23 changed files with 438 additions and 474 deletions

View File

@@ -21,12 +21,13 @@ import zod from 'zod'
import Captcha from './captcha'
import verify from '@/actions/auth/verify'
import {login} from '@/actions/auth/auth'
import {useRouter} from 'next/navigation'
import {useRouter, useSearchParams} from 'next/navigation'
import {toast} from 'sonner'
import {ApiResponse} from '@/lib/api'
import {Label} from '@/components/ui/label'
import logo from '@/assets/logo.webp'
import bg from './_assets/bg.webp'
import {useProfileStore} from '@/components/providers/StoreProvider'
export type LoginPageProps = {}
@@ -157,30 +158,27 @@ export default function LoginPage(props: LoginPageProps) {
// 调用登录函数
const result = await login({
username: values.username,
password: values.password, // 使用验证码作为密码
password: values.password,
remember: values.remember,
})
if (result.success) {
// 登录成功
toast.success('登录成功', {
description: '欢迎回来!',
})
// 跳转到首页或用户仪表板
router.push('/')
router.refresh() // 刷新页面状态
}
else {
// 登录失败
toast.error(result.message, {
// 登录失败
if (!result.success) {
return toast.error(result.message, {
description: '请检查您的手机号码和验证码',
})
}
// 登录成功
await refreshProfile()
router.push(redirect || '/')
toast.success('登录成功', {
description: '欢迎回来!',
})
}
catch (e) {
toast.error('服务器错误', {
description: '请稍后再试',
toast.error('登录错误', {
description: (e as Error).message,
})
}
finally {
@@ -188,6 +186,19 @@ export default function LoginPage(props: LoginPageProps) {
}
}
// ======================
// 重定向
// ======================
const params = useSearchParams()
const redirect = params.get('redirect')
const refreshProfile = useProfileStore(store=>store.refreshProfile)
// ======================
// render
// ======================
return (
<main className={merge(
`relative`,

View File

@@ -1,5 +1,5 @@
'use client'
import {createContext, ReactNode, useCallback, useEffect, useMemo, useState} from 'react'
import {createContext, ReactNode, useCallback, useContext, useEffect, useMemo, useState} from 'react'
import Link from 'next/link'
import Image from 'next/image'
import {LinkItem, MenuItem} from './navs'
@@ -8,14 +8,14 @@ import ProductMenu from './product'
import HelpMenu from './help'
import Wrap from '@/components/wrap'
import logo from '@/assets/logo.webp'
import {Button} from '@/components/ui/button'
import {useProfileStore} from '@/components/providers/StoreProvider'
export const HeaderContext = createContext<{
setMenu: (value: boolean) => void
} | null>(null)
export type ProviderProps = {
userCenter: ReactNode
}
export type ProviderProps = {}
export default function Provider(props: ProviderProps) {
@@ -51,7 +51,13 @@ export default function Provider(props: ProviderProps) {
], [])
// ======================
// 渲染组件
// 用户信息
// ======================
const profile = useProfileStore(store=>store.profile)
// ======================
// render
// ======================
return (
@@ -116,7 +122,35 @@ export default function Provider(props: ProviderProps) {
</nav>
</div>
{/* 登录 */}
{props.userCenter}
<div className={`flex items-center`}>
{profile == undefined
? <>
<Link
href="/login"
className={`w-24 h-12 flex items-center justify-center lg:text-lg`}
>
<span></span>
</Link>
<Link
href="/login"
className={[
`w-20 lg:w-24 h-10 lg:h-12 bg-gradient-to-r rounded-sm flex items-center justify-center lg:text-lg text-white`,
`transition-colors duration-200 ease-in-out`,
`from-blue-500 to-cyan-400 hover:from-blue-500 hover:to-cyan-300`,
].join(' ')}
>
<span></span>
</Link>
</>
: (
<Link href={`/admin`}>
<Button theme={`gradient`}>
</Button>
</Link>
)
}
</div>
</Wrap>
</div>

View File

@@ -1,45 +0,0 @@
import Link from 'next/link'
import {cookies} from 'next/headers'
import {Button} from '@/components/ui/button'
import {AuthContext} from '@/lib/auth'
export type UserCenterProps = {}
export default async function UserCenter(props: UserCenterProps) {
const store = await cookies()
const info = store.get('auth_info')?.value
const data = info ? JSON.parse(info) as AuthContext : undefined
return (
<div className={`flex items-center`}>
{data == undefined
? <>
<Link
href="/login"
className={`w-24 h-12 flex items-center justify-center lg:text-lg`}
>
<span></span>
</Link>
<Link
href="/login"
className={[
`w-20 lg:w-24 h-10 lg:h-12 bg-gradient-to-r rounded-sm flex items-center justify-center lg:text-lg text-white`,
`transition-colors duration-200 ease-in-out`,
`from-blue-500 to-cyan-400 hover:from-blue-500 hover:to-cyan-300`,
].join(' ')}
>
<span></span>
</Link>
</>
: (
<Link href={`/admin`}>
<Button theme={`gradient`}>
</Button>
</Link>
)
}
</div>
)
}

View File

@@ -1,14 +1,11 @@
import Provider from '@/app/(root)/@header/_client/provider'
import UserCenter from '@/app/(root)/@header/_server/user-center'
export type HeaderProps = {}
export default async function Header(props: HeaderProps) {
return (
<header className={`fixed top-0 w-full z-10`}>
<Provider
userCenter={<UserCenter/>}
/>
<Provider/>
</header>
)
}

View File

@@ -10,12 +10,6 @@ import {Tabs, TabsContent, TabsList, TabsTrigger} from '@/components/ui/tabs'
export type DashboardPageProps = {}
export default async function DashboardPage(props: DashboardPageProps) {
const profile = await getProfile()
if (!profile) {
return redirect('/login')
}
return (
<Page className={`flex-auto grid grid-cols-4 grid-rows-[150px_minmax(200px,1fr)_minmax(200px,1fr)_minmax(200px,1fr)]`}>
{/* banner */}

View File

@@ -1,17 +1,33 @@
import {cookies} from 'next/headers'
'use client'
import {Button} from '@/components/ui/button'
import {logout} from '@/actions/auth/auth'
import {useProfileStore} from '@/components/providers/StoreProvider'
import {useRouter} from 'next/navigation'
import {toast} from 'sonner'
export type ProfileProps = {}
export default async function Profile(props: ProfileProps) {
const store = await cookies()
const info = store.get('auth_info')?.value
const data = info ? JSON.parse(info) : undefined
export default function Profile(props: ProfileProps) {
const refreshProfile = useProfileStore(store => store.refreshProfile)
const router = useRouter()
const doLogout = async () => {
try {
const resp = await logout()
if (resp.success) {
await refreshProfile()
router.push('/')
}
}
catch (e) {
toast.error('退出登录失败', {
description: (e as Error).message,
})
}
}
return (
<div className="flex gap-2 items-center">
<span>{data?.payload.name}</span>
<Button theme={`error`} onClick={logout}>
<Button theme={`error`} onClick={doLogout}>
退
</Button>
</div>

View File

@@ -68,6 +68,8 @@ export default function BillsPage(props: BillsPageProps) {
}
useEffect(() => {
console.log('init bill list')
refresh(1, 10).then()
refresh(1, 10).then()
}, [])

View File

@@ -13,7 +13,7 @@ import {Identify} from '@/actions/auth/identify'
import {toast} from 'sonner'
import {useContext, useEffect, useRef, useState} from 'react'
import * as qrcode from 'qrcode'
import {AuthContext} from '@/components/providers/AuthProvider'
import {StoreContext, useProfileStore} from '@/components/providers/StoreProvider'
export type IdentifyPageProps = {}
@@ -90,8 +90,8 @@ export default function IdentifyPage(props: IdentifyPageProps) {
// 用户数据
// ======================
const ctx = useContext(AuthContext)
console.log('render identify page')
const profile = useProfileStore(store => store.profile)
const refreshProfile = useProfileStore(store => store.refreshProfile)
// ======================
// render
@@ -116,7 +116,7 @@ export default function IdentifyPage(props: IdentifyPageProps) {
<h3 className={`text-center text-lg font-bold`}></h3>
<p className={`text-sm text-gray-600`}></p>
</div>
{ctx.profile?.id_token ? (
{profile?.id_token ? (
<div className={`flex flex-col gap-4`}>
<p className={`text-sm text-gray-600`}></p>
</div>
@@ -162,7 +162,7 @@ export default function IdentifyPage(props: IdentifyPageProps) {
<canvas ref={canvas} width={256} height={256}/>
<p className={`text-sm text-gray-600`}></p>
<Button onClick={async () => {
await ctx.refreshProfile()
await refreshProfile()
setOpenDialog(false)
}}>

View File

@@ -4,8 +4,8 @@ import logo from '@/assets/logo.webp'
import Profile from '@/app/admin/_server/profile'
import {merge} from '@/lib/utils'
import Link from 'next/link'
import {getProfile} from '@/actions/auth/auth'
import {redirect} from 'next/navigation'
import {getProfile} from '@/actions/auth/auth'
export type DashboardLayoutProps = {
children: ReactNode
@@ -13,9 +13,9 @@ export type DashboardLayoutProps = {
export default async function DashboardLayout(props: DashboardLayoutProps) {
const profile = await getProfile()
if (!profile) {
return redirect('/login')
const user = await getProfile()
if (!user) {
return redirect(`/login?redirect=${encodeURIComponent('/admin')}`)
}
return (

View File

@@ -9,7 +9,7 @@ import {Input} from '@/components/ui/input'
import {useForm} from 'react-hook-form'
import {zodResolver} from '@hookform/resolvers/zod'
import * as z from 'zod'
import {AuthContext} from '@/components/providers/AuthProvider'
import {StoreContext, useProfileStore} from '@/components/providers/StoreProvider'
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger} from '@/components/ui/dialog'
import {toast} from 'sonner'
import {Alert, AlertDescription, AlertTitle} from '@/components/ui/alert'
@@ -22,8 +22,8 @@ import {User} from '@/lib/models'
export type ProfilePageProps = {}
export default function ProfilePage(props: ProfilePageProps) {
const authCtx = useContext(AuthContext)
const profile = authCtx.profile
const profile = useProfileStore(store => store.profile)
const refreshProfile = useProfileStore(store => store.refreshProfile)
// 默认选中的Tab
const [activeTab, setActiveTab] = useState('basic')
@@ -55,19 +55,19 @@ export default function ProfilePage(props: ProfilePageProps) {
</TabsList>
<TabsContent value="basic">
<BasicInfoTab profile={profile} refreshProfile={authCtx.refreshProfile}/>
<BasicInfoTab profile={profile} refreshProfile={refreshProfile}/>
</TabsContent>
<TabsContent value="security">
<SecurityTab profile={profile} refreshProfile={authCtx.refreshProfile}/>
<SecurityTab profile={profile} refreshProfile={refreshProfile}/>
</TabsContent>
<TabsContent value="balance">
<BalanceTab profile={profile} refreshProfile={authCtx.refreshProfile}/>
<BalanceTab profile={profile} refreshProfile={refreshProfile}/>
</TabsContent>
<TabsContent value="identify">
<IdentifyTab profile={profile} refreshProfile={authCtx.refreshProfile}/>
<IdentifyTab profile={profile} refreshProfile={refreshProfile}/>
</TabsContent>
</Tabs>
</div>

View File

@@ -3,7 +3,7 @@ import {Metadata} from 'next'
import './globals.css'
import localFont from 'next/font/local'
import {Toaster} from '@/components/ui/sonner'
import AuthProvider from '@/components/providers/AuthProvider'
import StoreProvider from '@/components/providers/StoreProvider'
import {getProfile} from '@/actions/auth/auth'
const font = localFont({
@@ -20,12 +20,15 @@ export default async function RootLayout({
}: Readonly<{
children: ReactNode
}>) {
const user = await getProfile()
return (
<html lang="zh-Cn">
<body className={`${font.className}`}>
<AuthProvider>
<StoreProvider user={user}>
{children}
</AuthProvider>
</StoreProvider>
<Toaster position={'top-center'} richColors expand/>
</body>
</html>