Added loginPage
This commit is contained in:
@@ -7,7 +7,6 @@ import { healthCheckInterval } from '@/lib/constants'
|
||||
import { useBackendState } from '@/stores/state'
|
||||
import { useSettingsStore } from '@/stores/settings'
|
||||
import { useEffect } from 'react'
|
||||
import { Toaster } from 'sonner'
|
||||
import SiteHeader from '@/features/SiteHeader'
|
||||
import { InvalidApiKeyError, RequireApiKeError } from '@/api/lightrag'
|
||||
|
||||
@@ -79,7 +78,6 @@ function App() {
|
||||
{enableHealthCheck && <StatusIndicator />}
|
||||
{message !== null && !apiKeyInvalid && <MessageAlert />}
|
||||
{apiKeyInvalid && <ApiKeyAlert />}
|
||||
<Toaster />
|
||||
</main>
|
||||
</ThemeProvider>
|
||||
)
|
||||
|
40
lightrag_webui/src/AppRouter.tsx
Normal file
40
lightrag_webui/src/AppRouter.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||
// import { useAuthStore } from '@/stores/state'
|
||||
import { Toaster } from 'sonner'
|
||||
import App from './App'
|
||||
import LoginPage from '@/features/LoginPage'
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
|
||||
// const { isAuthenticated } = useAuthStore()
|
||||
|
||||
// if (!isAuthenticated) {
|
||||
// return <Navigate to="/login" replace />
|
||||
// }
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
const AppRouter = () => {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="/*"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<App />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
<Toaster position="top-center" />
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
||||
export default AppRouter
|
@@ -2,6 +2,7 @@ import axios, { AxiosError } from 'axios'
|
||||
import { backendBaseUrl } from '@/lib/constants'
|
||||
import { errorMessage } from '@/lib/utils'
|
||||
import { useSettingsStore } from '@/stores/settings'
|
||||
import { useAuthStore } from '@/stores/state'
|
||||
|
||||
// Types
|
||||
export type LightragNodeType = {
|
||||
@@ -125,6 +126,11 @@ export type DocsStatusesResponse = {
|
||||
statuses: Record<DocStatus, DocStatusResponse[]>
|
||||
}
|
||||
|
||||
export type LoginResponse = {
|
||||
access_token: string
|
||||
token_type: string
|
||||
}
|
||||
|
||||
export const InvalidApiKeyError = 'Invalid API Key'
|
||||
export const RequireApiKeError = 'API Key required'
|
||||
|
||||
@@ -139,9 +145,13 @@ const axiosInstance = axios.create({
|
||||
// Interceptor:add api key
|
||||
axiosInstance.interceptors.request.use((config) => {
|
||||
const apiKey = useSettingsStore.getState().apiKey
|
||||
const token = localStorage.getItem('LIGHTRAG-API-TOKEN');
|
||||
if (apiKey) {
|
||||
config.headers['X-API-Key'] = apiKey
|
||||
}
|
||||
if (token) {
|
||||
config.headers['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
@@ -150,6 +160,21 @@ axiosInstance.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error: AxiosError) => {
|
||||
if (error.response) {
|
||||
interface ErrorResponse {
|
||||
detail: string;
|
||||
}
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('LIGHTRAG-API-TOKEN');
|
||||
sessionStorage.clear();
|
||||
useAuthStore.getState().logout();
|
||||
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
throw new Error(
|
||||
`${error.response.status} ${error.response.statusText}\n${JSON.stringify(
|
||||
error.response.data
|
||||
@@ -324,3 +349,17 @@ export const clearDocuments = async (): Promise<DocActionResponse> => {
|
||||
const response = await axiosInstance.delete('/documents')
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const loginToServer = async (username: string, password: string): Promise<LoginResponse> => {
|
||||
const formData = new FormData();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
|
||||
const response = await axiosInstance.post('/login', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
});
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
100
lightrag_webui/src/features/LoginPage.tsx
Normal file
100
lightrag_webui/src/features/LoginPage.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '@/stores/state'
|
||||
import { loginToServer } from '@/api/lightrag'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/Card'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { ZapIcon } from 'lucide-react'
|
||||
|
||||
const LoginPage = () => {
|
||||
const navigate = useNavigate()
|
||||
const { login } = useAuthStore()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
if (!username || !password) {
|
||||
toast.error('Please enter your username and password')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await loginToServer(username, password)
|
||||
login(response.access_token)
|
||||
navigate('/')
|
||||
toast.success('Login succeeded')
|
||||
} catch (error) {
|
||||
console.error('Login failed...', error)
|
||||
toast.error('Login failed, please check username and password')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-screen w-screen items-center justify-center bg-gradient-to-br from-emerald-50 to-teal-100 dark:from-gray-900 dark:to-gray-800">
|
||||
<Card className="w-full max-w-[480px] shadow-lg mx-4">
|
||||
<CardHeader className="flex items-center justify-center space-y-2 pb-8 pt-6">
|
||||
<div className="flex flex-col items-center space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<img src="/logo.png" alt="LightRAG Logo" className="h-12 w-12" />
|
||||
<ZapIcon className="size-10 text-emerald-400" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h1 className="text-3xl font-bold tracking-tight">LightRAG</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Please enter your account and password to log in to the system
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="px-8 pb-8">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<label htmlFor="username" className="text-sm font-medium w-16 shrink-0">
|
||||
username
|
||||
</label>
|
||||
<Input
|
||||
id="username"
|
||||
placeholder="Please input a username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
className="h-11 flex-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<label htmlFor="password" className="text-sm font-medium w-16 shrink-0">
|
||||
password
|
||||
</label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Please input a password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="h-11 flex-1"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-11 text-base font-medium mt-2"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Logging in...' : 'Login'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginPage
|
@@ -3,9 +3,11 @@ import { SiteInfo } from '@/lib/constants'
|
||||
import ThemeToggle from '@/components/ThemeToggle'
|
||||
import { TabsList, TabsTrigger } from '@/components/ui/Tabs'
|
||||
import { useSettingsStore } from '@/stores/settings'
|
||||
import { useAuthStore } from '@/stores/state'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
|
||||
import { ZapIcon, GithubIcon } from 'lucide-react'
|
||||
import { ZapIcon, GithubIcon, LogOutIcon } from 'lucide-react'
|
||||
|
||||
interface NavigationTabProps {
|
||||
value: string
|
||||
@@ -51,6 +53,14 @@ function TabsNavigation() {
|
||||
}
|
||||
|
||||
export default function SiteHeader() {
|
||||
const navigate = useNavigate()
|
||||
const { logout } = useAuthStore()
|
||||
|
||||
const handleLogout = () => {
|
||||
logout()
|
||||
navigate('/login')
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="border-border/40 bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-50 flex h-10 w-full border-b px-4 backdrop-blur">
|
||||
<a href="/" className="mr-6 flex items-center gap-2">
|
||||
@@ -63,13 +73,22 @@ export default function SiteHeader() {
|
||||
<TabsNavigation />
|
||||
</div>
|
||||
|
||||
<nav className="flex items-center">
|
||||
<nav className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="icon" side="bottom" tooltip="Project Repository">
|
||||
<a href={SiteInfo.github} target="_blank" rel="noopener noreferrer">
|
||||
<GithubIcon className="size-4" aria-hidden="true" />
|
||||
</a>
|
||||
</Button>
|
||||
<ThemeToggle />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
side="bottom"
|
||||
tooltip="Log Out"
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOutIcon className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</nav>
|
||||
</header>
|
||||
)
|
||||
|
@@ -1,10 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import AppRouter from './AppRouter'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<AppRouter />
|
||||
</StrictMode>
|
||||
)
|
||||
|
@@ -16,6 +16,14 @@ interface BackendState {
|
||||
setErrorMessage: (message: string, messageTitle: string) => void
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
isAuthenticated: boolean;
|
||||
showLoginModal: boolean;
|
||||
login: (token: string) => void;
|
||||
logout: () => void;
|
||||
setShowLoginModal: (show: boolean) => void;
|
||||
}
|
||||
|
||||
const useBackendStateStoreBase = create<BackendState>()((set) => ({
|
||||
health: true,
|
||||
message: null,
|
||||
@@ -57,3 +65,17 @@ const useBackendStateStoreBase = create<BackendState>()((set) => ({
|
||||
const useBackendState = createSelectors(useBackendStateStoreBase)
|
||||
|
||||
export { useBackendState }
|
||||
|
||||
export const useAuthStore = create<AuthState>(set => ({
|
||||
isAuthenticated: !!localStorage.getItem('LIGHTRAG-API-TOKEN'),
|
||||
showLoginModal: false,
|
||||
login: (token) => {
|
||||
localStorage.setItem('LIGHTRAG-API-TOKEN', token);
|
||||
set({ isAuthenticated: true, showLoginModal: false });
|
||||
},
|
||||
logout: () => {
|
||||
localStorage.removeItem('LIGHTRAG-API-TOKEN');
|
||||
set({ isAuthenticated: false });
|
||||
},
|
||||
setShowLoginModal: (show) => set({ showLoginModal: show })
|
||||
}));
|
||||
|
Reference in New Issue
Block a user