admin guard

This commit is contained in:
Artem Tsyrulnikov
2026-03-25 11:58:56 +03:00
parent b397860513
commit 045cb4232a
5 changed files with 163 additions and 2 deletions

View File

@@ -10,6 +10,8 @@ import {
ToastProvider, ToastProvider,
useToast, useToast,
} from '@/lib/hooks/useToast' } from '@/lib/hooks/useToast'
import AdminGuard from '@/feature/auth/AdminGuard'
import LoginPage from '@/feature/auth/LoginPage'
import { import {
ElementsCreation, ElementsCreation,
ProtocolCreation, ProtocolCreation,
@@ -40,16 +42,17 @@ const App: FC = () => {
<CategoryProvider> <CategoryProvider>
<TemplateProvider> <TemplateProvider>
<Routes> <Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/" element={<Layout />}> <Route path="/" element={<Layout />}>
<Route index element={<Navigate to="/templates" replace />} /> <Route index element={<Navigate to="/templates" replace />} />
<Route path="templates/" element={<TemplatesOverviewPage />} /> <Route path="templates/" element={<TemplatesOverviewPage />} />
<Route <Route
path="templates/:templateId/edit" path="templates/:templateId/edit"
element={<TemplateEditPage />} element={<AdminGuard><TemplateEditPage /></AdminGuard>}
/> />
<Route <Route
path="templates/:templateId/elements" path="templates/:templateId/elements"
element={<ElementsCreation />} element={<AdminGuard><ElementsCreation /></AdminGuard>}
/> />
<Route <Route
path="templates/:templateId/protocols" path="templates/:templateId/protocols"

View File

@@ -0,0 +1,18 @@
import { FC, ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { isAuthenticated } from './authService'
interface AdminGuardProps {
children: ReactNode
}
const AdminGuard: FC<AdminGuardProps> = ({ children }) => {
if (!isAuthenticated()) {
return <Navigate to="/login" replace />
}
return <>{children}</>
}
export default AdminGuard

View File

@@ -0,0 +1,67 @@
import { FC, FormEvent, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { login } from './authService'
const LoginPage: FC = () => {
const [password, setPassword] = useState('')
const [error, setError] = useState(false)
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const handleSubmit = async (e: FormEvent) => {
e.preventDefault()
setError(false)
setLoading(true)
const success = await login(password)
setLoading(false)
if (success) {
navigate('/templates', { replace: true })
} else {
setError(true)
setPassword('')
}
}
return (
<div className="flex h-screen items-center justify-center bg-gray-50">
<form
onSubmit={handleSubmit}
className="w-full max-w-sm rounded-lg bg-white p-8 shadow-md"
>
<h1 className="mb-6 text-center text-xl font-semibold text-gray-800">
Вход в режим администратора
</h1>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Пароль"
className={`mb-4 w-full rounded border px-4 py-2 outline-none focus:ring-2 ${
error
? 'border-red-400 focus:ring-red-300'
: 'border-gray-300 focus:ring-blue-300'
}`}
autoFocus
/>
{error && (
<p className="mb-4 text-sm text-red-500">Неверный пароль</p>
)}
<button
type="submit"
disabled={loading || !password}
className="w-full rounded bg-blue-600 px-4 py-2 text-white transition hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Проверка...' : 'Войти'}
</button>
</form>
</div>
)
}
export default LoginPage

View File

@@ -0,0 +1,57 @@
const ADMIN_HASH = 'fa4fec80e90189885dc6a389324bd3beaae9be020641dd37c89f440bf9515e4d'
const SALT = 'protoc_salt_2025'
const STORAGE_KEY = 'admin_auth'
const SESSION_DURATION_MS = 24 * 60 * 60 * 1000 // 24 часа
interface AuthData {
hash: string
expiresAt: number
}
async function sha256(message: string): Promise<string> {
const encoder = new TextEncoder()
const data = encoder.encode(message)
const hashBuffer = await crypto.subtle.digest('SHA-256', data)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
}
export async function login(password: string): Promise<boolean> {
const hash = await sha256(`${SALT}::${password}`)
if (hash !== ADMIN_HASH) {
return false
}
const authData: AuthData = {
hash,
expiresAt: Date.now() + SESSION_DURATION_MS,
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(authData))
return true
}
export function isAuthenticated(): boolean {
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return false
try {
const authData: AuthData = JSON.parse(raw)
if (authData.hash !== ADMIN_HASH) return false
if (Date.now() > authData.expiresAt) {
localStorage.removeItem(STORAGE_KEY)
return false
}
return true
} catch {
localStorage.removeItem(STORAGE_KEY)
return false
}
}
export function logout(): void {
localStorage.removeItem(STORAGE_KEY)
}

View File

@@ -47,8 +47,10 @@ import {
Trash2, Trash2,
Type, Type,
X, X,
LogOut,
} from 'lucide-react' } from 'lucide-react'
import { useCallback, useMemo, useState } from 'react' import { useCallback, useMemo, useState } from 'react'
import { isAuthenticated, logout } from '@/feature/auth/authService'
import { Button } from 'shared/ui/button' import { Button } from 'shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from 'shared/ui/card' import { Card, CardContent, CardHeader, CardTitle } from 'shared/ui/card'
import { Checkbox } from 'shared/ui/checkbox' import { Checkbox } from 'shared/ui/checkbox'
@@ -937,6 +939,20 @@ const TemplatesPageContent = () => {
<h1 className="text-lg font-semibold">Карточки протоколов</h1> <h1 className="text-lg font-semibold">Карточки протоколов</h1>
<div className="ml-auto flex items-center gap-2"> <div className="ml-auto flex items-center gap-2">
{isAuthenticated() && (
<Button
size="sm"
variant="ghost"
onClick={() => {
logout()
window.location.reload()
}}
title="Выйти из режима администратора"
>
<LogOut className="mr-1 h-4 w-4" />
Выйти
</Button>
)}
{/* Кнопка сохранения порядка */} {/* Кнопка сохранения порядка */}
<OrderSaveButton <OrderSaveButton
hasUnsavedChanges={orderState.hasUnsavedChanges} hasUnsavedChanges={orderState.hasUnsavedChanges}