* overhaul OIDC: backend token exchange, security hardening, group mapping, session management * add unit tests for OIDC overhaul (166 tests across 12 classes) * rewrite unit tests for metadata and extractor packages (~450 tests) * fix Kobo sync timeout with large magic shelves (#3172)
This commit is contained in:
@@ -18,6 +18,7 @@ import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {scan, withLatestFrom} from 'rxjs/operators';
|
||||
import {AuthService} from './shared/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -44,6 +45,7 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
private libraryService = inject(LibraryService);
|
||||
private libraryHealthService = inject(LibraryHealthService);
|
||||
private libraryLoadingService = inject(LibraryLoadingService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
ngOnInit(): void {
|
||||
window.addEventListener('online', this.onOnline);
|
||||
@@ -149,6 +151,11 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
this.taskService.handleTaskProgress(progress);
|
||||
})
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/session-revoked').subscribe(() => {
|
||||
this.authService.forceLogout('session_revoked');
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
|
||||
@@ -2,7 +2,6 @@ import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {initializeAuthFactory} from './auth-initializer';
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
@@ -16,8 +15,7 @@ describe('initializeAuthFactory', () => {
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: OAuthService, useValue: {configure: vi.fn(), loadDiscoveryDocumentAndTryLogin: vi.fn()}},
|
||||
{provide: AuthService, useValue: {tokenSubject: {next: vi.fn()}}},
|
||||
{provide: AuthService, useValue: {tokenSubject: {next: vi.fn()}, getInternalAccessToken: vi.fn()}},
|
||||
{provide: AppSettingsService, useValue: {publicAppSettings$: publicSettingsSubject.asObservable()}},
|
||||
AuthInitializationService,
|
||||
]
|
||||
@@ -34,7 +32,7 @@ describe('initializeAuthFactory', () => {
|
||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||
|
||||
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!});
|
||||
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false});
|
||||
|
||||
await initPromise;
|
||||
|
||||
@@ -51,7 +49,7 @@ describe('initializeAuthFactory', () => {
|
||||
const factory = TestBed.runInInjectionContext(() => initializeAuthFactory());
|
||||
const initPromise = TestBed.runInInjectionContext(() => factory());
|
||||
|
||||
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!});
|
||||
publicSettingsSubject.next({oidcEnabled: false, remoteAuthEnabled: false, oidcProviderDetails: null!, oidcForceOnlyMode: false});
|
||||
|
||||
await initPromise;
|
||||
|
||||
|
||||
@@ -1,27 +1,12 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AuthService, websocketInitializer} from '../../shared/service/auth.service';
|
||||
import {AppSettingsService} from '../../shared/service/app-settings.service';
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
|
||||
const OIDC_BYPASS_KEY = 'booklore-oidc-bypass';
|
||||
const OIDC_ERROR_COUNT_KEY = 'booklore-oidc-error-count';
|
||||
const MAX_OIDC_RETRIES = 3;
|
||||
const OIDC_TIMEOUT_MS = 5000;
|
||||
const SETTINGS_TIMEOUT_MS = 10000;
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise<T>((_, reject) =>
|
||||
setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
export function initializeAuthFactory() {
|
||||
return () => {
|
||||
const oauthService = inject(OAuthService);
|
||||
const appSettingsService = inject(AppSettingsService);
|
||||
const authService = inject(AuthService);
|
||||
const authInitService = inject(AuthInitializationService);
|
||||
@@ -38,73 +23,8 @@ export function initializeAuthFactory() {
|
||||
const sub = appSettingsService.publicAppSettings$.subscribe(publicSettings => {
|
||||
if (publicSettings) {
|
||||
clearTimeout(settingsTimeout);
|
||||
const forceLocalOnly = new URLSearchParams(window.location.search).get('localOnly') === 'true';
|
||||
const oidcBypassed = localStorage.getItem(OIDC_BYPASS_KEY) === 'true';
|
||||
const errorCount = parseInt(localStorage.getItem(OIDC_ERROR_COUNT_KEY) || '0', 10);
|
||||
|
||||
if (!forceLocalOnly &&
|
||||
publicSettings.oidcEnabled &&
|
||||
publicSettings.oidcProviderDetails &&
|
||||
!oidcBypassed &&
|
||||
errorCount < MAX_OIDC_RETRIES) {
|
||||
const details = publicSettings.oidcProviderDetails;
|
||||
|
||||
oauthService.configure({
|
||||
issuer: details.issuerUri,
|
||||
clientId: details.clientId,
|
||||
scope: 'openid profile email offline_access',
|
||||
redirectUri: window.location.origin + '/oauth2-callback',
|
||||
responseType: 'code',
|
||||
showDebugInformation: false,
|
||||
requireHttps: false,
|
||||
strictDiscoveryDocumentValidation: false,
|
||||
});
|
||||
|
||||
console.log(`[OIDC] Attempting discovery and login (attempt ${errorCount + 1}/${MAX_OIDC_RETRIES})`);
|
||||
|
||||
withTimeout(oauthService.loadDiscoveryDocumentAndTryLogin(), OIDC_TIMEOUT_MS)
|
||||
.then(() => {
|
||||
console.log('[OIDC] Discovery document loaded and login attempted');
|
||||
localStorage.removeItem(OIDC_ERROR_COUNT_KEY);
|
||||
|
||||
if (oauthService.hasValidAccessToken()) {
|
||||
authService.tokenSubject.next(oauthService.getAccessToken());
|
||||
console.log('[OIDC] Valid access token found after tryLogin');
|
||||
oauthService.setupAutomaticSilentRefresh();
|
||||
websocketInitializer(authService)();
|
||||
authInitService.markAsInitialized();
|
||||
resolve();
|
||||
} else {
|
||||
console.log('[OIDC] No valid access token found, attempting silent login with prompt=none');
|
||||
oauthService.initImplicitFlow();
|
||||
resolve();
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
const newErrorCount = errorCount + 1;
|
||||
localStorage.setItem(OIDC_ERROR_COUNT_KEY, newErrorCount.toString());
|
||||
|
||||
authInitService.markAsInitialized();
|
||||
|
||||
const isTimeout = err.message.includes('timed out');
|
||||
const errorType = isTimeout ? 'timeout' : 'network/configuration';
|
||||
|
||||
console.error(
|
||||
`OIDC initialization failed (${errorType}, attempt ${newErrorCount}/${MAX_OIDC_RETRIES}): ` +
|
||||
'Unable to complete OpenID Connect discovery or login. ' +
|
||||
`${isTimeout ? 'The request timed out after ' + OIDC_TIMEOUT_MS + 'ms. ' : ''}` +
|
||||
'This may be due to an incorrect issuer URL, client ID, network issue, or slow server response. ' +
|
||||
'Falling back to local login. Details:', err
|
||||
);
|
||||
|
||||
if (newErrorCount >= MAX_OIDC_RETRIES) {
|
||||
console.warn(`[OIDC] Maximum retry attempts (${MAX_OIDC_RETRIES}) exceeded. OIDC will be automatically bypassed until manually re-enabled.`);
|
||||
localStorage.setItem(OIDC_BYPASS_KEY, 'true');
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
} else if (publicSettings.remoteAuthEnabled) {
|
||||
if (publicSettings.remoteAuthEnabled) {
|
||||
authService.remoteLogin().subscribe({
|
||||
next: () => {
|
||||
authInitService.markAsInitialized();
|
||||
@@ -117,12 +37,8 @@ export function initializeAuthFactory() {
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if (forceLocalOnly) {
|
||||
console.warn('[OIDC] Forced local-only login via ?localOnly=true');
|
||||
} else if (oidcBypassed) {
|
||||
console.log('[OIDC] OIDC is manually bypassed, using local authentication only');
|
||||
} else if (errorCount >= MAX_OIDC_RETRIES) {
|
||||
console.log(`[OIDC] OIDC automatically bypassed due to ${errorCount} consecutive errors`);
|
||||
if (authService.getInternalAccessToken()) {
|
||||
websocketInitializer(authService)();
|
||||
}
|
||||
authInitService.markAsInitialized();
|
||||
resolve();
|
||||
@@ -133,16 +49,3 @@ export function initializeAuthFactory() {
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function resetOidcBypass(): void {
|
||||
localStorage.removeItem(OIDC_BYPASS_KEY);
|
||||
localStorage.removeItem(OIDC_ERROR_COUNT_KEY);
|
||||
}
|
||||
|
||||
export function isOidcBypassed(): boolean {
|
||||
return localStorage.getItem(OIDC_BYPASS_KEY) === 'true';
|
||||
}
|
||||
|
||||
export function getOidcErrorCount(): number {
|
||||
return parseInt(localStorage.getItem(OIDC_ERROR_COUNT_KEY) || '0', 10);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,7 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
const internalToken = authService.getInternalAccessToken();
|
||||
const oidcToken = authService.getOidcAccessToken();
|
||||
const token = internalToken || oidcToken;
|
||||
|
||||
const token = authService.getInternalAccessToken();
|
||||
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
||||
|
||||
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||
@@ -21,7 +18,7 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
return next(authReq).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401) {
|
||||
return handle401Error(authService, authReq, next, router, !!internalToken);
|
||||
return handle401Error(authService, authReq, next, router);
|
||||
}
|
||||
return throwError(() => error);
|
||||
})
|
||||
@@ -31,8 +28,8 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn, router: Router, isInternal: boolean): Observable<HttpEvent<unknown>> {
|
||||
if (!isRefreshing && isInternal) {
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn, router: Router): Observable<HttpEvent<unknown>> {
|
||||
if (!isRefreshing) {
|
||||
isRefreshing = true;
|
||||
refreshTokenSubject.next(null);
|
||||
|
||||
@@ -56,23 +53,17 @@ function handle401Error(authService: AuthService, request: HttpRequest<unknown>,
|
||||
);
|
||||
}
|
||||
|
||||
if (isRefreshing && isInternal) {
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap(token =>
|
||||
next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
forceLogout(authService, router, isInternal ? 'Session expired, please log in again.' : 'OIDC token expired, please log in again.');
|
||||
return throwError(() => new Error('Authentication failed, please log in.'));
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap(token =>
|
||||
next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function forceLogout(authService: AuthService, router: Router, message?: string): void {
|
||||
if (message) console.warn(message);
|
||||
function forceLogout(authService: AuthService, router: Router): void {
|
||||
authService.logout();
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
|
||||
export const AuthGuard: CanActivateFn = (route, state) => {
|
||||
const router = inject(Router);
|
||||
const authService = inject(AuthService);
|
||||
const oauthService = inject(OAuthService);
|
||||
|
||||
const internalAccessToken = authService.getInternalAccessToken();
|
||||
|
||||
if (internalAccessToken) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(internalAccessToken.split('.')[1]));
|
||||
if (payload.exp && payload.exp * 1000 < Date.now()) {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
return router.createUrlTree(['/login']);
|
||||
}
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
@@ -25,10 +27,6 @@ export const AuthGuard: CanActivateFn = (route, state) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (oauthService.hasValidAccessToken()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
};
|
||||
|
||||
+394
-41
@@ -2,7 +2,7 @@
|
||||
<div class="main-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-lock"></i>
|
||||
<i class="pi pi-key"></i>
|
||||
{{ t('title') }}
|
||||
</h2>
|
||||
<p class="settings-description">
|
||||
@@ -54,7 +54,6 @@
|
||||
<div class="auth-method-info">
|
||||
<span class="auth-method-label">
|
||||
{{ t('oidc.label') }}
|
||||
<span class="experimental-badge">{{ t('oidc.experimental') }}</span>
|
||||
</span>
|
||||
<span class="auth-method-status" [class.active]="oidcEnabled">
|
||||
{{ oidcEnabled ? t('oidc.enabled') : t('oidc.disabled') }}
|
||||
@@ -81,26 +80,13 @@
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-cog"></i>
|
||||
{{ t('providerConfig.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('providerConfig.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
</div>
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-cog"></i>
|
||||
{{ t('providerConfig.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('providerConfig.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
@@ -109,6 +95,7 @@
|
||||
<label for="providerName">{{ t('providerConfig.providerName') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="providerName"
|
||||
[(ngModel)]="oidcProvider.providerName"
|
||||
[placeholder]="t('providerConfig.providerPlaceholder')"/>
|
||||
@@ -118,24 +105,39 @@
|
||||
<label for="clientId">{{ t('providerConfig.clientId') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="clientId"
|
||||
[(ngModel)]="oidcProvider.clientId"
|
||||
[placeholder]="t('providerConfig.clientIdPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item full-width">
|
||||
<div class="config-item">
|
||||
<label for="clientSecret">{{ t('providerConfig.clientSecret') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="clientSecret"
|
||||
type="password"
|
||||
[(ngModel)]="oidcProvider.clientSecret"
|
||||
[placeholder]="t('providerConfig.clientSecretPlaceholder')"/>
|
||||
<span class="field-hint">{{ t('providerConfig.clientSecretHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="config-item span-2">
|
||||
<label for="issuerUri">{{ t('providerConfig.issuerUri') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
[placeholder]="t('providerConfig.issuerPlaceholder')"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item full-width">
|
||||
<div class="config-item">
|
||||
<label for="scope">{{ t('providerConfig.scope') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="scope"
|
||||
[readonly]="true"
|
||||
disabled="disabled"
|
||||
@@ -144,6 +146,26 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (oidcEnabled) {
|
||||
<div class="config-grid" style="margin-top: 0.75rem;">
|
||||
<div class="config-item">
|
||||
<label for="sessionDuration">{{ t('providerConfig.sessionDuration') }}</label>
|
||||
<p-inputNumber
|
||||
size="small"
|
||||
inputId="sessionDuration"
|
||||
[(ngModel)]="sessionDurationHours"
|
||||
[min]="1"
|
||||
[max]="8760"
|
||||
[showButtons]="true"
|
||||
[placeholder]="t('providerConfig.sessionDurationPlaceholder')"
|
||||
mode="decimal"
|
||||
[useGrouping]="false">
|
||||
</p-inputNumber>
|
||||
<span class="field-hint">{{ t('providerConfig.sessionDurationHint') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="claims-section">
|
||||
<h4 class="subsection-title">{{ t('providerConfig.claimMappings') }}</h4>
|
||||
<p class="subsection-description">
|
||||
@@ -154,6 +176,7 @@
|
||||
<label for="claimUsername">{{ t('providerConfig.usernameClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimUsername"
|
||||
[(ngModel)]="oidcProvider.claimMapping.username"
|
||||
[placeholder]="t('providerConfig.usernamePlaceholder')"/>
|
||||
@@ -162,6 +185,7 @@
|
||||
<label for="claimEmail">{{ t('providerConfig.emailClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimEmail"
|
||||
[(ngModel)]="oidcProvider.claimMapping.email"
|
||||
[placeholder]="t('providerConfig.emailPlaceholder')"/>
|
||||
@@ -170,16 +194,162 @@
|
||||
<label for="claimName">{{ t('providerConfig.nameClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimName"
|
||||
[(ngModel)]="oidcProvider.claimMapping.name"
|
||||
[placeholder]="t('providerConfig.namePlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item">
|
||||
<label for="claimGroups">{{ t('providerConfig.groupsClaim') }}</label>
|
||||
<input
|
||||
pInputText
|
||||
pSize="small"
|
||||
id="claimGroups"
|
||||
[(ngModel)]="oidcProvider.claimMapping.groups"
|
||||
[placeholder]="t('providerConfig.groupsPlaceholder')"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="provider-actions-row">
|
||||
<div class="test-results-inline">
|
||||
@if (testConnectionResult) {
|
||||
<div class="test-results-toggle"
|
||||
[style.border-radius]="showTestDetails ? '6px 6px 0 0' : '6px'"
|
||||
(click)="showTestDetails = !showTestDetails">
|
||||
@if (testConnectionResult.success) {
|
||||
<i class="pi pi-check-circle" style="color: var(--p-green-500);"></i>
|
||||
<span>{{ t('testConnection.passed') }}</span>
|
||||
} @else {
|
||||
<i class="pi pi-times-circle" style="color: var(--p-red-500);"></i>
|
||||
<span>{{ t('testConnection.failed') }}</span>
|
||||
}
|
||||
<span style="color: var(--p-text-muted-color); font-size: 0.75rem;">
|
||||
({{ testConnectionResult.checks.length }} {{ t('testConnection.checks') }})
|
||||
</span>
|
||||
<i class="pi pi-chevron-right toggle-chevron" [class.expanded]="showTestDetails"></i>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="provider-action-buttons">
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="t('testConnection.button')"
|
||||
[icon]="isTestingConnection ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
|
||||
severity="info"
|
||||
size="small"
|
||||
(click)="testConnection()"
|
||||
[disabled]="!oidcProvider.issuerUri || isTestingConnection">
|
||||
</p-button>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
@if (testConnectionResult && showTestDetails) {
|
||||
<div class="test-results-details">
|
||||
@for (check of testConnectionResult.checks; track check.name) {
|
||||
<div class="test-check-row">
|
||||
@switch (check.status) {
|
||||
@case ('PASS') {
|
||||
<i class="pi pi-check-circle" style="color: var(--p-green-500);"></i>
|
||||
}
|
||||
@case ('FAIL') {
|
||||
<i class="pi pi-times-circle" style="color: var(--p-red-500);"></i>
|
||||
}
|
||||
@case ('WARN') {
|
||||
<i class="pi pi-exclamation-triangle" style="color: var(--p-yellow-500);"></i>
|
||||
}
|
||||
@case ('SKIP') {
|
||||
<i class="pi pi-minus-circle" style="color: var(--p-surface-400);"></i>
|
||||
}
|
||||
}
|
||||
<span class="check-name">{{ check.name }}</span>
|
||||
<span class="check-message">{{ check.message }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
{{ t('infoPanel.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('infoPanel.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<div class="info-panel-grid">
|
||||
@for (item of infoItems; track item.labelKey) {
|
||||
<div class="info-panel-item">
|
||||
<span class="info-panel-label">{{ t(item.labelKey) }}</span>
|
||||
<div class="info-panel-value-row">
|
||||
<code class="info-panel-value">{{ item.value }}</code>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
icon="pi pi-copy"
|
||||
severity="secondary"
|
||||
size="small"
|
||||
[style]="{'min-width': '2rem'}"
|
||||
(click)="copyToClipboard(item.value)">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (oidcEnabled) {
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-ban"></i>
|
||||
{{ t('oidcOnly.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('oidcOnly.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="provisioning-toggle">
|
||||
<div class="toggle-content">
|
||||
<div class="toggle-info">
|
||||
<span class="toggle-label">{{ t('oidcOnly.label') }}</span>
|
||||
<span class="toggle-status" [class.active]="oidcForceOnlyMode">
|
||||
{{ oidcForceOnlyMode ? t('oidcOnly.enabled') : t('oidcOnly.disabled') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="toggle-description">
|
||||
{{ t('oidcOnly.description') }}
|
||||
</p>
|
||||
@if (oidcForceOnlyMode) {
|
||||
<p class="toggle-description" style="color: var(--p-yellow-500); margin-top: 0.5rem;">
|
||||
<i class="pi pi-exclamation-triangle" style="margin-right: 0.25rem;"></i>
|
||||
{{ t('oidcOnly.backdoorHint') }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcForceOnlyMode"
|
||||
(onChange)="toggleOidcForceOnlyMode()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
@@ -192,14 +362,6 @@
|
||||
{{ t('provisioning.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
[label]="'common.save' | transloco"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcAutoProvisionSettings()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -223,6 +385,31 @@
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
|
||||
<div class="provisioning-toggle">
|
||||
<div class="toggle-content">
|
||||
<div class="toggle-info">
|
||||
<span class="toggle-label">{{ t('provisioning.linkLocalLabel') }}</span>
|
||||
<span class="toggle-status" [class.active]="allowLocalAccountLinking">
|
||||
{{ allowLocalAccountLinking ? t('provisioning.autoEnabled') : t('provisioning.autoDisabled') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="toggle-description">
|
||||
{{ t('provisioning.linkLocalDesc') }}
|
||||
</p>
|
||||
@if (allowLocalAccountLinking) {
|
||||
<p class="toggle-description" style="color: var(--p-yellow-500); margin-top: 0.5rem;">
|
||||
<i class="pi pi-exclamation-triangle" style="margin-right: 0.25rem;"></i>
|
||||
{{ t('provisioning.linkLocalWarning') }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="allowLocalAccountLinking"
|
||||
inputId="linkLocal"
|
||||
(onChange)="saveOidcAutoProvisionSettings()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
|
||||
@if (autoUserProvisioningEnabled) {
|
||||
<div class="default-settings">
|
||||
<div class="permissions-group">
|
||||
@@ -252,20 +439,186 @@
|
||||
|
||||
<div class="libraries-group">
|
||||
<h4 class="group-title">{{ t('provisioning.defaultLibraryAccess') }}</h4>
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
[placeholder]="t('provisioning.selectLibraries')"
|
||||
appendTo="body"
|
||||
class="libraries-select">
|
||||
</p-multiSelect>
|
||||
<div style="display: flex; align-items: center; gap: 0.5rem; justify-content: space-between;">
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
[placeholder]="t('provisioning.selectLibraries')"
|
||||
appendTo="body"
|
||||
class="libraries-select"
|
||||
style="flex: 1;">
|
||||
</p-multiSelect>
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
[label]="'common.save' | transloco"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcAutoProvisionSettings()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-sitemap"></i>
|
||||
{{ t('groupMapping.sectionTitle') }}
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
{{ t('groupMapping.sectionDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-plus"
|
||||
[label]="t('groupMapping.addMapping')"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="openNewGroupMapping()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="config-grid-2col" style="margin-bottom: 1rem;">
|
||||
<div class="config-item">
|
||||
<label for="groupSyncMode">{{ t('groupMapping.syncModeLabel') }}</label>
|
||||
<p-select
|
||||
inputId="groupSyncMode"
|
||||
[(ngModel)]="groupSyncMode"
|
||||
[options]="groupSyncModeOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
appendTo="body">
|
||||
</p-select>
|
||||
<span class="field-hint">{{ t('groupMapping.syncModeHint') }}</span>
|
||||
</div>
|
||||
<div class="config-item" style="display: flex; align-items: flex-end;">
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveGroupSyncMode()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (groupMappings.length > 0) {
|
||||
<p-table [value]="groupMappings" [tableStyle]="{'min-width': '100%'}" styleClass="p-datatable-sm">
|
||||
<ng-template #header>
|
||||
<tr>
|
||||
<th>{{ t('groupMapping.colGroupClaim') }}</th>
|
||||
<th>{{ t('groupMapping.colAdmin') }}</th>
|
||||
<th>{{ t('groupMapping.colPermissions') }}</th>
|
||||
<th>{{ t('groupMapping.colLibraries') }}</th>
|
||||
<th>{{ t('groupMapping.colDescription') }}</th>
|
||||
<th style="width: 8rem;"></th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
<ng-template #body let-mapping>
|
||||
<tr>
|
||||
<td>{{ mapping.oidcGroupClaim }}</td>
|
||||
<td>
|
||||
@if (mapping.isAdmin) {
|
||||
<app-tag [rounded]="true" color="warning" size="2xs">Admin</app-tag>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@for (perm of mapping.permissions; track perm) {
|
||||
<app-tag [rounded]="true" color="info" size="2xs" style="margin-right: 0.25rem; margin-bottom: 0.25rem;">{{ perm }}</app-tag>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@for (libId of mapping.libraryIds; track libId) {
|
||||
<app-tag [rounded]="true" color="secondary" size="2xs" style="margin-right: 0.25rem; margin-bottom: 0.25rem;">{{ getLibraryName(libId) }}</app-tag>
|
||||
}
|
||||
</td>
|
||||
<td>{{ mapping.description }}</td>
|
||||
<td>
|
||||
<div style="display: flex; gap: 0.5rem;">
|
||||
<p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (click)="openEditGroupMapping(mapping)"></p-button>
|
||||
<p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (click)="deleteGroupMapping(mapping)"></p-button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-dialog
|
||||
[header]="editingGroupMapping.id ? t('groupMapping.editTitle') : t('groupMapping.addTitle')"
|
||||
[(visible)]="showGroupMappingDialog"
|
||||
[modal]="true"
|
||||
[style]="{width: '550px', maxWidth: '95vw'}"
|
||||
[dismissableMask]="true">
|
||||
<div class="config-grid" style="gap: 1rem;">
|
||||
<div class="config-item full-width">
|
||||
<label for="gmGroupClaim">{{ t('groupMapping.groupClaimLabel') }}</label>
|
||||
<input pInputText id="gmGroupClaim" [(ngModel)]="editingGroupMapping.oidcGroupClaim" [placeholder]="t('groupMapping.groupClaimPlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<label for="gmDescription">{{ t('groupMapping.descriptionLabel') }}</label>
|
||||
<input pInputText id="gmDescription" [(ngModel)]="editingGroupMapping.description" [placeholder]="t('groupMapping.descriptionPlaceholder')"/>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<div class="provisioning-toggle" style="padding: 0;">
|
||||
<div class="toggle-content">
|
||||
<span class="toggle-label">{{ t('groupMapping.adminLabel') }}</span>
|
||||
</div>
|
||||
<p-toggleswitch [(ngModel)]="editingGroupMapping.isAdmin"></p-toggleswitch>
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<h4 class="group-title">{{ t('groupMapping.permissionsLabel') }}</h4>
|
||||
<div class="permissions-grid">
|
||||
<div class="permission-item">
|
||||
<p-checkbox [binary]="true" [disabled]="true" [ngModel]="true" inputId="gmPermRead"></p-checkbox>
|
||||
<label for="gmPermRead">{{ t('provisioning.readBooks') }}</label>
|
||||
</div>
|
||||
@for (perm of editingGroupMappingPerms; track perm) {
|
||||
<div class="permission-item">
|
||||
<p-checkbox [(ngModel)]="perm.selected" [binary]="true" [inputId]="'gm_' + perm.value"></p-checkbox>
|
||||
<label [for]="'gm_' + perm.value">{{ t(perm.translationKey) }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="config-item full-width">
|
||||
<h4 class="group-title">{{ t('groupMapping.librariesLabel') }}</h4>
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingGroupMappingLibraryIds"
|
||||
[placeholder]="t('provisioning.selectLibraries')"
|
||||
appendTo="body"
|
||||
class="libraries-select">
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
</div>
|
||||
<ng-template #footer>
|
||||
<p-button
|
||||
[label]="'common.save' | transloco"
|
||||
icon="pi pi-check"
|
||||
(click)="saveGroupMapping()"
|
||||
[disabled]="!editingGroupMapping.oidcGroupClaim">
|
||||
</p-button>
|
||||
</ng-template>
|
||||
</p-dialog>
|
||||
}
|
||||
</div>
|
||||
</ng-container>
|
||||
|
||||
+169
-26
@@ -140,17 +140,6 @@
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
.experimental-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.125rem 0.5rem;
|
||||
background: color-mix(in srgb, var(--p-orange-500) 15%, transparent);
|
||||
color: var(--p-orange-500);
|
||||
border-radius: 12px;
|
||||
font-size: 0.625rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.auth-method-status {
|
||||
font-size: 0.875rem;
|
||||
@@ -184,10 +173,24 @@
|
||||
// Configuration Grid
|
||||
.config-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.config-grid-2col {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -195,16 +198,24 @@
|
||||
.config-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
gap: 0.375rem;
|
||||
|
||||
&.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
&.span-2 {
|
||||
grid-column: span 2;
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-column: span 1;
|
||||
}
|
||||
}
|
||||
|
||||
label {
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
input {
|
||||
@@ -213,36 +224,36 @@
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
// Claims Section
|
||||
.claims-section {
|
||||
margin-top: 1.5rem;
|
||||
padding-top: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.subsection-title {
|
||||
font-size: 0.9375rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.5rem 0;
|
||||
margin: 0 0 0.25rem 0;
|
||||
}
|
||||
|
||||
.subsection-description {
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.5;
|
||||
margin: 0 0 1rem 0;
|
||||
line-height: 1.4;
|
||||
margin: 0 0 0.75rem 0;
|
||||
}
|
||||
|
||||
.claims-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
@@ -253,6 +264,102 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Provider Actions Row
|
||||
.provider-actions-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
|
||||
@media (max-width: 600px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
|
||||
.test-results-inline {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.provider-action-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
// Test Connection Results
|
||||
.test-results-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.625rem 0.875rem;
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--p-text-color);
|
||||
transition: background 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--ground-background) 40%, var(--p-surface-800) 60%);
|
||||
}
|
||||
|
||||
.toggle-chevron {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
transition: transform 0.2s ease;
|
||||
margin-left: auto;
|
||||
|
||||
&.expanded {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.test-results-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
padding: 0.5rem 0.875rem 0.625rem;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-top: none;
|
||||
border-radius: 0 0 6px 6px;
|
||||
background: color-mix(in srgb, var(--ground-background) 60%, var(--p-surface-800) 40%);
|
||||
}
|
||||
|
||||
.test-check-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.5rem;
|
||||
padding: 0.1875rem 0;
|
||||
font-size: 0.8125rem;
|
||||
|
||||
.check-name {
|
||||
font-weight: 500;
|
||||
color: var(--p-text-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.check-message {
|
||||
color: var(--p-text-muted-color);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 0.8125rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Provisioning Toggle
|
||||
.provisioning-toggle {
|
||||
display: flex;
|
||||
@@ -353,3 +460,39 @@
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
// Info Panel
|
||||
.info-panel-grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.info-panel-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.info-panel-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
|
||||
.info-panel-value-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.info-panel-value {
|
||||
flex: 1;
|
||||
font-size: 0.8125rem;
|
||||
padding: 0.375rem 0.625rem;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 4px;
|
||||
color: var(--p-text-color);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
+253
-5
@@ -5,16 +5,23 @@ import {Button} from 'primeng/button';
|
||||
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {ToggleSwitch} from 'primeng/toggleswitch';
|
||||
import {InputNumber} from 'primeng/inputnumber';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AppSettingsService} from '../../../shared/service/app-settings.service';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AppSettingKey, AppSettings, OidcProviderDetails} from '../../../shared/model/app-settings.model';
|
||||
import {AppSettingKey, AppSettings, OidcProviderDetails, OidcTestResult} from '../../../shared/model/app-settings.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {Library} from '../../../features/book/model/library.model';
|
||||
import {LibraryService} from '../../../features/book/service/library.service';
|
||||
import {ExternalDocLinkComponent} from '../../../shared/components/external-doc-link/external-doc-link.component';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {OidcGroupMapping} from '../../../shared/model/oidc-group-mapping.model';
|
||||
import {OidcGroupMappingService} from '../../../shared/service/oidc-group-mapping.service';
|
||||
import {Select} from 'primeng/select';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {TagComponent} from '../../../shared/components/tag/tag.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-authentication-settings',
|
||||
@@ -27,10 +34,15 @@ import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/tran
|
||||
ToggleSwitch,
|
||||
Button,
|
||||
MultiSelect,
|
||||
InputNumber,
|
||||
ReactiveFormsModule,
|
||||
ExternalDocLinkComponent,
|
||||
TranslocoDirective,
|
||||
TranslocoPipe
|
||||
TranslocoPipe,
|
||||
Select,
|
||||
TableModule,
|
||||
Dialog,
|
||||
TagComponent
|
||||
],
|
||||
styleUrls: ['./authentication-settings.component.scss']
|
||||
})
|
||||
@@ -49,25 +61,59 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
|
||||
internalAuthEnabled = true;
|
||||
autoUserProvisioningEnabled = false;
|
||||
allowLocalAccountLinking = true;
|
||||
selectedPermissions: string[] = [];
|
||||
oidcEnabled = false;
|
||||
allLibraries: Library[] = [];
|
||||
editingLibraryIds: number[] = [];
|
||||
sessionDurationHours: number | null = null;
|
||||
backchannelLogoutUri = `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`;
|
||||
oidcForceOnlyMode = false;
|
||||
|
||||
infoItems = [
|
||||
{labelKey: 'infoPanel.redirectUri', value: `${window.location.origin}/oauth2-callback`},
|
||||
{labelKey: 'infoPanel.postLogoutRedirectUri', value: `${window.location.origin}/login`},
|
||||
{labelKey: 'infoPanel.backChannelLogoutUri', value: `${window.location.origin}/api/v1/auth/oidc/backchannel-logout`},
|
||||
{labelKey: 'infoPanel.requiredScopes', value: 'openid profile email offline_access'},
|
||||
{labelKey: 'infoPanel.pkceMethod', value: 'S256'},
|
||||
{labelKey: 'infoPanel.grantType', value: 'Authorization Code'},
|
||||
];
|
||||
|
||||
// Test connection
|
||||
isTestingConnection = false;
|
||||
testConnectionResult: OidcTestResult | null = null;
|
||||
showTestDetails = false;
|
||||
|
||||
// Group mapping
|
||||
groupSyncMode: string = 'DISABLED';
|
||||
groupSyncModeOptions = [
|
||||
{label: 'Disabled', value: 'DISABLED'},
|
||||
{label: 'On Login (Replace)', value: 'ON_LOGIN'},
|
||||
{label: 'On Login (Additive)', value: 'ON_LOGIN_ADDITIVE'}
|
||||
];
|
||||
groupMappings: OidcGroupMapping[] = [];
|
||||
showGroupMappingDialog = false;
|
||||
editingGroupMapping: OidcGroupMapping = this.emptyGroupMapping();
|
||||
editingGroupMappingPerms: {label: string; value: string; selected: boolean; translationKey: string}[] = [];
|
||||
editingGroupMappingLibraryIds: number[] = [];
|
||||
|
||||
oidcProvider: OidcProviderDetails = {
|
||||
providerName: '',
|
||||
clientId: '',
|
||||
clientSecret: '',
|
||||
issuerUri: '',
|
||||
claimMapping: {
|
||||
username: '',
|
||||
email: '',
|
||||
name: ''
|
||||
name: '',
|
||||
groups: ''
|
||||
}
|
||||
};
|
||||
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private groupMappingService = inject(OidcGroupMappingService);
|
||||
private t = inject(TranslocoService);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
@@ -91,15 +137,21 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
const details = settings.oidcAutoProvisionDetails;
|
||||
|
||||
this.autoUserProvisioningEnabled = details?.enableAutoProvisioning ?? false;
|
||||
this.allowLocalAccountLinking = details?.allowLocalAccountLinking ?? true;
|
||||
this.selectedPermissions = details?.defaultPermissions ?? [];
|
||||
this.editingLibraryIds = details?.defaultLibraryIds ?? [];
|
||||
|
||||
const defaultClaimMapping = {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'given_name'
|
||||
name: 'given_name',
|
||||
groups: ''
|
||||
};
|
||||
|
||||
this.sessionDurationHours = settings.oidcSessionDurationHours ?? null;
|
||||
this.groupSyncMode = settings.oidcGroupSyncMode ?? 'DISABLED';
|
||||
this.oidcForceOnlyMode = settings.oidcForceOnlyMode ?? false;
|
||||
|
||||
this.oidcProvider = {
|
||||
providerName: settings.oidcProviderDetails?.providerName || '',
|
||||
clientId: settings.oidcProviderDetails?.clientId || '',
|
||||
@@ -110,6 +162,10 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
this.availablePermissions.forEach(perm => {
|
||||
perm.selected = this.selectedPermissions.includes(perm.value);
|
||||
});
|
||||
|
||||
if (this.oidcEnabled) {
|
||||
this.loadGroupMappings();
|
||||
}
|
||||
}
|
||||
|
||||
isOidcFormComplete(): boolean {
|
||||
@@ -134,12 +190,18 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
}
|
||||
|
||||
saveOidcProvider(): void {
|
||||
const payload = [
|
||||
const payload: {key: AppSettingKey; newValue: unknown}[] = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_PROVIDER_DETAILS,
|
||||
newValue: this.oidcProvider
|
||||
}
|
||||
];
|
||||
if (this.oidcEnabled) {
|
||||
payload.push({
|
||||
key: AppSettingKey.OIDC_SESSION_DURATION_HOURS,
|
||||
newValue: this.sessionDurationHours
|
||||
});
|
||||
}
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
@@ -154,9 +216,45 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
copyBackchannelUri(): void {
|
||||
this.copyToClipboard(this.backchannelLogoutUri);
|
||||
}
|
||||
|
||||
copyToClipboard(value: string): void {
|
||||
navigator.clipboard.writeText(value).then(() => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.copiedToClipboard')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
saveSessionDuration(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_SESSION_DURATION_HOURS,
|
||||
newValue: this.sessionDurationHours
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.sessionDurationSaved')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.sessionDurationError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
saveOidcAutoProvisionSettings(): void {
|
||||
const provisionDetails = {
|
||||
enableAutoProvisioning: this.autoUserProvisioningEnabled,
|
||||
allowLocalAccountLinking: this.allowLocalAccountLinking,
|
||||
defaultPermissions: [
|
||||
'permissionRead',
|
||||
...this.availablePermissions.filter(p => p.selected).map(p => p.value)
|
||||
@@ -184,4 +282,154 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// Group mapping methods
|
||||
loadGroupMappings(): void {
|
||||
this.groupMappingService.getAll().subscribe(mappings => this.groupMappings = mappings);
|
||||
}
|
||||
|
||||
saveGroupSyncMode(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_GROUP_SYNC_MODE,
|
||||
newValue: this.groupSyncMode
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.syncModeSaved')
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.syncModeError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
openNewGroupMapping(): void {
|
||||
this.editingGroupMapping = this.emptyGroupMapping();
|
||||
this.initGroupMappingPerms([]);
|
||||
this.editingGroupMappingLibraryIds = [];
|
||||
this.showGroupMappingDialog = true;
|
||||
}
|
||||
|
||||
openEditGroupMapping(mapping: OidcGroupMapping): void {
|
||||
this.editingGroupMapping = {...mapping};
|
||||
this.initGroupMappingPerms(mapping.permissions);
|
||||
this.editingGroupMappingLibraryIds = [...mapping.libraryIds];
|
||||
this.showGroupMappingDialog = true;
|
||||
}
|
||||
|
||||
private initGroupMappingPerms(selectedPerms: string[]): void {
|
||||
this.editingGroupMappingPerms = this.availablePermissions.map(p => ({
|
||||
...p,
|
||||
selected: selectedPerms.includes(p.value)
|
||||
}));
|
||||
}
|
||||
|
||||
saveGroupMapping(): void {
|
||||
const mapping: OidcGroupMapping = {
|
||||
...this.editingGroupMapping,
|
||||
permissions: [
|
||||
'permissionRead',
|
||||
...this.editingGroupMappingPerms.filter(p => p.selected).map(p => p.value)
|
||||
],
|
||||
libraryIds: this.editingGroupMappingLibraryIds
|
||||
};
|
||||
|
||||
const obs = mapping.id
|
||||
? this.groupMappingService.update(mapping.id, mapping)
|
||||
: this.groupMappingService.create(mapping);
|
||||
|
||||
obs.subscribe({
|
||||
next: () => {
|
||||
this.showGroupMappingDialog = false;
|
||||
this.loadGroupMappings();
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingSaved')
|
||||
});
|
||||
},
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
deleteGroupMapping(mapping: OidcGroupMapping): void {
|
||||
if (!mapping.id) return;
|
||||
this.groupMappingService.delete(mapping.id).subscribe({
|
||||
next: () => {
|
||||
this.loadGroupMappings();
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingDeleted')
|
||||
});
|
||||
},
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.toast.groupMappingError')
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
getLibraryName(id: number): string {
|
||||
return this.allLibraries.find(l => l.id === id)?.name ?? `#${id}`;
|
||||
}
|
||||
|
||||
testConnection(): void {
|
||||
this.isTestingConnection = true;
|
||||
this.testConnectionResult = null;
|
||||
this.appSettingsService.testOidcConnection(this.oidcProvider).subscribe({
|
||||
next: (result) => {
|
||||
this.testConnectionResult = result;
|
||||
this.showTestDetails = true;
|
||||
this.isTestingConnection = false;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('settingsAuth.testConnection.error')
|
||||
});
|
||||
this.isTestingConnection = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleOidcForceOnlyMode(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.OIDC_FORCE_ONLY_MODE,
|
||||
newValue: this.oidcForceOnlyMode
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('settingsAuth.toast.saved'),
|
||||
detail: this.t.translate('settingsAuth.oidcOnly.saved')
|
||||
}),
|
||||
error: (err) => {
|
||||
this.oidcForceOnlyMode = !this.oidcForceOnlyMode;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: err?.error?.message || this.t.translate('settingsAuth.oidcOnly.error')
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private emptyGroupMapping(): OidcGroupMapping {
|
||||
return {oidcGroupClaim: '', isAdmin: false, permissions: [], libraryIds: [], description: ''};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1,4 @@
|
||||
|
||||
<div class="oidc-callback-loading">
|
||||
<i class="pi pi-spin pi-spinner"></i>
|
||||
<span>{{ 'auth.oidc.signingIn' | transloco }}</span>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
.oidc-callback-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
gap: 1rem;
|
||||
color: var(--text-color);
|
||||
background: var(--ground-background);
|
||||
|
||||
i {
|
||||
font-size: 2.5rem;
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,69 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {TranslocoPipe} from '@jsverse/transloco';
|
||||
import {OidcService} from '../oidc.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-oidc-callback',
|
||||
templateUrl: './oidc-callback.component.html',
|
||||
styleUrls: ['./oidc-callback.component.scss']
|
||||
styleUrls: ['./oidc-callback.component.scss'],
|
||||
imports: [TranslocoPipe]
|
||||
})
|
||||
export class OidcCallbackComponent implements OnInit {
|
||||
private router = inject(Router);
|
||||
private oauthService = inject(OAuthService);
|
||||
private messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private oidcService = inject(OidcService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
async ngOnInit(): Promise<void> {
|
||||
try {
|
||||
await this.oauthService.tryLoginCodeFlow();
|
||||
if (this.oauthService.hasValidAccessToken()) {
|
||||
this.router.navigate(['/dashboard']);
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[OIDC Callback] Login failed', e);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('auth.oidc.loginFailedSummary'),
|
||||
detail: this.t.translate('auth.oidc.redirectingDetail'),
|
||||
life: 3000
|
||||
});
|
||||
setTimeout(() => {
|
||||
this.router.navigate(['/login']);
|
||||
}, 3000);
|
||||
ngOnInit(): void {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
|
||||
const error = params.get('error');
|
||||
if (error) {
|
||||
const description = params.get('error_description') || error;
|
||||
console.error('[OIDC Callback] Provider returned error:', error, description);
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: description}});
|
||||
return;
|
||||
}
|
||||
|
||||
const code = params.get('code');
|
||||
const returnedState = params.get('state');
|
||||
|
||||
if (!code || !returnedState) {
|
||||
console.error('[OIDC Callback] Missing code or state');
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: 'missing_code'}});
|
||||
return;
|
||||
}
|
||||
|
||||
const pkceState = this.oidcService.retrievePkceState(returnedState);
|
||||
if (!pkceState) {
|
||||
console.error('[OIDC Callback] No PKCE state found for state parameter');
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: 'missing_pkce_state'}});
|
||||
return;
|
||||
}
|
||||
|
||||
if (returnedState !== pkceState.state) {
|
||||
console.error('[OIDC Callback] State mismatch');
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: 'state_mismatch'}});
|
||||
return;
|
||||
}
|
||||
|
||||
this.oidcService.exchangeCode(code, pkceState.codeVerifier, pkceState.nonce, pkceState.state).subscribe({
|
||||
next: (response) => {
|
||||
sessionStorage.removeItem('oidc_redirect_count');
|
||||
this.authService.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
this.authService.initializeWebSocketConnection();
|
||||
if (response.isDefaultPassword === 'true') {
|
||||
this.router.navigate(['/change-password']);
|
||||
} else {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('[OIDC Callback] Token exchange failed', err);
|
||||
const errorMsg = err.error?.message || 'exchange_failed';
|
||||
this.router.navigate(['/login'], {queryParams: {oidcError: errorMsg}});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {firstValueFrom, Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import {AppSettingsService, PublicAppSettings} from '../../shared/service/app-settings.service';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
|
||||
interface OidcPkceState {
|
||||
codeVerifier: string;
|
||||
state: string;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
interface OidcTokenResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
isDefaultPassword: string;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class OidcService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
|
||||
async generatePkce(): Promise<{codeVerifier: string; codeChallenge: string}> {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
const codeVerifier = this.base64UrlEncode(array);
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const hash = await crypto.subtle.digest('SHA-256', encoder.encode(codeVerifier));
|
||||
const codeChallenge = this.base64UrlEncode(new Uint8Array(hash));
|
||||
|
||||
return {codeVerifier, codeChallenge};
|
||||
}
|
||||
|
||||
generateRandomString(): string {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
return this.base64UrlEncode(array);
|
||||
}
|
||||
|
||||
buildAuthUrl(
|
||||
issuerUri: string,
|
||||
clientId: string,
|
||||
codeChallenge: string,
|
||||
state: string,
|
||||
nonce: string,
|
||||
authorizationEndpoint?: string
|
||||
): Promise<string> {
|
||||
const redirectUri = `${window.location.origin}/oauth2-callback`;
|
||||
const scope = 'openid profile email offline_access';
|
||||
|
||||
if (authorizationEndpoint) {
|
||||
return Promise.resolve(this.buildUrl(authorizationEndpoint, clientId, redirectUri, scope, codeChallenge, state, nonce));
|
||||
}
|
||||
|
||||
// Fetch from discovery if authorization_endpoint not provided
|
||||
return fetch(`${issuerUri.replace(/\/+$/, '')}/.well-known/openid-configuration`)
|
||||
.then(res => res.json())
|
||||
.then(doc => {
|
||||
const endpoint = doc.authorization_endpoint;
|
||||
if (!endpoint) {
|
||||
throw new Error('authorization_endpoint not found in discovery document');
|
||||
}
|
||||
return this.buildUrl(endpoint, clientId, redirectUri, scope, codeChallenge, state, nonce);
|
||||
});
|
||||
}
|
||||
|
||||
async fetchState(): Promise<string> {
|
||||
const response = await firstValueFrom(
|
||||
this.http.get<{state: string}>(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/state`)
|
||||
);
|
||||
return response.state;
|
||||
}
|
||||
|
||||
exchangeCode(code: string, codeVerifier: string, nonce: string, state: string): Observable<OidcTokenResponse> {
|
||||
const redirectUri = `${window.location.origin}/oauth2-callback`;
|
||||
return this.http.post<OidcTokenResponse>(`${API_CONFIG.BASE_URL}/api/v1/auth/oidc/callback`, {
|
||||
code,
|
||||
codeVerifier,
|
||||
redirectUri,
|
||||
nonce,
|
||||
state
|
||||
});
|
||||
}
|
||||
|
||||
storePkceState(pkceState: OidcPkceState): void {
|
||||
sessionStorage.setItem(`oidc_pkce_${pkceState.state}`, JSON.stringify(pkceState));
|
||||
}
|
||||
|
||||
retrievePkceState(state: string): OidcPkceState | null {
|
||||
const key = `oidc_pkce_${state}`;
|
||||
const stored = sessionStorage.getItem(key);
|
||||
sessionStorage.removeItem(key);
|
||||
if (!stored) return null;
|
||||
try {
|
||||
return JSON.parse(stored);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private buildUrl(
|
||||
endpoint: string,
|
||||
clientId: string,
|
||||
redirectUri: string,
|
||||
scope: string,
|
||||
codeChallenge: string,
|
||||
state: string,
|
||||
nonce: string
|
||||
): string {
|
||||
const params = new URLSearchParams({
|
||||
response_type: 'code',
|
||||
client_id: clientId,
|
||||
redirect_uri: redirectUri,
|
||||
scope,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
state,
|
||||
nonce,
|
||||
});
|
||||
return `${endpoint}?${params.toString()}`;
|
||||
}
|
||||
|
||||
private base64UrlEncode(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
for (const byte of bytes) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return btoa(binary)
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ export class AuthorService {
|
||||
}
|
||||
|
||||
autoMatchAuthors(authorIds: number[]): Observable<AuthorSummary> {
|
||||
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
const headers = new HttpHeaders()
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
@@ -101,7 +101,7 @@ export class AuthorService {
|
||||
}
|
||||
|
||||
getAuthorPhotoUrl(authorId: number): string {
|
||||
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
let url = `${this.mediaBaseUrl}/author/${authorId}/photo`;
|
||||
if (token) {
|
||||
url += `?token=${token}`;
|
||||
@@ -110,7 +110,7 @@ export class AuthorService {
|
||||
}
|
||||
|
||||
getAuthorThumbnailUrl(authorId: number, cacheBuster?: number): string {
|
||||
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
let url = `${this.mediaBaseUrl}/author/${authorId}/thumbnail`;
|
||||
if (token) {
|
||||
url += `?token=${token}`;
|
||||
|
||||
@@ -16,9 +16,7 @@ export class BookMetadataService {
|
||||
private sseClient = inject(SseClient);
|
||||
|
||||
fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable<BookMetadata> {
|
||||
const token =
|
||||
this.authService.getOidcAccessToken() ||
|
||||
this.authService.getInternalAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
|
||||
if (!token) {
|
||||
throw new Error('No authentication token available');
|
||||
|
||||
@@ -17,7 +17,7 @@ export class CbxReaderService {
|
||||
private http = inject(HttpClient);
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
private appendToken(url: string): string {
|
||||
|
||||
@@ -167,7 +167,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
// Load cover URLs - prefer stored audiobook cover, fall back to embedded, then book cover
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${this.bookId}/cover?token=${encodeURIComponent(token || '')}`;
|
||||
this.coverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${this.bookId}/audiobook-cover?token=${encodeURIComponent(token || '')}`;
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ export class AudiobookService {
|
||||
}
|
||||
|
||||
getStreamUrl(bookId: number, trackIndex?: number): string {
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
let url = `${this.baseUrl}/${bookId}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
|
||||
if (trackIndex !== undefined && trackIndex !== null) {
|
||||
url += `&trackIndex=${trackIndex}`;
|
||||
@@ -34,12 +34,12 @@ export class AudiobookService {
|
||||
}
|
||||
|
||||
getTrackStreamUrl(bookId: number, trackIndex: number): string {
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
return `${this.baseUrl}/${bookId}/track/${trackIndex}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
|
||||
}
|
||||
|
||||
getEmbeddedCoverUrl(bookId: number): string {
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
return `${this.baseUrl}/${bookId}/cover?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,6 @@ export class EpubStreamingService {
|
||||
}
|
||||
|
||||
getAuthToken(): string | null {
|
||||
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
||||
this.bookData = this.altBookType
|
||||
? `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content?bookType=${this.altBookType}`
|
||||
: `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content`;
|
||||
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
this.authorization = token ? `Bearer ${token}` : '';
|
||||
this.isLoading = false;
|
||||
},
|
||||
|
||||
@@ -17,121 +17,94 @@
|
||||
<p class="login-subtitle">{{ t('subtitle') }}</p>
|
||||
</div>
|
||||
|
||||
@if (showOidcBypassInfo) {
|
||||
<div class="oidc-warning">
|
||||
<div class="warning-content">
|
||||
<div class="warning-header">
|
||||
<i class="pi pi-exclamation-triangle"></i>
|
||||
<span>{{ t('oidcWarningTitle') }}</span>
|
||||
</div>
|
||||
<p class="warning-message">{{ oidcBypassMessage }}</p>
|
||||
<div class="warning-actions">
|
||||
<p-button
|
||||
size="small"
|
||||
severity="warn"
|
||||
[label]="t('retryOidc')"
|
||||
icon="pi pi-refresh"
|
||||
(click)="retryOidc()"
|
||||
/>
|
||||
<p-button
|
||||
size="small"
|
||||
severity="success"
|
||||
[label]="t('useLocalLogin')"
|
||||
icon="pi pi-times"
|
||||
(click)="dismissOidcWarning()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@if (infoMessage) {
|
||||
<div class="info-message" style="margin-bottom: 1rem;">
|
||||
<p-message severity="info">{{ infoMessage }}</p-message>
|
||||
</div>
|
||||
}
|
||||
|
||||
<form class="login-form" #loginForm="ngForm" (ngSubmit)="login()">
|
||||
<div class="form-field">
|
||||
<label for="username" class="form-label">
|
||||
<i class="pi pi-user"></i>
|
||||
<span>{{ t('usernameLabel') }}</span>
|
||||
</label>
|
||||
<input
|
||||
fluid
|
||||
pInputText
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
[(ngModel)]="username"
|
||||
[placeholder]="t('usernamePlaceholder')"
|
||||
class="form-input"
|
||||
autocomplete="username"
|
||||
/>
|
||||
@if (errorMessage) {
|
||||
<div class="error-message" style="margin-bottom: 1rem;">
|
||||
<p-message severity="error">{{ errorMessage }}</p-message>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="form-field">
|
||||
<label for="password" class="form-label">
|
||||
<i class="pi pi-lock"></i>
|
||||
<span>{{ t('passwordLabel') }}</span>
|
||||
</label>
|
||||
<p-password
|
||||
id="password"
|
||||
name="password"
|
||||
required
|
||||
[(ngModel)]="password"
|
||||
[feedback]="false"
|
||||
[placeholder]="t('passwordPlaceholder')"
|
||||
[toggleMask]="true"
|
||||
[fluid]="true"
|
||||
autocomplete="current-password"
|
||||
></p-password>
|
||||
</div>
|
||||
|
||||
<p-button
|
||||
fluid
|
||||
type="submit"
|
||||
[label]="t('signIn')"
|
||||
icon="pi pi-sign-in"
|
||||
[disabled]="!loginForm.valid || !username || !password"
|
||||
class="login-button">
|
||||
</p-button>
|
||||
|
||||
@if (errorMessage) {
|
||||
<div class="error-message">
|
||||
<p-message severity="error">{{ errorMessage }}</p-message>
|
||||
@if (showLocalLogin) {
|
||||
<form class="login-form" #loginForm="ngForm" (ngSubmit)="login()">
|
||||
<div class="form-field">
|
||||
<label for="username" class="form-label">
|
||||
<i class="pi pi-user"></i>
|
||||
<span>{{ t('usernameLabel') }}</span>
|
||||
</label>
|
||||
<input
|
||||
fluid
|
||||
pInputText
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
[(ngModel)]="username"
|
||||
[placeholder]="t('usernamePlaceholder')"
|
||||
class="form-input"
|
||||
autocomplete="username"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (oidcEnabled && !isOidcBypassed) {
|
||||
<div class="divider">
|
||||
<span>{{ t('orContinueWith') }}</span>
|
||||
<div class="form-field">
|
||||
<label for="password" class="form-label">
|
||||
<i class="pi pi-lock"></i>
|
||||
<span>{{ t('passwordLabel') }}</span>
|
||||
</label>
|
||||
<p-password
|
||||
id="password"
|
||||
name="password"
|
||||
required
|
||||
[(ngModel)]="password"
|
||||
[feedback]="false"
|
||||
[placeholder]="t('passwordPlaceholder')"
|
||||
[toggleMask]="true"
|
||||
[fluid]="true"
|
||||
autocomplete="current-password"
|
||||
></p-password>
|
||||
</div>
|
||||
|
||||
<p-button
|
||||
fluid
|
||||
severity="secondary"
|
||||
[label]="isOidcLoginInProgress ? t('redirectingTo', {provider: oidcName}) : oidcName"
|
||||
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
|
||||
[disabled]="isOidcLoginInProgress"
|
||||
(click)="loginWithOidc()"
|
||||
class="oidc-button"/>
|
||||
type="submit"
|
||||
[label]="t('signIn')"
|
||||
icon="pi pi-sign-in"
|
||||
[disabled]="!loginForm.valid || !username || !password"
|
||||
class="login-button">
|
||||
</p-button>
|
||||
|
||||
<div class="help-text">
|
||||
<button
|
||||
type="button"
|
||||
class="text-link"
|
||||
(click)="bypassOidc()">
|
||||
{{ t('oidcTrouble', {provider: oidcName}) }}
|
||||
</button>
|
||||
@if (oidcEnabled) {
|
||||
<div class="divider">
|
||||
<span>{{ t('orContinueWith') }}</span>
|
||||
</div>
|
||||
|
||||
<p-button
|
||||
fluid
|
||||
severity="secondary"
|
||||
[label]="isOidcLoginInProgress ? t('redirectingTo', {provider: oidcName}) : oidcName"
|
||||
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
|
||||
[disabled]="isOidcLoginInProgress"
|
||||
(click)="loginWithOidc()"
|
||||
class="oidc-button"/>
|
||||
}
|
||||
</form>
|
||||
} @else {
|
||||
@if (oidcEnabled) {
|
||||
<div class="login-form">
|
||||
<p-button
|
||||
fluid
|
||||
severity="secondary"
|
||||
[label]="isOidcLoginInProgress ? t('redirectingTo', {provider: oidcName}) : oidcName"
|
||||
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
|
||||
[disabled]="isOidcLoginInProgress"
|
||||
(click)="loginWithOidc()"
|
||||
class="oidc-button"/>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (oidcEnabled && isOidcBypassed) {
|
||||
<div class="help-text">
|
||||
<button
|
||||
type="button"
|
||||
class="text-link primary"
|
||||
(click)="enableOidc()">
|
||||
{{ t('reEnableOidc', {provider: oidcName}) }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Password} from 'primeng/password';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Message} from 'primeng/message';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {Observable, Subject} from 'rxjs';
|
||||
import {Observable} from 'rxjs';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {getOidcErrorCount, isOidcBypassed, resetOidcBypass} from '../../../core/security/auth-initializer';
|
||||
import {AppSettingsService, PublicAppSettings} from '../../service/app-settings.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {OidcService} from '../../../core/security/oidc.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
@@ -26,28 +25,46 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
templateUrl: './login.component.html',
|
||||
styleUrls: ['./login.component.scss']
|
||||
})
|
||||
export class LoginComponent implements OnInit, OnDestroy {
|
||||
export class LoginComponent implements OnInit {
|
||||
username = '';
|
||||
password = '';
|
||||
errorMessage = '';
|
||||
infoMessage = '';
|
||||
oidcEnabled = false;
|
||||
oidcName = 'OIDC';
|
||||
isOidcBypassed = false;
|
||||
showOidcBypassInfo = false;
|
||||
oidcBypassMessage = '';
|
||||
isOidcLoginInProgress = false;
|
||||
showLocalLogin = true;
|
||||
private oidcOnlyAutoRedirect = false;
|
||||
|
||||
private authService = inject(AuthService);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private oidcService = inject(OidcService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private router = inject(Router);
|
||||
private route = inject(ActivatedRoute);
|
||||
private translocoService = inject(TranslocoService);
|
||||
|
||||
publicAppSettings$: Observable<PublicAppSettings | null> = this.appSettingsService.publicAppSettings$;
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private static readonly OIDC_ERROR_KEYS: Record<string, string> = {
|
||||
'state_mismatch': 'auth.login.oidcErrors.stateMismatch',
|
||||
'missing_code': 'auth.login.oidcErrors.stateMismatch',
|
||||
'exchange_failed': 'auth.login.oidcErrors.exchangeFailed'
|
||||
};
|
||||
|
||||
private static readonly MAX_REDIRECT_COUNT = 3;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.queryParams.pipe(take(1)).subscribe(params => {
|
||||
if (params['reason'] === 'session_revoked') {
|
||||
this.infoMessage = this.translocoService.translate('auth.login.sessionRevoked');
|
||||
}
|
||||
|
||||
const oidcError = params['oidcError'];
|
||||
if (oidcError) {
|
||||
this.errorMessage = this.resolveOidcError(oidcError);
|
||||
}
|
||||
});
|
||||
|
||||
this.publicAppSettings$
|
||||
.pipe(
|
||||
filter(settings => settings != null),
|
||||
@@ -56,25 +73,55 @@ export class LoginComponent implements OnInit, OnDestroy {
|
||||
.subscribe(publicSettings => {
|
||||
this.oidcEnabled = publicSettings!.oidcEnabled;
|
||||
this.oidcName = publicSettings!.oidcProviderDetails?.providerName || 'OIDC';
|
||||
this.checkOidcBypassStatus();
|
||||
|
||||
this.route.queryParams.pipe(take(1)).subscribe(params => {
|
||||
const isLocalMode = params['local'] === 'true';
|
||||
const hasOidcError = !!params['oidcError'];
|
||||
|
||||
if (publicSettings!.oidcForceOnlyMode && !isLocalMode && !hasOidcError) {
|
||||
this.handleAutoRedirect();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private checkOidcBypassStatus(): void {
|
||||
this.isOidcBypassed = isOidcBypassed();
|
||||
const errorCount = getOidcErrorCount();
|
||||
private handleAutoRedirect(): void {
|
||||
const countStr = sessionStorage.getItem('oidc_redirect_count');
|
||||
const count = countStr ? parseInt(countStr, 10) : 0;
|
||||
|
||||
if (this.oidcEnabled && (this.isOidcBypassed || errorCount > 0)) {
|
||||
this.showOidcBypassInfo = true;
|
||||
|
||||
if (this.isOidcBypassed && errorCount >= 3) {
|
||||
this.oidcBypassMessage = this.translocoService.translate('auth.login.oidcAutoDisabled', {provider: this.oidcName, count: errorCount});
|
||||
} else if (this.isOidcBypassed) {
|
||||
this.oidcBypassMessage = this.translocoService.translate('auth.login.oidcManuallyDisabled', {provider: this.oidcName});
|
||||
} else if (errorCount > 0) {
|
||||
this.oidcBypassMessage = this.translocoService.translate('auth.login.oidcErrors', {provider: this.oidcName, count: errorCount});
|
||||
}
|
||||
if (count >= LoginComponent.MAX_REDIRECT_COUNT) {
|
||||
sessionStorage.removeItem('oidc_redirect_count');
|
||||
this.errorMessage = this.translocoService.translate('auth.login.oidcOnlyRedirectFailed');
|
||||
this.showLocalLogin = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.oidcOnlyAutoRedirect = true;
|
||||
sessionStorage.setItem('oidc_redirect_count', String(count + 1));
|
||||
this.showLocalLogin = false;
|
||||
this.loginWithOidc();
|
||||
}
|
||||
|
||||
private resolveOidcError(error: string): string {
|
||||
if (error.startsWith('OIDC user')) {
|
||||
return this.translocoService.translate('auth.login.oidcErrors.userNotProvisioned');
|
||||
}
|
||||
if (error.startsWith('Cannot reach')) {
|
||||
return this.translocoService.translate('auth.login.oidcErrors.providerUnreachable');
|
||||
}
|
||||
if (error.startsWith('Invalid token') || error.startsWith('No token')) {
|
||||
return this.translocoService.translate('auth.login.oidcErrors.invalidToken');
|
||||
}
|
||||
if (error.startsWith('Failed to exchange') || error.includes('token exchange')) {
|
||||
return this.translocoService.translate('auth.login.oidcErrors.exchangeFailed');
|
||||
}
|
||||
|
||||
const key = LoginComponent.OIDC_ERROR_KEYS[error];
|
||||
if (key) {
|
||||
return this.translocoService.translate(key);
|
||||
}
|
||||
|
||||
return this.translocoService.translate('auth.login.oidcErrors.unknown');
|
||||
}
|
||||
|
||||
login(): void {
|
||||
@@ -98,7 +145,7 @@ export class LoginComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
loginWithOidc(): void {
|
||||
async loginWithOidc(): Promise<void> {
|
||||
if (this.isOidcLoginInProgress) {
|
||||
return;
|
||||
}
|
||||
@@ -107,45 +154,36 @@ export class LoginComponent implements OnInit, OnDestroy {
|
||||
this.errorMessage = '';
|
||||
|
||||
try {
|
||||
setTimeout(() => {
|
||||
const publicSettings = this.appSettingsService.currentPublicSettings;
|
||||
if (!publicSettings?.oidcProviderDetails) {
|
||||
this.errorMessage = this.translocoService.translate('auth.login.oidcInitError');
|
||||
this.isOidcLoginInProgress = false;
|
||||
}, 5000);
|
||||
this.oAuthService.initCodeFlow();
|
||||
return;
|
||||
}
|
||||
|
||||
const details = publicSettings.oidcProviderDetails;
|
||||
const pkce = await this.oidcService.generatePkce();
|
||||
const state = await this.oidcService.fetchState();
|
||||
const nonce = this.oidcService.generateRandomString();
|
||||
|
||||
this.oidcService.storePkceState({codeVerifier: pkce.codeVerifier, state, nonce});
|
||||
|
||||
const authUrl = await this.oidcService.buildAuthUrl(
|
||||
details.issuerUri,
|
||||
details.clientId,
|
||||
pkce.codeChallenge,
|
||||
state,
|
||||
nonce
|
||||
);
|
||||
|
||||
window.location.href = authUrl;
|
||||
} catch (error) {
|
||||
console.error('OIDC login initiation failed:', error);
|
||||
this.errorMessage = this.translocoService.translate('auth.login.oidcInitError');
|
||||
sessionStorage.removeItem('oidc_redirect_count');
|
||||
this.errorMessage = this.translocoService.translate('auth.login.oidcErrors.providerUnreachable');
|
||||
this.showLocalLogin = !this.oidcOnlyAutoRedirect;
|
||||
this.isOidcLoginInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
bypassOidc(): void {
|
||||
localStorage.setItem('booklore-oidc-bypass', 'true');
|
||||
this.isOidcBypassed = true;
|
||||
this.showOidcBypassInfo = false;
|
||||
}
|
||||
|
||||
enableOidc(): void {
|
||||
resetOidcBypass();
|
||||
this.isOidcBypassed = false;
|
||||
this.showOidcBypassInfo = false;
|
||||
this.isOidcLoginInProgress = false;
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
retryOidc(): void {
|
||||
resetOidcBypass();
|
||||
this.isOidcBypassed = false;
|
||||
this.showOidcBypassInfo = false;
|
||||
this.isOidcLoginInProgress = false;
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
dismissOidcWarning(): void {
|
||||
this.showOidcBypassInfo = false;
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,16 +33,19 @@ export interface MetadataMatchWeights {
|
||||
export interface OidcProviderDetails {
|
||||
providerName: string;
|
||||
clientId: string;
|
||||
clientSecret?: string;
|
||||
issuerUri: string;
|
||||
claimMapping: {
|
||||
username: string;
|
||||
email: string;
|
||||
name: string;
|
||||
groups: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OidcAutoProvisionDetails {
|
||||
enableAutoProvisioning: boolean;
|
||||
allowLocalAccountLinking: boolean;
|
||||
defaultPermissions: string[];
|
||||
defaultLibraryIds: number[];
|
||||
}
|
||||
@@ -156,6 +159,17 @@ export interface CoverCroppingSettings {
|
||||
smartCroppingEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface OidcTestCheck {
|
||||
name: string;
|
||||
status: 'PASS' | 'FAIL' | 'WARN' | 'SKIP';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface OidcTestResult {
|
||||
success: boolean;
|
||||
checks: OidcTestCheck[];
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
autoBookSearch: boolean;
|
||||
similarBookRecommendation: boolean;
|
||||
@@ -179,6 +193,9 @@ export interface AppSettings {
|
||||
metadataDownloadOnBookdrop: boolean;
|
||||
telemetryEnabled: boolean;
|
||||
metadataProviderSpecificFields: MetadataProviderSpecificFields;
|
||||
oidcSessionDurationHours: number | null;
|
||||
oidcGroupSyncMode: string | null;
|
||||
oidcForceOnlyMode: boolean;
|
||||
diskType: string;
|
||||
}
|
||||
|
||||
@@ -226,4 +243,7 @@ export enum AppSettingKey {
|
||||
COVER_CROPPING_SETTINGS = 'COVER_CROPPING_SETTINGS',
|
||||
TELEMETRY_ENABLED = 'TELEMETRY_ENABLED',
|
||||
METADATA_PROVIDER_SPECIFIC_FIELDS = 'METADATA_PROVIDER_SPECIFIC_FIELDS',
|
||||
OIDC_SESSION_DURATION_HOURS = 'OIDC_SESSION_DURATION_HOURS',
|
||||
OIDC_GROUP_SYNC_MODE = 'OIDC_GROUP_SYNC_MODE',
|
||||
OIDC_FORCE_ONLY_MODE = 'OIDC_FORCE_ONLY_MODE',
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
export interface OidcGroupMapping {
|
||||
id?: number;
|
||||
oidcGroupClaim: string;
|
||||
isAdmin: boolean;
|
||||
permissions: string[];
|
||||
libraryIds: number[];
|
||||
description: string;
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
import {inject, Injectable, Injector} from '@angular/core';
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {catchError, finalize, map, shareReplay, switchMap, tap} from 'rxjs/operators';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AppSettings, OidcProviderDetails} from '../model/app-settings.model';
|
||||
import {AuthService} from './auth.service';
|
||||
import {AppSettings, OidcProviderDetails, OidcTestResult} from '../model/app-settings.model';
|
||||
|
||||
export interface PublicAppSettings {
|
||||
oidcEnabled: boolean;
|
||||
remoteAuthEnabled: boolean;
|
||||
oidcProviderDetails: OidcProviderDetails;
|
||||
oidcForceOnlyMode: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class AppSettingsService {
|
||||
private http = inject(HttpClient);
|
||||
private injector = inject(Injector);
|
||||
|
||||
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/settings`;
|
||||
private readonly publicApiUrl = `${API_CONFIG.BASE_URL}/api/v1/public-settings`;
|
||||
@@ -50,6 +49,10 @@ export class AppSettingsService {
|
||||
})
|
||||
);
|
||||
|
||||
get currentPublicSettings(): PublicAppSettings | null {
|
||||
return this.publicAppSettingsSubject.value;
|
||||
}
|
||||
|
||||
private fetchAppSettings(): Observable<AppSettings> {
|
||||
return this.http.get<AppSettings>(this.apiUrl).pipe(
|
||||
tap(settings => {
|
||||
@@ -74,11 +77,16 @@ export class AppSettingsService {
|
||||
);
|
||||
}
|
||||
|
||||
testOidcConnection(providerDetails: OidcProviderDetails): Observable<OidcTestResult> {
|
||||
return this.http.post<OidcTestResult>(`${this.apiUrl}/oidc/test`, providerDetails);
|
||||
}
|
||||
|
||||
private syncPublicSettings(appSettings: AppSettings): void {
|
||||
const updatedPublicSettings: PublicAppSettings = {
|
||||
oidcEnabled: appSettings.oidcEnabled,
|
||||
remoteAuthEnabled: appSettings.remoteAuthEnabled,
|
||||
oidcProviderDetails: appSettings.oidcProviderDetails
|
||||
oidcProviderDetails: appSettings.oidcProviderDetails,
|
||||
oidcForceOnlyMode: appSettings.oidcForceOnlyMode
|
||||
};
|
||||
const current = this.publicAppSettingsSubject.value;
|
||||
|
||||
@@ -86,6 +94,7 @@ export class AppSettingsService {
|
||||
!current ||
|
||||
current.oidcEnabled !== updatedPublicSettings.oidcEnabled ||
|
||||
current.remoteAuthEnabled !== updatedPublicSettings.remoteAuthEnabled ||
|
||||
current.oidcForceOnlyMode !== updatedPublicSettings.oidcForceOnlyMode ||
|
||||
JSON.stringify(current.oidcProviderDetails) !== JSON.stringify(updatedPublicSettings.oidcProviderDetails)
|
||||
) {
|
||||
this.publicAppSettingsSubject.next(updatedPublicSettings);
|
||||
@@ -118,12 +127,6 @@ export class AppSettingsService {
|
||||
this.appSettingsSubject.next({...current});
|
||||
this.syncPublicSettings(current);
|
||||
}
|
||||
if (!enabled) {
|
||||
const authService = this.injector.get(AuthService);
|
||||
setTimeout(() => {
|
||||
authService.clearOIDCTokens();
|
||||
});
|
||||
}
|
||||
}),
|
||||
catchError(err => {
|
||||
console.error('Error toggling OIDC:', err);
|
||||
|
||||
@@ -4,7 +4,6 @@ import {BehaviorSubject, Observable, tap} from 'rxjs';
|
||||
import {RxStompService} from '../websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {createRxStompConfig} from '../websocket/rx-stomp.config';
|
||||
import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc';
|
||||
import {Router} from '@angular/router';
|
||||
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
|
||||
|
||||
@@ -19,12 +18,10 @@ export class AuthService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private injector = inject(Injector);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private oAuthStorage = inject(OAuthStorage);
|
||||
private router = inject(Router);
|
||||
private postLoginInitializer = inject(PostLoginInitializerService);
|
||||
|
||||
public tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken());
|
||||
public tokenSubject = new BehaviorSubject<string | null>(this.getInternalAccessToken());
|
||||
public token$ = this.tokenSubject.asObservable();
|
||||
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
|
||||
@@ -72,36 +69,39 @@ export class AuthService {
|
||||
return localStorage.getItem('accessToken_Internal');
|
||||
}
|
||||
|
||||
getOidcAccessToken(): string | null {
|
||||
return this.oAuthService.getIdToken();
|
||||
}
|
||||
|
||||
getInternalRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken_Internal');
|
||||
}
|
||||
|
||||
clearOIDCTokens(): void {
|
||||
const hasInternalTokens = this.getInternalAccessToken() || this.getInternalRefreshToken();
|
||||
if (!hasInternalTokens) {
|
||||
this.oAuthStorage.removeItem("access_token");
|
||||
this.oAuthStorage.removeItem("refresh_token");
|
||||
this.oAuthStorage.removeItem("id_token");
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
logout(): void {
|
||||
const refreshToken = this.getInternalRefreshToken();
|
||||
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, {refreshToken}).subscribe({
|
||||
next: (response) => {
|
||||
this.clearSession();
|
||||
if (response.logoutUrl) {
|
||||
window.location.href = response.logoutUrl;
|
||||
} else {
|
||||
this.router.navigate(['/login']).then(() => window.location.reload());
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.clearSession();
|
||||
this.router.navigate(['/login']).then(() => window.location.reload());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
forceLogout(reason: string): void {
|
||||
this.clearSession();
|
||||
this.router.navigate(['/login'], {queryParams: {reason}});
|
||||
}
|
||||
|
||||
private clearSession(): void {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
localStorage.removeItem('refreshToken_Internal');
|
||||
this.oAuthStorage.removeItem("access_token");
|
||||
this.oAuthStorage.removeItem("refresh_token");
|
||||
this.oAuthStorage.removeItem("id_token");
|
||||
this.tokenSubject.next(null);
|
||||
this.postLoginInitialized = false;
|
||||
this.getRxStompService().deactivate();
|
||||
this.router.navigate(['/login']).then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
getRxStompService(): RxStompService {
|
||||
@@ -112,7 +112,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
initializeWebSocketConnection(): void {
|
||||
const token = this.getOidcAccessToken() || this.getInternalAccessToken();
|
||||
const token = this.getInternalAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
const stompService = this.getRxStompService();
|
||||
|
||||
@@ -68,7 +68,7 @@ export class CustomFontService {
|
||||
}
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
public appendToken(url: string): string {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {OidcGroupMapping} from '../model/oidc-group-mapping.model';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class OidcGroupMappingService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private baseUrl = `${API_CONFIG.BASE_URL}/api/v1/admin/oidc-group-mappings`;
|
||||
|
||||
getAll(): Observable<OidcGroupMapping[]> {
|
||||
return this.http.get<OidcGroupMapping[]>(this.baseUrl);
|
||||
}
|
||||
|
||||
create(mapping: OidcGroupMapping): Observable<OidcGroupMapping> {
|
||||
return this.http.post<OidcGroupMapping>(this.baseUrl, mapping);
|
||||
}
|
||||
|
||||
update(id: number, mapping: OidcGroupMapping): Observable<OidcGroupMapping> {
|
||||
return this.http.put<OidcGroupMapping>(`${this.baseUrl}/${id}`, mapping);
|
||||
}
|
||||
|
||||
delete(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.baseUrl}/${id}`);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import {AuthService} from './auth.service';
|
||||
import {UserService} from '../../features/settings/user-management/user.service';
|
||||
import {filter, catchError} from 'rxjs/operators';
|
||||
import {of} from 'rxjs';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class StartupService {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class UrlHelperService {
|
||||
private router = inject(Router);
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
private appendToken(url: string): string {
|
||||
|
||||
@@ -9,9 +9,7 @@ export function createRxStompConfig(authService: AuthService): RxStompConfig {
|
||||
heartbeatOutgoing: 20000,
|
||||
reconnectDelay: 10000,
|
||||
beforeConnect: (stomp) => {
|
||||
const oidcToken = authService.getOidcAccessToken();
|
||||
const internalToken = authService.getInternalAccessToken();
|
||||
const token = oidcToken || internalToken;
|
||||
const token = authService.getInternalAccessToken();
|
||||
if (token) {
|
||||
stomp.stompClient.connectHeaders = {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
|
||||
Reference in New Issue
Block a user