feat(auth): refactor authentication flow and add login route

- Updated import path for QueryLoginBrowser in query.ts
- Enhanced AuthProvider to allow open links without requiring login
- Added clearMe function to reset user state and redirect to login
- Introduced BaseHeader component for consistent header layout
- Created LoginComponent to handle login success events
- Added App component to manage login state and navigation
- Defined new login route in routeTree and integrated with the application
This commit is contained in:
2026-02-24 17:25:45 +08:00
parent c1df9eb5d4
commit fcd914b3c2
10 changed files with 386 additions and 231 deletions

View File

@@ -1,5 +1,5 @@
import { Query, DataOpts } from '@kevisual/query';
import { QueryLoginBrowser } from '@kevisual/api/login'
import { QueryLoginBrowser } from '@kevisual/api/query-login'
import { useContextKey } from '@kevisual/context';
export const query = useContextKey('query', new Query({
url: '/api/router',

View File

@@ -2,6 +2,12 @@ import { useEffect } from "react"
import { useLayoutStore } from "./store"
import { useShallow } from "zustand/shallow"
import { LogIn, LockKeyhole } from "lucide-react"
export { BaseHeader } from './modules/BaseHeader'
import { useMemo } from 'react';
import { useLocation } from '@tanstack/react-router';
const openLinkList = [
'/login'
]
type Props = {
children?: React.ReactNode,
@@ -15,8 +21,14 @@ export const AuthProvider = ({ children, mustLogin }: Props) => {
useEffect(() => {
store.init()
}, [])
const location = useLocation()
const isOpen = useMemo(() => {
console.log('location.pathname', location.pathname, openLinkList)
return openLinkList.some(item => location.pathname.startsWith(item))
}, [location.pathname])
console.log('AuthProvider', { location, isOpen, me: store.me })
const loginUrl = '/root/login/?redirect=' + encodeURIComponent(window.location.href);
if (mustLogin && !store.me) {
if (mustLogin && !store.me && !isOpen) {
return (
<div className="w-full h-full min-h-screen flex items-center justify-center bg-background">
<div className="flex flex-col items-center gap-6 p-10 rounded-2xl border border-border bg-card shadow-lg max-w-sm w-full mx-4">

View File

@@ -0,0 +1,75 @@
import { Home, User, LogIn, LogOut } from 'lucide-react';
import { Link } from '@tanstack/react-router'
import { useLayoutStore } from '../store';
import { useShallow } from 'zustand/shallow';
import { useMemo } from 'react';
export const BaseHeader = (props: { main?: React.ComponentType | null }) => {
const store = useLayoutStore(useShallow(state => ({
me: state.me,
clearMe: state.clearMe,
})));
const meInfo = useMemo(() => {
if (!store.me) {
return (
<button
onClick={() => window.open('/root/login/?redirect=' + encodeURIComponent(window.location.href), '_self')}
className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
>
<LogIn className="w-4 h-4" />
<span></span>
</button>
)
}
return (
<div className="flex items-center gap-3">
{store.me.avatar && (
<img
src={store.me.avatar}
alt="Avatar"
className="w-8 h-8 rounded-full object-cover"
/>
)}
{!store.me.avatar && (
<div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
<User className="w-4 h-4 text-gray-500" />
</div>
)}
<span className="font-medium text-gray-700">{store.me?.username}</span>
<button
onClick={() => store.clearMe?.()}
className="flex items-center gap-1 px-2 py-1 text-sm text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors cursor-pointer"
title="退出登录"
>
<LogOut className="w-4 h-4" />
</button>
</div>
)
}, [store.me, store.clearMe])
return (
<>
<div className="flex gap-2 text-lg w-full h-12 items-center justify-between">
<div className='px-2'>
<Link
to="/"
activeProps={{
className: 'font-bold',
}}
activeOptions={{ exact: true }}
>
<Home className='w-5 h-5' />
</Link>
</div>
<div className='mr-4'>
{meInfo}
</div>
</div>
<hr />
</>
)
}
export const LayoutMain = () => {
return <BaseHeader />
}

49
src/pages/auth/page.tsx Normal file
View File

@@ -0,0 +1,49 @@
import { useContextKey } from '@kevisual/context';
import '@kevisual/kv-login';
import { checkPluginLogin } from '@kevisual/kv-login'
import { useEffect } from 'react';
import { useLayoutStore } from './store';
import { useShallow } from 'zustand/shallow';
import { useNavigate } from '@tanstack/react-router';
export const LoginComponent = ({ onLoginSuccess }: { onLoginSuccess: () => void }) => {
useEffect(() => {
// 监听登录成功事件
const handleLoginSuccess = () => {
console.log('监听到登录成功事件,关闭弹窗');
onLoginSuccess();
};
const loginEmitter = useContextKey('login-emitter')
console.log('KvLogin Types:', loginEmitter);
loginEmitter.on('login-success', handleLoginSuccess);
// 清理监听器
return () => {
loginEmitter.off('login-success', handleLoginSuccess);
};
}, [onLoginSuccess]);
// @ts-ignore
return (<kv-login></kv-login>)
}
export const App = () => {
const store = useLayoutStore(useShallow((state) => ({
init: state.init
})));
useEffect(() => {
checkPluginLogin();
}, []);
const navigate = useNavigate();
const handleLoginSuccess = async () => {
await store.init()
navigate({ to: '/' })
};
return <div className='w-full h-full'>
<div className='w-md mx-auto flex mt-20'>
<LoginComponent onLoginSuccess={handleLoginSuccess} />
</div>
</div>
}
export default App;

View File

@@ -19,11 +19,14 @@ export type LayoutStore = {
setOpenUser: (openUser: boolean) => void;
me?: UserInfo;
setMe: (me: UserInfo) => void;
clearMe: () => void;
getMe: () => Promise<void>;
switchOrg: (username?: string) => Promise<void>;
isAdmin: boolean;
setIsAdmin: (isAdmin: boolean) => void
init: () => Promise<void>;
openLinkList: string[];
setOpenLinkList: (openLinkList: string[]) => void;
};
export const useLayoutStore = create<LayoutStore>((set, get) => ({
open: false,
@@ -32,6 +35,10 @@ export const useLayoutStore = create<LayoutStore>((set, get) => ({
setOpenUser: (openUser) => set({ openUser }),
me: undefined,
setMe: (me) => set({ me }),
clearMe: () => {
set({ me: undefined, isAdmin: false });
window.location.href = '/root/login/?redirect=' + encodeURIComponent(window.location.href);
},
getMe: async () => {
const res = await queryLogin.getMe();
if (res.code === 200) {
@@ -61,5 +68,7 @@ export const useLayoutStore = create<LayoutStore>((set, get) => ({
set({ isAdmin: user.orgs?.includes?.('admin') || false });
}
}
}
},
openLinkList: ['/login'],
setOpenLinkList: (openLinkList) => set({ openLinkList }),
}));

View File

@@ -9,9 +9,15 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as LoginRouteImport } from './routes/login'
import { Route as DemoRouteImport } from './routes/demo'
import { Route as IndexRouteImport } from './routes/index'
const LoginRoute = LoginRouteImport.update({
id: '/login',
path: '/login',
getParentRoute: () => rootRouteImport,
} as any)
const DemoRoute = DemoRouteImport.update({
id: '/demo',
path: '/demo',
@@ -26,31 +32,42 @@ const IndexRoute = IndexRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/demo': typeof DemoRoute
'/login': typeof LoginRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/demo': typeof DemoRoute
'/login': typeof LoginRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/demo': typeof DemoRoute
'/login': typeof LoginRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/demo'
fullPaths: '/' | '/demo' | '/login'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/demo'
id: '__root__' | '/' | '/demo'
to: '/' | '/demo' | '/login'
id: '__root__' | '/' | '/demo' | '/login'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
DemoRoute: typeof DemoRoute
LoginRoute: typeof LoginRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/login': {
id: '/login'
path: '/login'
fullPath: '/login'
preLoaderRoute: typeof LoginRouteImport
parentRoute: typeof rootRouteImport
}
'/demo': {
id: '/demo'
path: '/demo'
@@ -71,6 +88,7 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
DemoRoute: DemoRoute,
LoginRoute: LoginRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)

View File

@@ -1,43 +1,18 @@
// import { LayoutMain } from '@/modules/layout'
const LayoutMain = null;
import { Link, Outlet, createRootRoute } from '@tanstack/react-router'
import { LayoutMain } from '@/pages/auth/modules/BaseHeader';
import { Outlet, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { Toaster } from '@/components/ui/sonner'
import { AuthProvider } from '@/pages/auth'
import { TooltipProvider } from '@/components/ui/tooltip'
import { Home } from 'lucide-react';
export const Route = createRootRoute({
component: RootComponent,
})
const BaseHeader = (props: { main?: React.ComponentType | null }) => {
if (props.main) {
const MainComponent = props.main
return <MainComponent />
}
return (
<>
<div className="flex gap-2 text-lg w-full h-12 items-center">
<div className='px-2'>
<Link
to="/"
activeProps={{
className: 'font-bold',
}}
activeOptions={{ exact: true }}
>
<Home className='w-5 h-5' />
</Link>
</div>
</div>
<hr />
</>
)
}
function RootComponent() {
return (
<div className='h-full overflow-hidden'>
<BaseHeader main={LayoutMain} />
<LayoutMain />
<AuthProvider mustLogin={true}>
<TooltipProvider>
<main className='h-[calc(100%-3rem)] overflow-auto scrollbar'>

9
src/routes/login.tsx Normal file
View File

@@ -0,0 +1,9 @@
import { createFileRoute } from '@tanstack/react-router'
import App from '@/pages/auth/page'
export const Route = createFileRoute('/login')({
component: RouteComponent,
})
function RouteComponent() {
return <App />
}