Initial commit: backend scaffold, auth, frontend login
- FastAPI + SQLAlchemy async + Alembic + Postgres backend - Auth: JWT access + rotating refresh tokens, argon2, roles, audit log - React 19 + Vite frontend: login page, protected route, auth context - Docker Compose: postgres, redis, migrate, api, worker (placeholder), frontend/nginx Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Собирается с контекстом = корень репозитория (см. docker-compose.yml),
|
||||
# потому что финальный слой берёт docker/nginx.frontend.conf из соседней
|
||||
# директории — Docker не даёт COPY выйти за пределы build context иначе.
|
||||
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
# Зависимости — отдельным слоем, чтобы правка исходников не переустанавливала node_modules.
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY frontend/ .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.27-alpine AS runtime
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY docker/nginx.frontend.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD wget -qO- http://127.0.0.1/ >/dev/null || exit 1
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>lux_fiscal</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1434
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.103.2",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"oxlint": "^1.81.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.3.0"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,34 @@
|
||||
import { apiFetch } from '@/api/client'
|
||||
import type { LoginResponse, TokenPair, User } from '@/api/types'
|
||||
|
||||
export function login(email: string, password: string): Promise<LoginResponse> {
|
||||
return apiFetch<LoginResponse>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { email, password },
|
||||
})
|
||||
}
|
||||
|
||||
export function refresh(refreshToken: string): Promise<TokenPair> {
|
||||
return apiFetch<TokenPair>('/auth/refresh', {
|
||||
method: 'POST',
|
||||
body: { refresh_token: refreshToken },
|
||||
})
|
||||
}
|
||||
|
||||
export function logout(refreshToken: string): Promise<void> {
|
||||
return apiFetch<void>('/auth/logout', {
|
||||
method: 'POST',
|
||||
body: { refresh_token: refreshToken },
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchMe(): Promise<User> {
|
||||
return apiFetch<User>('/auth/me')
|
||||
}
|
||||
|
||||
export function changePassword(currentPassword: string, newPassword: string): Promise<void> {
|
||||
return apiFetch<void>('/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: { current_password: currentPassword, new_password: newPassword },
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '@/api/tokenStore'
|
||||
import type { ApiErrorBody, TokenPair } from '@/api/types'
|
||||
|
||||
const API_PREFIX = '/api/v1'
|
||||
|
||||
/** Эндпоинты, которые не должны получать Authorization и не должны запускать refresh. */
|
||||
const PUBLIC_PATHS = new Set(['/auth/login', '/auth/refresh'])
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
async function readErrorMessage(response: Response): Promise<string> {
|
||||
try {
|
||||
const body = (await response.json()) as ApiErrorBody
|
||||
if (typeof body.detail === 'string') return body.detail
|
||||
if (Array.isArray(body.detail)) {
|
||||
return body.detail.map((item) => item.msg).join('; ')
|
||||
}
|
||||
} catch {
|
||||
// Тело не JSON или пустое — используем сообщение по статусу ниже.
|
||||
}
|
||||
|
||||
if (response.status === 401) return 'Требуется вход в систему'
|
||||
if (response.status === 403) return 'Недостаточно прав для этого действия'
|
||||
if (response.status >= 500) return 'Сервер временно недоступен, попробуйте позже'
|
||||
return `Ошибка запроса (${response.status})`
|
||||
}
|
||||
|
||||
// Параллельные 401 не должны порождать несколько запросов на refresh —
|
||||
// все ждут один и тот же промис.
|
||||
let refreshPromise: Promise<string> | null = null
|
||||
|
||||
async function refreshAccessToken(): Promise<string> {
|
||||
if (refreshPromise) return refreshPromise
|
||||
|
||||
const refreshToken = getRefreshToken()
|
||||
if (!refreshToken) {
|
||||
throw new ApiError(401, 'Сессия истекла, войдите снова')
|
||||
}
|
||||
|
||||
refreshPromise = (async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_PREFIX}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
clearTokens()
|
||||
throw new ApiError(response.status, await readErrorMessage(response))
|
||||
}
|
||||
|
||||
const pair = (await response.json()) as TokenPair
|
||||
setTokens(pair.access_token, pair.refresh_token)
|
||||
return pair.access_token
|
||||
} finally {
|
||||
refreshPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return refreshPromise
|
||||
}
|
||||
|
||||
export interface ApiFetchOptions extends Omit<RequestInit, 'body'> {
|
||||
body?: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Обёртка над fetch: подставляет Authorization, при первом 401 на защищённом
|
||||
* эндпоинте один раз молча обновляет access-токен и повторяет запрос.
|
||||
*/
|
||||
export async function apiFetch<T = void>(path: string, options: ApiFetchOptions = {}): Promise<T> {
|
||||
const isPublic = PUBLIC_PATHS.has(path)
|
||||
const accessToken = getAccessToken()
|
||||
|
||||
const headers = new Headers(options.headers)
|
||||
headers.set('Content-Type', 'application/json')
|
||||
if (accessToken && !isPublic) {
|
||||
headers.set('Authorization', `Bearer ${accessToken}`)
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_PREFIX}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
||||
})
|
||||
|
||||
if (response.status === 401 && !isPublic) {
|
||||
try {
|
||||
const newAccessToken = await refreshAccessToken()
|
||||
const retryHeaders = new Headers(options.headers)
|
||||
retryHeaders.set('Content-Type', 'application/json')
|
||||
retryHeaders.set('Authorization', `Bearer ${newAccessToken}`)
|
||||
|
||||
const retryResponse = await fetch(`${API_PREFIX}${path}`, {
|
||||
...options,
|
||||
headers: retryHeaders,
|
||||
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
||||
})
|
||||
|
||||
if (!retryResponse.ok) {
|
||||
throw new ApiError(retryResponse.status, await readErrorMessage(retryResponse))
|
||||
}
|
||||
if (retryResponse.status === 204) return undefined as T
|
||||
return (await retryResponse.json()) as T
|
||||
} catch (err) {
|
||||
clearTokens()
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, await readErrorMessage(response))
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
return (await response.json()) as T
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Хранилище токенов вне React-дерева.
|
||||
*
|
||||
* `client.ts` должен уметь читать access-токен и молча обновлять его по 401
|
||||
* без импорта React-контекста (иначе получится цикл api -> auth-context ->
|
||||
* api). Поэтому токены живут в модульном синглтоне, а `AuthProvider`
|
||||
* подписывается на его изменения через `subscribe`.
|
||||
*
|
||||
* access-токен — только в памяти (переживает не дольше вкладки).
|
||||
* refresh-токен — в localStorage, иначе при обновлении страницы
|
||||
* пользователя выкидывало бы из системы каждый раз.
|
||||
*/
|
||||
|
||||
const REFRESH_TOKEN_KEY = 'lux_fiscal.refresh_token'
|
||||
|
||||
interface TokenState {
|
||||
accessToken: string | null
|
||||
refreshToken: string | null
|
||||
}
|
||||
|
||||
let state: TokenState = {
|
||||
accessToken: null,
|
||||
refreshToken: readRefreshTokenFromStorage(),
|
||||
}
|
||||
|
||||
type Listener = (state: TokenState) => void
|
||||
const listeners = new Set<Listener>()
|
||||
|
||||
function readRefreshTokenFromStorage(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY)
|
||||
} catch {
|
||||
// Приватный режим браузера может запрещать доступ к localStorage.
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeRefreshTokenToStorage(token: string | null): void {
|
||||
try {
|
||||
if (token) {
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, token)
|
||||
} else {
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
}
|
||||
} catch {
|
||||
// Не критично: без localStorage просто не переживём перезагрузку страницы.
|
||||
}
|
||||
}
|
||||
|
||||
function notify(): void {
|
||||
for (const listener of listeners) listener(state)
|
||||
}
|
||||
|
||||
export function getAccessToken(): string | null {
|
||||
return state.accessToken
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
return state.refreshToken
|
||||
}
|
||||
|
||||
export function setTokens(accessToken: string, refreshToken: string): void {
|
||||
state = { accessToken, refreshToken }
|
||||
writeRefreshTokenToStorage(refreshToken)
|
||||
notify()
|
||||
}
|
||||
|
||||
export function setAccessToken(accessToken: string): void {
|
||||
state = { ...state, accessToken }
|
||||
notify()
|
||||
}
|
||||
|
||||
export function clearTokens(): void {
|
||||
state = { accessToken: null, refreshToken: null }
|
||||
writeRefreshTokenToStorage(null)
|
||||
notify()
|
||||
}
|
||||
|
||||
/** Вызывается при монтировании AuthProvider и при каждом изменении токенов. */
|
||||
export function subscribeToTokens(listener: Listener): () => void {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Типы, зеркалящие Pydantic-схемы бэкенда (backend/app/schemas/auth.py,
|
||||
* backend/app/db/models/user.py). Меняются синхронно с ними вручную —
|
||||
* генерация клиента из OpenAPI запланирована на более поздний этап.
|
||||
*/
|
||||
|
||||
// `erasableSyntaxOnly` в tsconfig запрещает TS-enum — используем union строк,
|
||||
// он полностью совпадает по значениям с UserRole на бэкенде.
|
||||
export type UserRole = 'admin' | 'cashier' | 'viewer'
|
||||
|
||||
export interface User {
|
||||
id: string
|
||||
email: string
|
||||
full_name: string
|
||||
role: UserRole
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
export interface TokenPair {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
token_type: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
export interface LoginResponse extends TokenPair {
|
||||
user: User
|
||||
}
|
||||
|
||||
export interface ApiErrorBody {
|
||||
detail?: string | { msg: string }[]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
|
||||
import { AppRoutes } from '@/app/routes'
|
||||
import { AuthProvider } from '@/features/auth/AuthContext'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// Данные о заказах/чеках меняются постоянно и опрашиваются отдельно —
|
||||
// глобальный автоповтор через фокус окна тут не нужен.
|
||||
refetchOnWindowFocus: false,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Navigate, Route, Routes } from 'react-router-dom'
|
||||
|
||||
import { LoginPage } from '@/features/auth/LoginPage'
|
||||
import { ProtectedRoute } from '@/features/auth/ProtectedRoute'
|
||||
import { DashboardPage } from '@/pages/DashboardPage'
|
||||
|
||||
export function AppRoutes() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/" element={<DashboardPage />} />
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { createContext, useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import * as authApi from '@/api/auth'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { clearTokens, getRefreshToken, setTokens } from '@/api/tokenStore'
|
||||
import type { User } from '@/api/types'
|
||||
|
||||
type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated'
|
||||
|
||||
interface AuthContextValue {
|
||||
status: AuthStatus
|
||||
user: User | null
|
||||
/** null, пока запрос не завершится (успехом или ошибкой). */
|
||||
error: string | null
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => Promise<void>
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line react/only-export-components -- контекст и провайдер экспортируются вместе намеренно
|
||||
export const AuthContext = createContext<AuthContextValue | null>(null)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
// Если refresh-токена нет, статус известен сразу же, без похода в сеть —
|
||||
// вычисляем его в инициализаторе, а не синхронным setState внутри эффекта.
|
||||
const [status, setStatus] = useState<AuthStatus>(() =>
|
||||
getRefreshToken() ? 'loading' : 'unauthenticated',
|
||||
)
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// При открытии приложения пытаемся восстановить сессию по refresh-токену
|
||||
// из localStorage — иначе каждая перезагрузка страницы требовала бы входа.
|
||||
useEffect(() => {
|
||||
const existingRefreshToken = getRefreshToken()
|
||||
if (!existingRefreshToken) return
|
||||
|
||||
let cancelled = false
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const pair = await authApi.refresh(existingRefreshToken)
|
||||
setTokens(pair.access_token, pair.refresh_token)
|
||||
const me = await authApi.fetchMe()
|
||||
if (cancelled) return
|
||||
setUser(me)
|
||||
setStatus('authenticated')
|
||||
} catch {
|
||||
if (cancelled) return
|
||||
clearTokens()
|
||||
setStatus('unauthenticated')
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
setError(null)
|
||||
try {
|
||||
const result = await authApi.login(email, password)
|
||||
setTokens(result.access_token, result.refresh_token)
|
||||
setUser(result.user)
|
||||
setStatus('authenticated')
|
||||
} catch (err) {
|
||||
const message = err instanceof ApiError ? err.message : 'Не удалось подключиться к серверу'
|
||||
setError(message)
|
||||
throw err
|
||||
}
|
||||
}, [])
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
const refreshToken = getRefreshToken()
|
||||
if (refreshToken) {
|
||||
// Best-effort: даже если сервер недоступен, локально выходим всё равно.
|
||||
try {
|
||||
await authApi.logout(refreshToken)
|
||||
} catch {
|
||||
// Токен и так будет забыт локально ниже.
|
||||
}
|
||||
}
|
||||
clearTokens()
|
||||
setUser(null)
|
||||
setStatus('unauthenticated')
|
||||
}, [])
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({ status, user, error, login, logout }),
|
||||
[status, user, error, login, logout],
|
||||
)
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
.login-page {
|
||||
min-height: 100svh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 380px;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 12px;
|
||||
box-shadow: var(--shadow-card);
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
margin-bottom: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-header h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.login-header p {
|
||||
color: var(--color-text-muted);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.login-field {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-field label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
margin-bottom: 6px;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.login-field input {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.login-field input:focus {
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
.login-field input:disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.login-error {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
background: var(--color-danger-bg);
|
||||
border: 1px solid var(--color-danger-border);
|
||||
color: var(--color-danger);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
font-size: 13px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-submit {
|
||||
width: 100%;
|
||||
padding: 11px 16px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.login-submit:hover:not(:disabled) {
|
||||
background: var(--color-primary-hover);
|
||||
}
|
||||
|
||||
.login-submit:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.login-submit .spinner {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-width: 2px;
|
||||
border-color: rgba(255, 255, 255, 0.4);
|
||||
border-top-color: #fff;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useId, useState } from 'react'
|
||||
import type { FormEvent } from 'react'
|
||||
import { Navigate, useLocation } from 'react-router-dom'
|
||||
|
||||
import { ApiError } from '@/api/client'
|
||||
import '@/features/auth/LoginPage.css'
|
||||
import { useAuth } from '@/features/auth/useAuth'
|
||||
|
||||
interface LocationState {
|
||||
from?: { pathname: string }
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const { status, login } = useAuth()
|
||||
const location = useLocation()
|
||||
|
||||
const emailId = useId()
|
||||
const passwordId = useId()
|
||||
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
// Уже вошли — на странице входа делать нечего.
|
||||
if (status === 'authenticated') {
|
||||
const state = location.state as LocationState | null
|
||||
const redirectTo = state?.from?.pathname ?? '/'
|
||||
return <Navigate to={redirectTo} replace />
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
setFormError(null)
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await login(email, password)
|
||||
} catch (err) {
|
||||
const message = err instanceof ApiError ? err.message : 'Не удалось подключиться к серверу'
|
||||
setFormError(message)
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<div className="login-card">
|
||||
<div className="login-header">
|
||||
<h1>lux_fiscal</h1>
|
||||
<p>Вход в систему фискализации заказов</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
{formError && (
|
||||
<div className="login-error" role="alert">
|
||||
{formError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="login-field">
|
||||
<label htmlFor={emailId}>Email</label>
|
||||
<input
|
||||
id={emailId}
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
required
|
||||
value={email}
|
||||
disabled={submitting}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="login-field">
|
||||
<label htmlFor={passwordId}>Пароль</label>
|
||||
<input
|
||||
id={passwordId}
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
disabled={submitting}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button type="submit" className="login-submit" disabled={submitting}>
|
||||
{submitting && <span className="spinner" aria-hidden="true" />}
|
||||
{submitting ? 'Входим…' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom'
|
||||
|
||||
import { useAuth } from '@/features/auth/useAuth'
|
||||
|
||||
/** Пропускает дальше только аутентифицированных; остальных отправляет на /login. */
|
||||
export function ProtectedRoute() {
|
||||
const { status } = useAuth()
|
||||
const location = useLocation()
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<div className="page-center">
|
||||
<span className="spinner" aria-label="Загрузка" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === 'unauthenticated') {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />
|
||||
}
|
||||
|
||||
return <Outlet />
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useContext } from 'react'
|
||||
|
||||
import { AuthContext } from '@/features/auth/AuthContext'
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) {
|
||||
throw new Error('useAuth должен вызываться внутри <AuthProvider>')
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Глобальные стили и дизайн-токены.
|
||||
* Внутренний рабочий инструмент, не маркетинговая страница — раскладка
|
||||
* на всю ширину, без фиксированной колонки.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--color-bg: #f6f7f9;
|
||||
--color-surface: #ffffff;
|
||||
--color-border: #e2e4e9;
|
||||
--color-text: #1f2430;
|
||||
--color-text-muted: #6b7280;
|
||||
--color-primary: #2563eb;
|
||||
--color-primary-hover: #1d4ed8;
|
||||
--color-danger: #dc2626;
|
||||
--color-danger-bg: #fef2f2;
|
||||
--color-danger-border: #fecaca;
|
||||
--shadow-card: 0 1px 2px rgba(16, 24, 40, 0.05), 0 1px 3px rgba(16, 24, 40, 0.1);
|
||||
|
||||
--font-sans: system-ui, 'Segoe UI', Roboto, sans-serif;
|
||||
|
||||
color-scheme: light dark;
|
||||
font-family: var(--font-sans);
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-bg: #0f1115;
|
||||
--color-surface: #171a21;
|
||||
--color-border: #2a2e38;
|
||||
--color-text: #e5e7eb;
|
||||
--color-text-muted: #9ca3af;
|
||||
--color-primary: #3b82f6;
|
||||
--color-primary-hover: #60a5fa;
|
||||
--color-danger: #f87171;
|
||||
--color-danger-bg: rgba(248, 113, 113, 0.12);
|
||||
--color-danger-border: rgba(248, 113, 113, 0.35);
|
||||
--shadow-card: 0 1px 2px rgba(0, 0, 0, 0.3), 0 1px 3px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
#root {
|
||||
min-height: 100svh;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
/* --- Общие утилиты, используются в нескольких экранах --- */
|
||||
|
||||
.page-center {
|
||||
min-height: 100svh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
border: 3px solid var(--color-border);
|
||||
border-top-color: var(--color-primary);
|
||||
animation: spin 0.7s linear infinite;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
|
||||
import { App } from '@/app/App'
|
||||
import '@/index.css'
|
||||
|
||||
const rootElement = document.getElementById('root')
|
||||
if (!rootElement) {
|
||||
throw new Error('Элемент #root не найден в index.html')
|
||||
}
|
||||
|
||||
createRoot(rootElement).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
.dashboard-shell {
|
||||
min-height: 100svh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dashboard-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 24px;
|
||||
background: var(--color-surface);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.dashboard-brand {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.dashboard-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font-size: 14px;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.dashboard-role {
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-bg);
|
||||
border: 1px solid var(--color-border);
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.dashboard-logout {
|
||||
border: 1px solid var(--color-border);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
border-radius: 8px;
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dashboard-logout:hover {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.dashboard-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.dashboard-placeholder {
|
||||
text-align: center;
|
||||
max-width: 420px;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.dashboard-placeholder h2 {
|
||||
color: var(--color-text);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import '@/pages/DashboardPage.css'
|
||||
import { useAuth } from '@/features/auth/useAuth'
|
||||
|
||||
const ROLE_LABEL: Record<string, string> = {
|
||||
admin: 'Администратор',
|
||||
cashier: 'Кассир',
|
||||
viewer: 'Наблюдатель',
|
||||
}
|
||||
|
||||
/**
|
||||
* Временная заглушка. Очередь «получено, чек не пробит» — этап 6 плана,
|
||||
* пока здесь только подтверждение, что вход и защищённый роут работают.
|
||||
*/
|
||||
export function DashboardPage() {
|
||||
const { user, logout } = useAuth()
|
||||
|
||||
return (
|
||||
<div className="dashboard-shell">
|
||||
<header className="dashboard-topbar">
|
||||
<span className="dashboard-brand">lux_fiscal</span>
|
||||
<div className="dashboard-user">
|
||||
<span>{user?.full_name}</span>
|
||||
<span className="dashboard-role">{user ? (ROLE_LABEL[user.role] ?? user.role) : ''}</span>
|
||||
<button type="button" className="dashboard-logout" onClick={() => void logout()}>
|
||||
Выйти
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="dashboard-body">
|
||||
<div className="dashboard-placeholder">
|
||||
<h2>Очередь заказов появится здесь</h2>
|
||||
<p>
|
||||
Вход выполнен успешно. Экран «получено, чек не пробит» будет добавлен на следующих
|
||||
этапах — после интеграций с Новой Поштой и Checkbox.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"ignoreDeprecations": "6.0",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
},
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import path from 'node:path'
|
||||
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(import.meta.dirname, 'src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
// Бэкенд слушает на 8000 (см. docker-compose.yml). Запросы идут по
|
||||
// относительному пути /api/v1/... — тот же приём работает и в проде,
|
||||
// где /api проксирует nginx. Благодаря этому фронтенд нигде не хранит
|
||||
// абсолютный адрес API и CORS не нужен вообще.
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user