feat(auth): implement portal SSO and local admin authentication
Added support for portal SSO with JWT authentication and local admin login. Updated environment configuration to include AUTH_REQUIRED, AUTH_JWT_SECRET, AUTH_ISSUER, and AUTH_PORTAL_URL. Enhanced the auth plugin to handle JWT verification based on the new configuration. Introduced new routes for authentication and updated the API client to manage token handling and redirects. Improved user experience by integrating authentication checks across various routes and components.
This commit is contained in:
@@ -8,6 +8,7 @@ import {
|
||||
SettingsIcon,
|
||||
} from 'lucide-react'
|
||||
import { AppSwitcher } from '@/components/app-switcher'
|
||||
import { NavUser } from '@/components/nav-user'
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -106,7 +107,9 @@ export function AppSidebar() {
|
||||
<NavSection label="Инфраструктура" items={infrastructureNav} pathname={pathname} />
|
||||
<NavSection label="Операции" items={operationsNav} pathname={pathname} />
|
||||
</SidebarContent>
|
||||
<SidebarFooter />
|
||||
<SidebarFooter>
|
||||
<NavUser />
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
BreadcrumbSeparator,
|
||||
} from '@cfdm/ui/components/breadcrumb'
|
||||
import { Separator } from '@cfdm/ui/components/separator'
|
||||
import { ModeToggle } from '@/components/mode-toggle'
|
||||
import { SystemMonitorPopover } from '@/components/layout/system-monitor-popover'
|
||||
import { AppsMenu } from '@/components/layout/apps-menu'
|
||||
import { SidebarTrigger } from '@cfdm/ui/components/sidebar'
|
||||
@@ -93,7 +92,7 @@ function useDynamicBreadcrumbLabels() {
|
||||
}, [matches])
|
||||
}
|
||||
|
||||
/** Header chrome — etalon EvoBGP (Trigger + Separator + Breadcrumb + Apps/Monitor/Mode). */
|
||||
/** Header chrome — AppsMenu + SystemMonitor; theme in NavUser (app-shell-1). */
|
||||
export function SiteHeader() {
|
||||
const pathname = useRouterState({ select: (s) => s.location.pathname })
|
||||
const dynamicLabels = useDynamicBreadcrumbLabels()
|
||||
@@ -131,7 +130,6 @@ export function SiteHeader() {
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<AppsMenu />
|
||||
<SystemMonitorPopover />
|
||||
<ModeToggle />
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { AppAvatar, AppAvatarFallback } from '@/components/app-avatar'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import {
|
||||
ChevronsUpDownIcon,
|
||||
LogOutIcon,
|
||||
MonitorIcon,
|
||||
MoonIcon,
|
||||
PaletteIcon,
|
||||
SettingsIcon,
|
||||
SunIcon,
|
||||
} from 'lucide-react'
|
||||
|
||||
import { cn } from '@cfdm/ui/lib/utils'
|
||||
import {
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
} from '@cfdm/ui/components/avatar'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -15,16 +32,108 @@ import {
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from '@cfdm/ui/components/sidebar'
|
||||
import { ChevronsUpDownIcon, LogOutIcon } from 'lucide-react'
|
||||
import { clearToken } from '@/lib/auth'
|
||||
|
||||
import {
|
||||
can,
|
||||
clearToken,
|
||||
getClaims,
|
||||
isAuthEnabled,
|
||||
redirectToPortalLogin,
|
||||
resetPortalHandoff,
|
||||
} from '@/lib/auth'
|
||||
|
||||
/** Sidebar footer account menu — ReUI app-shell-1 NavUser. @see https://reui.io/preview/base/app-shell-1 */
|
||||
|
||||
const THEMES = [
|
||||
{
|
||||
value: 'light',
|
||||
label: 'Светлая',
|
||||
icon: <SunIcon className="size-3.5" aria-hidden />,
|
||||
},
|
||||
{
|
||||
value: 'dark',
|
||||
label: 'Тёмная',
|
||||
icon: <MoonIcon className="size-3.5" aria-hidden />,
|
||||
},
|
||||
{
|
||||
value: 'system',
|
||||
label: 'Системная',
|
||||
icon: <MonitorIcon className="size-3.5" aria-hidden />,
|
||||
},
|
||||
] as const
|
||||
|
||||
function ThemeSegmentedToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const [mounted, setMounted] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
|
||||
const currentTheme = mounted ? (theme ?? 'system') : 'system'
|
||||
|
||||
return (
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label="Тема"
|
||||
className="bg-muted/60 inline-flex items-center gap-0.5 rounded-full p-0.5"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
{THEMES.map(({ value, label, icon }) => {
|
||||
const isActive = currentTheme === value
|
||||
return (
|
||||
<Button
|
||||
key={value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={isActive}
|
||||
aria-label={label}
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={() => setTheme(value)}
|
||||
className={cn(
|
||||
'rounded-full',
|
||||
isActive
|
||||
? 'bg-background text-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
</Button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function initials(name: string, email: string): string {
|
||||
const base = name.trim() || email.trim()
|
||||
if (!base) return '?'
|
||||
const parts = base.split(/\s+/).filter(Boolean)
|
||||
if (parts.length >= 2) {
|
||||
return `${parts[0]![0] ?? ''}${parts[1]![0] ?? ''}`.toUpperCase()
|
||||
}
|
||||
return base.slice(0, 2).toUpperCase()
|
||||
}
|
||||
|
||||
export function NavUser() {
|
||||
const navigate = useNavigate()
|
||||
const { isMobile } = useSidebar()
|
||||
const claims = getClaims()
|
||||
const authOn = isAuthEnabled()
|
||||
|
||||
const handleLogout = () => {
|
||||
const name = claims?.name?.trim() || (authOn ? 'Пользователь' : 'Гость')
|
||||
const email = claims?.email?.trim() || (authOn ? '' : 'auth выключен')
|
||||
const fallback = initials(name, email)
|
||||
|
||||
function handleSignOut() {
|
||||
clearToken()
|
||||
navigate({ to: '/login' })
|
||||
resetPortalHandoff()
|
||||
if (authOn) {
|
||||
redirectToPortalLogin()
|
||||
return
|
||||
}
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -33,42 +142,75 @@ export function NavUser() {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" />
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
className="data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<AppAvatar>
|
||||
<AppAvatarFallback>АД</AppAvatarFallback>
|
||||
</AppAvatar>
|
||||
<Avatar className="size-8 rounded-lg">
|
||||
<AvatarFallback className="rounded-lg text-xs">
|
||||
{fallback}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">Администратор</span>
|
||||
<span className="truncate text-xs">admin</span>
|
||||
<span className="truncate font-semibold">{name}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{email || '—'}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronsUpDownIcon className="ml-auto size-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-56"
|
||||
className="w-(--anchor-width) min-w-56 rounded-lg"
|
||||
side={isMobile ? 'bottom' : 'right'}
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel className="p-0 font-normal">
|
||||
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
||||
<AppAvatar>
|
||||
<AppAvatarFallback>АД</AppAvatarFallback>
|
||||
</AppAvatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-medium">Администратор</span>
|
||||
<span className="truncate text-xs">admin</span>
|
||||
</div>
|
||||
<DropdownMenuLabel className="flex items-center gap-2 py-2 font-normal text-foreground">
|
||||
<Avatar className="size-8 rounded-lg">
|
||||
<AvatarFallback className="rounded-lg text-xs">
|
||||
{fallback}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid min-w-0 flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">{name}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{email || '—'}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
</DropdownMenuGroup>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout}>
|
||||
<LogOutIcon />
|
||||
Выйти
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuGroup>
|
||||
{can('cfdm:settings:admin') ? (
|
||||
<DropdownMenuItem
|
||||
nativeButton={false}
|
||||
render={<Link to="/settings/appearance" />}
|
||||
>
|
||||
<SettingsIcon aria-hidden />
|
||||
Настройки
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
<DropdownMenuItem className="cursor-default focus:bg-transparent">
|
||||
<PaletteIcon aria-hidden />
|
||||
Тема
|
||||
<div className="ml-auto">
|
||||
<ThemeSegmentedToggle />
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={handleSignOut}>
|
||||
<LogOutIcon aria-hidden />
|
||||
Выйти
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
import {
|
||||
clearToken,
|
||||
ensureAuthConfig,
|
||||
getToken,
|
||||
hasPortalHandoffFlag,
|
||||
isAuthEnabled,
|
||||
isPortalHandoffCoolingDown,
|
||||
redirectToPortalLogin,
|
||||
} from '@/lib/auth'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
@@ -9,8 +19,24 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
async function handoffOnUnauthorized(): Promise<void> {
|
||||
clearToken()
|
||||
const cfg = await ensureAuthConfig()
|
||||
if (
|
||||
(cfg.required || isAuthEnabled()) &&
|
||||
!hasPortalHandoffFlag() &&
|
||||
!isPortalHandoffCoolingDown()
|
||||
) {
|
||||
redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
||||
return
|
||||
}
|
||||
if (!cfg.required && !isAuthEnabled()) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const token = localStorage.getItem('cfdm_token')
|
||||
const token = getToken()
|
||||
const headers = new Headers(init?.headers)
|
||||
if (init?.body != null && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json')
|
||||
@@ -19,8 +45,7 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
|
||||
const res = await fetch(path, { ...init, headers })
|
||||
if (res.status === 401 && !path.includes('/auth/login')) {
|
||||
localStorage.removeItem('cfdm_token')
|
||||
window.location.href = '/login'
|
||||
await handoffOnUnauthorized()
|
||||
throw new ApiError(401, 'UNAUTHORIZED', 'Unauthorized')
|
||||
}
|
||||
if (!res.ok) {
|
||||
|
||||
+243
-3
@@ -1,11 +1,251 @@
|
||||
/** Portal JWT storage + claims helpers for Cloudflare Domain Manager. */
|
||||
|
||||
const TOKEN_KEY = 'cfdm_token'
|
||||
const HANDOFF_KEY = 'cfdm_auth_401_handoff'
|
||||
const HANDOFF_AT_KEY = 'cfdm_portal_handoff_at'
|
||||
/** Min gap between portal handoffs — breaks SSO↔401 redirect storms. */
|
||||
const HANDOFF_COOLDOWN_MS = 12_000
|
||||
const API_BASE = import.meta.env.VITE_API_URL ?? ''
|
||||
|
||||
export type AccessClaims = {
|
||||
sub: string
|
||||
email: string
|
||||
name: string
|
||||
apps: string[]
|
||||
permissions: string[]
|
||||
is_admin?: boolean
|
||||
iss?: string
|
||||
exp?: number
|
||||
}
|
||||
|
||||
export type RuntimeAuthConfig = {
|
||||
required: boolean
|
||||
portalUrl: string
|
||||
}
|
||||
|
||||
let runtimeConfig: RuntimeAuthConfig | null = null
|
||||
let runtimeConfigPromise: Promise<RuntimeAuthConfig> | null = null
|
||||
|
||||
function viteAuthEnabled(): boolean {
|
||||
return (
|
||||
import.meta.env.VITE_AUTH_ENABLED === 'true' ||
|
||||
import.meta.env.VITE_AUTH_ENABLED === '1'
|
||||
)
|
||||
}
|
||||
|
||||
function vitePortalUrl(): string {
|
||||
return (import.meta.env.VITE_AUTH_PORTAL_URL ?? 'http://localhost:5175').replace(
|
||||
/\/$/,
|
||||
'',
|
||||
)
|
||||
}
|
||||
|
||||
/** Load auth mode from API (Docker-friendly). Falls back to VITE_* flags. */
|
||||
export async function ensureAuthConfig(): Promise<RuntimeAuthConfig> {
|
||||
if (runtimeConfig) return runtimeConfig
|
||||
if (runtimeConfigPromise) return runtimeConfigPromise
|
||||
|
||||
runtimeConfigPromise = (async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/v1/auth/config`)
|
||||
if (res.ok) {
|
||||
const data = (await res.json()) as {
|
||||
required?: boolean
|
||||
portal_url?: string
|
||||
}
|
||||
runtimeConfig = {
|
||||
required: Boolean(data.required) || viteAuthEnabled(),
|
||||
portalUrl: (data.portal_url || vitePortalUrl()).replace(/\/$/, ''),
|
||||
}
|
||||
return runtimeConfig
|
||||
}
|
||||
} catch {
|
||||
/* ignore — use vite defaults */
|
||||
}
|
||||
runtimeConfig = {
|
||||
required: viteAuthEnabled(),
|
||||
portalUrl: vitePortalUrl(),
|
||||
}
|
||||
return runtimeConfig
|
||||
})().finally(() => {
|
||||
runtimeConfigPromise = null
|
||||
})
|
||||
|
||||
return runtimeConfigPromise
|
||||
}
|
||||
|
||||
export function getAuthConfigSync(): RuntimeAuthConfig | null {
|
||||
return runtimeConfig
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
return localStorage.getItem('cfdm_token')
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function setToken(token: string) {
|
||||
localStorage.setItem('cfdm_token', token)
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
}
|
||||
|
||||
export function clearToken() {
|
||||
localStorage.removeItem('cfdm_token')
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function isAuthEnabled(): boolean {
|
||||
if (runtimeConfig) return runtimeConfig.required
|
||||
return viteAuthEnabled()
|
||||
}
|
||||
|
||||
export function authPortalUrl(): string {
|
||||
if (runtimeConfig?.portalUrl) return runtimeConfig.portalUrl
|
||||
return vitePortalUrl()
|
||||
}
|
||||
|
||||
/** True when another portal handoff happened too recently (SSO loop guard). */
|
||||
export function isPortalHandoffCoolingDown(): boolean {
|
||||
const raw = sessionStorage.getItem(HANDOFF_AT_KEY)
|
||||
if (!raw) return false
|
||||
const at = Number(raw)
|
||||
if (!Number.isFinite(at)) return false
|
||||
return Date.now() - at < HANDOFF_COOLDOWN_MS
|
||||
}
|
||||
|
||||
export function markPortalHandoff(): void {
|
||||
sessionStorage.setItem(HANDOFF_KEY, '1')
|
||||
sessionStorage.setItem(HANDOFF_AT_KEY, String(Date.now()))
|
||||
}
|
||||
|
||||
export function clearPortalHandoffFlag(): void {
|
||||
sessionStorage.removeItem(HANDOFF_KEY)
|
||||
}
|
||||
|
||||
/** Clear cooldown too — use on intentional logout so next login is allowed. */
|
||||
export function resetPortalHandoff(): void {
|
||||
sessionStorage.removeItem(HANDOFF_KEY)
|
||||
sessionStorage.removeItem(HANDOFF_AT_KEY)
|
||||
}
|
||||
|
||||
export function hasPortalHandoffFlag(): boolean {
|
||||
return sessionStorage.getItem(HANDOFF_KEY) === '1'
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect to auth-portal SSO. Returns false if cooldown blocks the handoff
|
||||
* (clears local token) — prevents infinite SSO when API rejects JWT.
|
||||
*/
|
||||
export function redirectToPortalLogin(returnTo?: string): boolean {
|
||||
if (isPortalHandoffCoolingDown()) {
|
||||
clearToken()
|
||||
return false
|
||||
}
|
||||
markPortalHandoff()
|
||||
const callback =
|
||||
returnTo ?? `${window.location.origin}/auth/callback`
|
||||
const url = new URL(authPortalUrl())
|
||||
url.searchParams.set('return_to', callback)
|
||||
window.location.assign(url.toString())
|
||||
return true
|
||||
}
|
||||
|
||||
export function parseHashToken(hash: string): {
|
||||
accessToken: string | null
|
||||
expiresAt: string | null
|
||||
} {
|
||||
const raw = hash.startsWith('#') ? hash.slice(1) : hash
|
||||
const params = new URLSearchParams(raw)
|
||||
return {
|
||||
accessToken: params.get('access_token'),
|
||||
expiresAt: params.get('expires_at'),
|
||||
}
|
||||
}
|
||||
|
||||
export function decodeClaims(token: string): AccessClaims | null {
|
||||
try {
|
||||
const parts = token.split('.')
|
||||
if (parts.length < 2) return null
|
||||
const json = atob(parts[1]!.replace(/-/g, '+').replace(/_/g, '/'))
|
||||
const payload = JSON.parse(json) as Record<string, unknown>
|
||||
return {
|
||||
sub: String(payload.sub ?? ''),
|
||||
email: String(payload.email ?? ''),
|
||||
name: String(payload.name ?? ''),
|
||||
apps: Array.isArray(payload.apps) ? payload.apps.map(String) : [],
|
||||
permissions: Array.isArray(payload.permissions)
|
||||
? payload.permissions.map(String)
|
||||
: [],
|
||||
is_admin: Boolean(payload.is_admin),
|
||||
iss: payload.iss ? String(payload.iss) : undefined,
|
||||
exp: typeof payload.exp === 'number' ? payload.exp : undefined,
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getClaims(): AccessClaims | null {
|
||||
const token = getToken()
|
||||
if (!token) return null
|
||||
const claims = decodeClaims(token)
|
||||
if (!claims) return null
|
||||
if (claims.exp && claims.exp * 1000 < Date.now()) {
|
||||
clearToken()
|
||||
return null
|
||||
}
|
||||
return claims
|
||||
}
|
||||
|
||||
export function hasPermission(
|
||||
granted: readonly string[],
|
||||
required: string,
|
||||
): boolean {
|
||||
if (granted.includes(required)) return true
|
||||
const parts = required.split(':')
|
||||
if (parts.length !== 3) return false
|
||||
const [app, section, action] = parts
|
||||
if (action === 'read') {
|
||||
return (
|
||||
granted.includes(`${app}:${section}:write`) ||
|
||||
granted.includes(`${app}:${section}:admin`)
|
||||
)
|
||||
}
|
||||
if (action === 'write') {
|
||||
return granted.includes(`${app}:${section}:admin`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function can(required: string): boolean {
|
||||
if (!isAuthEnabled()) return true
|
||||
const claims = getClaims()
|
||||
if (!claims) return false
|
||||
if (!claims.apps.includes('cfdm')) return false
|
||||
return hasPermission(claims.permissions, required)
|
||||
}
|
||||
|
||||
/** Nav path → minimum permission to show the item. */
|
||||
export function permissionForPath(pathname: string): string | null {
|
||||
if (pathname === '/' || pathname.startsWith('/dashboard')) {
|
||||
return 'cfdm:domains:read'
|
||||
}
|
||||
if (pathname.startsWith('/domains')) return 'cfdm:domains:read'
|
||||
if (pathname.startsWith('/groups')) return 'cfdm:groups:read'
|
||||
if (pathname.startsWith('/services')) return 'cfdm:services:read'
|
||||
if (pathname.startsWith('/certificates')) return 'cfdm:certificates:read'
|
||||
if (pathname.startsWith('/settings')) return 'cfdm:settings:admin'
|
||||
return 'cfdm:domains:read'
|
||||
}
|
||||
|
||||
export function firstAllowedPath(): string {
|
||||
const candidates = [
|
||||
'/',
|
||||
'/domains',
|
||||
'/groups',
|
||||
'/services',
|
||||
'/certificates',
|
||||
'/settings/appearance',
|
||||
]
|
||||
for (const path of candidates) {
|
||||
const perm = permissionForPath(path)
|
||||
if (!perm || can(perm)) return path
|
||||
}
|
||||
return '/'
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as AuthRouteImport } from './routes/_auth'
|
||||
import { Route as AuthIndexRouteImport } from './routes/_auth/index'
|
||||
import { Route as AuthCallbackRouteImport } from './routes/auth.callback'
|
||||
import { Route as AuthServicesRouteImport } from './routes/_auth/services'
|
||||
import { Route as AuthGroupsRouteImport } from './routes/_auth/groups'
|
||||
import { Route as AuthCertificatesRouteImport } from './routes/_auth/certificates'
|
||||
@@ -38,6 +39,11 @@ const AuthIndexRoute = AuthIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => AuthRoute,
|
||||
} as any)
|
||||
const AuthCallbackRoute = AuthCallbackRouteImport.update({
|
||||
id: '/auth/callback',
|
||||
path: '/auth/callback',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthServicesRoute = AuthServicesRouteImport.update({
|
||||
id: '/services',
|
||||
path: '/services',
|
||||
@@ -103,6 +109,7 @@ export interface FileRoutesByFullPath {
|
||||
'/certificates': typeof AuthCertificatesRoute
|
||||
'/groups': typeof AuthGroupsRouteWithChildren
|
||||
'/services': typeof AuthServicesRoute
|
||||
'/auth/callback': typeof AuthCallbackRoute
|
||||
'/groups/$groupId': typeof AuthGroupsGroupIdRoute
|
||||
'/settings/appearance': typeof AuthSettingsAppearanceRoute
|
||||
'/settings/integrations': typeof AuthSettingsIntegrationsRoute
|
||||
@@ -116,6 +123,7 @@ export interface FileRoutesByTo {
|
||||
'/certificates': typeof AuthCertificatesRoute
|
||||
'/groups': typeof AuthGroupsRouteWithChildren
|
||||
'/services': typeof AuthServicesRoute
|
||||
'/auth/callback': typeof AuthCallbackRoute
|
||||
'/': typeof AuthIndexRoute
|
||||
'/groups/$groupId': typeof AuthGroupsGroupIdRoute
|
||||
'/settings/appearance': typeof AuthSettingsAppearanceRoute
|
||||
@@ -133,6 +141,7 @@ export interface FileRoutesById {
|
||||
'/_auth/certificates': typeof AuthCertificatesRoute
|
||||
'/_auth/groups': typeof AuthGroupsRouteWithChildren
|
||||
'/_auth/services': typeof AuthServicesRoute
|
||||
'/auth/callback': typeof AuthCallbackRoute
|
||||
'/_auth/': typeof AuthIndexRoute
|
||||
'/_auth/groups/$groupId': typeof AuthGroupsGroupIdRoute
|
||||
'/_auth/settings/appearance': typeof AuthSettingsAppearanceRoute
|
||||
@@ -151,6 +160,7 @@ export interface FileRouteTypes {
|
||||
| '/certificates'
|
||||
| '/groups'
|
||||
| '/services'
|
||||
| '/auth/callback'
|
||||
| '/groups/$groupId'
|
||||
| '/settings/appearance'
|
||||
| '/settings/integrations'
|
||||
@@ -164,6 +174,7 @@ export interface FileRouteTypes {
|
||||
| '/certificates'
|
||||
| '/groups'
|
||||
| '/services'
|
||||
| '/auth/callback'
|
||||
| '/'
|
||||
| '/groups/$groupId'
|
||||
| '/settings/appearance'
|
||||
@@ -180,6 +191,7 @@ export interface FileRouteTypes {
|
||||
| '/_auth/certificates'
|
||||
| '/_auth/groups'
|
||||
| '/_auth/services'
|
||||
| '/auth/callback'
|
||||
| '/_auth/'
|
||||
| '/_auth/groups/$groupId'
|
||||
| '/_auth/settings/appearance'
|
||||
@@ -193,6 +205,7 @@ export interface FileRouteTypes {
|
||||
export interface RootRouteChildren {
|
||||
AuthRoute: typeof AuthRouteWithChildren
|
||||
LoginRoute: typeof LoginRoute
|
||||
AuthCallbackRoute: typeof AuthCallbackRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -218,6 +231,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthIndexRouteImport
|
||||
parentRoute: typeof AuthRoute
|
||||
}
|
||||
'/auth/callback': {
|
||||
id: '/auth/callback'
|
||||
path: '/auth/callback'
|
||||
fullPath: '/auth/callback'
|
||||
preLoaderRoute: typeof AuthCallbackRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_auth/services': {
|
||||
id: '/_auth/services'
|
||||
path: '/services'
|
||||
@@ -352,6 +372,7 @@ const AuthRouteWithChildren = AuthRoute._addFileChildren(AuthRouteChildren)
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
AuthRoute: AuthRouteWithChildren,
|
||||
LoginRoute: LoginRoute,
|
||||
AuthCallbackRoute: AuthCallbackRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { createRootRouteWithContext, Outlet, redirect } from '@tanstack/react-router'
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { getToken } from '@/lib/auth'
|
||||
import {
|
||||
ensureAuthConfig,
|
||||
getClaims,
|
||||
getToken,
|
||||
redirectToPortalLogin,
|
||||
} from '@/lib/auth'
|
||||
|
||||
export interface RouterContext {
|
||||
queryClient: QueryClient
|
||||
@@ -8,9 +13,46 @@ export interface RouterContext {
|
||||
|
||||
export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
component: () => <Outlet />,
|
||||
beforeLoad: ({ location }) => {
|
||||
beforeLoad: async ({ location }) => {
|
||||
const isLogin = location.pathname === '/login'
|
||||
const isCallback = location.pathname === '/auth/callback'
|
||||
if (isCallback) return
|
||||
|
||||
const cfg = await ensureAuthConfig()
|
||||
const token = getToken()
|
||||
const claims = getClaims()
|
||||
|
||||
if (cfg.required) {
|
||||
if (isLogin) {
|
||||
const ok = redirectToPortalLogin(
|
||||
`${window.location.origin}/auth/callback`,
|
||||
)
|
||||
if (!ok) {
|
||||
throw redirect({
|
||||
to: '/auth/callback',
|
||||
search: { error: 'sso_loop' },
|
||||
})
|
||||
}
|
||||
await new Promise(() => {})
|
||||
return
|
||||
}
|
||||
if (!token || !claims) {
|
||||
const ok = redirectToPortalLogin(
|
||||
`${window.location.origin}/auth/callback`,
|
||||
)
|
||||
if (!ok) {
|
||||
throw redirect({
|
||||
to: '/auth/callback',
|
||||
search: { error: 'sso_loop' },
|
||||
})
|
||||
}
|
||||
await new Promise(() => {})
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Local auth mode (AUTH_REQUIRED=false)
|
||||
if (!token && !isLogin) {
|
||||
throw redirect({ to: '/login' })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,47 @@
|
||||
import { createFileRoute, Outlet } from '@tanstack/react-router'
|
||||
import { Outlet, createFileRoute, redirect } from '@tanstack/react-router'
|
||||
import { AppShell } from '@/components/layout/app-shell'
|
||||
import {
|
||||
can,
|
||||
ensureAuthConfig,
|
||||
firstAllowedPath,
|
||||
getClaims,
|
||||
getToken,
|
||||
permissionForPath,
|
||||
redirectToPortalLogin,
|
||||
} from '@/lib/auth'
|
||||
|
||||
export const Route = createFileRoute('/_auth')({
|
||||
beforeLoad: async ({ location }) => {
|
||||
const cfg = await ensureAuthConfig()
|
||||
if (!cfg.required) return
|
||||
|
||||
const token = getToken()
|
||||
const claims = getClaims()
|
||||
if (!token || !claims) {
|
||||
const ok = redirectToPortalLogin(
|
||||
`${window.location.origin}/auth/callback`,
|
||||
)
|
||||
if (!ok) {
|
||||
throw redirect({
|
||||
to: '/auth/callback',
|
||||
search: { error: 'sso_loop' },
|
||||
})
|
||||
}
|
||||
await new Promise(() => {})
|
||||
return
|
||||
}
|
||||
if (!claims.apps.includes('cfdm')) {
|
||||
throw redirect({ to: '/' })
|
||||
}
|
||||
|
||||
const perm = permissionForPath(location.pathname)
|
||||
if (perm && !can(perm)) {
|
||||
const fallback = firstAllowedPath()
|
||||
if (fallback !== location.pathname) {
|
||||
throw redirect({ to: fallback as '/' })
|
||||
}
|
||||
}
|
||||
},
|
||||
component: () => (
|
||||
<AppShell>
|
||||
<Outlet />
|
||||
|
||||
@@ -4,7 +4,12 @@ import { toast } from 'sonner'
|
||||
import { LogOutIcon, PaletteIcon } from 'lucide-react'
|
||||
|
||||
import { api } from '@/lib/api-client'
|
||||
import { clearToken } from '@/lib/auth'
|
||||
import {
|
||||
clearToken,
|
||||
isAuthEnabled,
|
||||
redirectToPortalLogin,
|
||||
resetPortalHandoff,
|
||||
} from '@/lib/auth'
|
||||
import { SettingRow } from '@/components/setting-row'
|
||||
import { Switch } from '@cfdm/ui/components/switch'
|
||||
import { Button } from '@cfdm/ui/components/button'
|
||||
@@ -53,6 +58,11 @@ function AppearanceSettingsPage() {
|
||||
|
||||
const handleLogout = () => {
|
||||
clearToken()
|
||||
resetPortalHandoff()
|
||||
if (isAuthEnabled()) {
|
||||
redirectToPortalLogin()
|
||||
return
|
||||
}
|
||||
void navigate({ to: '/login' })
|
||||
}
|
||||
|
||||
@@ -82,7 +92,7 @@ function AppearanceSettingsPage() {
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
title="Сессия"
|
||||
description="Выйти из учётной записи администратора."
|
||||
description="Выйти из учётной записи."
|
||||
last
|
||||
>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleLogout}>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||
import {
|
||||
authPortalUrl,
|
||||
clearPortalHandoffFlag,
|
||||
clearToken,
|
||||
ensureAuthConfig,
|
||||
firstAllowedPath,
|
||||
getClaims,
|
||||
getToken,
|
||||
parseHashToken,
|
||||
redirectToPortalLogin,
|
||||
setToken,
|
||||
} from '@/lib/auth'
|
||||
|
||||
export const Route = createFileRoute('/auth/callback')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
error: typeof search.error === 'string' ? search.error : undefined,
|
||||
}),
|
||||
beforeLoad: async ({ search }) => {
|
||||
await ensureAuthConfig()
|
||||
|
||||
if (search.error === 'sso_loop') {
|
||||
return
|
||||
}
|
||||
|
||||
const { accessToken } = parseHashToken(window.location.hash)
|
||||
if (accessToken) {
|
||||
setToken(accessToken)
|
||||
clearPortalHandoffFlag()
|
||||
const claims = getClaims()
|
||||
if (!claims) {
|
||||
clearToken()
|
||||
window.location.assign(authPortalUrl())
|
||||
await new Promise(() => {})
|
||||
return
|
||||
}
|
||||
throw redirect({ to: firstAllowedPath() as '/' })
|
||||
}
|
||||
if (getToken() && getClaims()) {
|
||||
clearPortalHandoffFlag()
|
||||
throw redirect({ to: firstAllowedPath() as '/' })
|
||||
}
|
||||
const ok = redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
||||
if (!ok) {
|
||||
throw redirect({ to: '/auth/callback', search: { error: 'sso_loop' } })
|
||||
}
|
||||
await new Promise(() => {})
|
||||
},
|
||||
component: AuthCallbackPage,
|
||||
})
|
||||
|
||||
function AuthCallbackPage() {
|
||||
const { error } = Route.useSearch()
|
||||
if (error === 'sso_loop') {
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-3 p-6 text-center">
|
||||
<h1 className="text-lg font-semibold">Сессия не принята</h1>
|
||||
<p className="text-muted-foreground max-w-md text-sm">
|
||||
Повторный вход через portal остановлен (защита от цикла редиректов).
|
||||
Обычно это несовпадение JWT_SECRET / ISSUER или просроченный токен.
|
||||
Войдите заново на portal, затем откройте Cloudflare Domain Manager.
|
||||
</p>
|
||||
<a className="text-primary text-sm underline" href={authPortalUrl()}>
|
||||
Открыть Auth Portal
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { createFileRoute, Link, redirect } from '@tanstack/react-router'
|
||||
import { CloudIcon } from 'lucide-react'
|
||||
import { Frame, FramePanel } from '@/components/reui/frame'
|
||||
import {
|
||||
@@ -6,8 +6,24 @@ import {
|
||||
AUTH13_SIDEBAR_IMAGE_LIGHT,
|
||||
} from '@/lib/auth-13-assets'
|
||||
import { LoginForm } from '@/components/login-form'
|
||||
import { ensureAuthConfig, redirectToPortalLogin } from '@/lib/auth'
|
||||
|
||||
export const Route = createFileRoute('/login')({
|
||||
beforeLoad: async () => {
|
||||
const cfg = await ensureAuthConfig()
|
||||
if (cfg.required) {
|
||||
const ok = redirectToPortalLogin(
|
||||
`${window.location.origin}/auth/callback`,
|
||||
)
|
||||
if (!ok) {
|
||||
throw redirect({
|
||||
to: '/auth/callback',
|
||||
search: { error: 'sso_loop' },
|
||||
})
|
||||
}
|
||||
await new Promise(() => {})
|
||||
}
|
||||
},
|
||||
component: LoginPage,
|
||||
})
|
||||
|
||||
|
||||
Vendored
+3
@@ -2,6 +2,9 @@
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_APP_SWITCHER?: string
|
||||
readonly VITE_API_URL?: string
|
||||
readonly VITE_AUTH_ENABLED?: string
|
||||
readonly VITE_AUTH_PORTAL_URL?: string
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
Reference in New Issue
Block a user