7e435e07b7
Phase 1a из плана: только swap библиотеки, realm/URL остаются на auth.nstart.space/realms/nstart. Phase 2 (intgr с altum auth-service) — отдельный эпик. Зачем. oidc-client-ts с automaticSilentRenew триггерил бесконечный POST /token loop когда refresh_token истекал (см. MR !269 revert, ~30+ 400'к в console, страница залипала на 403). Altum давно ушёл с oidc-client-ts на keycloak-js по той же причине. Новая модель. - src/lib/keycloak.ts — singleton + initKeycloak(check-sso, PKCE) + ensureFreshToken(N) wrapper над kc.updateToken(). Зеркало altum/src/lib/keycloak.ts. - src/stores/authStore.ts — Zustand store: {user, isAuthenticated, isLoading, error}. checkAuth() ждёт initKeycloak, wireKeycloakEvents() → onAuthSuccess/Refresh/Logout/TokenExpired re-снэпшотят store. - src/auth/useAuth.ts — compat shim для react-oidc-context API (auth.user.profile, isAuthenticated, signinSilent, signinRedirect, signoutRedirect, removeUser, error). Все 11 callsites продолжают работать без правок (только сменили путь import'а). - src/api/client.ts — request interceptor дёргает ensureFreshToken(30) ПЕРЕД каждым запросом + attaches Bearer ${getToken()}. 401 interceptor делает ensureFreshToken(0) + retry один раз. Никаких таймеров, никаких setAccessToken/setUnauthorizedHandler holder'ов — keycloak-js сам source of truth. - src/main.tsx — убран <AuthProvider>, <TokenSync />. Просто useAuthStore.getState().checkAuth() на старте, потом обычный render. - public/silent-check-sso.html — endpoint для silentCheckSsoRedirectUri. Удалены. - src/auth/TokenSync.tsx — не нужен, ensureFreshToken на запросах. - src/auth/oidcConfig.ts — не нужен, конфиг внутри lib/keycloak.ts. - npm deps: react-oidc-context, oidc-client-ts. Добавлены deps: keycloak-js@26.2.4, zustand@5.0.13. Tests: 171/171 passed, TSC чистый. Migration callsites — все unchanged по семантике благодаря compat shim.
82 lines
2.6 KiB
TypeScript
82 lines
2.6 KiB
TypeScript
import { useAuth } from '@/auth/useAuth'
|
|
import { useTranslation } from 'react-i18next'
|
|
import { IconButton } from '@/ui'
|
|
import { SignInIcon, SignOutIcon, UserIcon } from '@phosphor-icons/react'
|
|
|
|
/**
|
|
* Бейдж в header'е: «Войти» если anonymous; имя + logout если залогинен.
|
|
*
|
|
* <p>Logout жмёт {@code signoutRedirect} — Keycloak инвалидирует SSO-сессию и
|
|
* вернёт на post-logout-uri (корень).
|
|
*/
|
|
export function AuthBadge() {
|
|
const { t } = useTranslation()
|
|
const auth = useAuth()
|
|
|
|
if (auth.isLoading) {
|
|
return (
|
|
<span className="text-cap text-mute">
|
|
{t('loading')}
|
|
</span>
|
|
)
|
|
}
|
|
|
|
if (auth.error) {
|
|
// Не валим UI — просто кнопка для повтора login.
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={() => auth.signinRedirect()}
|
|
className="h-7 px-2.5 rounded-md border border-line bg-surface text-cell text-ink-2 hover:bg-surface-2 hover:text-ink inline-flex items-center gap-1.5 transition-colors"
|
|
>
|
|
<SignInIcon size={14} weight="regular" />
|
|
{t('auth.login')}
|
|
</button>
|
|
)
|
|
}
|
|
|
|
if (!auth.isAuthenticated) {
|
|
// Compact sign-in button matching TopBar control style (h-8, surface bg).
|
|
// Previously Button variant="primary" — слишком крупно, выбивалось из
|
|
// toolbar style per user feedback ("кнопка Войти слишком большая").
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={() => auth.signinRedirect()}
|
|
className="h-7 px-2.5 rounded-md border border-line bg-surface text-cell text-ink-2 hover:bg-surface-2 hover:text-ink inline-flex items-center gap-1.5 transition-colors"
|
|
>
|
|
<SignInIcon size={14} weight="regular" />
|
|
{t('auth.login')}
|
|
</button>
|
|
)
|
|
}
|
|
|
|
const profile = auth.user?.profile
|
|
const display =
|
|
profile?.preferred_username ||
|
|
profile?.name ||
|
|
profile?.email ||
|
|
profile?.sub ||
|
|
'user'
|
|
|
|
return (
|
|
<div className="flex items-center gap-2">
|
|
<span className="inline-flex items-center gap-1 text-body text-ink">
|
|
<UserIcon size={14} weight="duotone" />
|
|
<span className="hidden sm:inline">{display}</span>
|
|
</span>
|
|
<IconButton
|
|
type="button"
|
|
icon={<SignOutIcon weight="bold" />}
|
|
label={t('auth.logout')}
|
|
onClick={() =>
|
|
auth.signoutRedirect().catch(() => {
|
|
// Если Keycloak недоступен — просто очищаем локальный state.
|
|
auth.removeUser()
|
|
})
|
|
}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|