From bba3309310ac92fc1af844885e9aa46b1d5e7d7a Mon Sep 17 00:00:00 2001 From: "aditya.chandel" Date: Sat, 28 Jun 2025 18:18:34 -0600 Subject: [PATCH 1/7] Sync favicon color with primary theme --- .../theme-configurator/favicon-service.ts | 27 +++++++++++++++++++ .../theme-configurator.component.ts | 20 +++++++++++--- 2 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 booklore-ui/src/app/layout/component/theme-configurator/favicon-service.ts diff --git a/booklore-ui/src/app/layout/component/theme-configurator/favicon-service.ts b/booklore-ui/src/app/layout/component/theme-configurator/favicon-service.ts new file mode 100644 index 000000000..6283061b1 --- /dev/null +++ b/booklore-ui/src/app/layout/component/theme-configurator/favicon-service.ts @@ -0,0 +1,27 @@ +import {Injectable} from '@angular/core'; + +@Injectable({providedIn: 'root'}) +export class FaviconService { + private svgTemplate = (color: string) => ` + + + + + `; + + updateFavicon(color: string) { + const svg = this.svgTemplate(color); + const blob = new Blob([svg], {type: 'image/svg+xml'}); + const url = URL.createObjectURL(blob); + + let favicon = document.querySelector("link[rel*='icon']") as HTMLLinkElement; + if (!favicon) { + favicon = document.createElement('link'); + favicon.rel = 'icon'; + document.head.appendChild(favicon); + } + + favicon.type = 'image/svg+xml'; + favicon.href = url; + } +} diff --git a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts index c5bb03c2a..04667b4ab 100644 --- a/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts +++ b/booklore-ui/src/app/layout/component/theme-configurator/theme-configurator.component.ts @@ -1,5 +1,5 @@ import {CommonModule, isPlatformBrowser} from '@angular/common'; -import {Component, computed, inject, OnInit, PLATFORM_ID} from '@angular/core'; +import {Component, computed, effect, inject, OnInit, PLATFORM_ID} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes'; import Aura from '@primeng/themes/aura'; @@ -9,6 +9,7 @@ import {InputSwitchModule} from 'primeng/inputswitch'; import {RadioButtonModule} from 'primeng/radiobutton'; import {ToggleSwitchModule} from 'primeng/toggleswitch'; import {AppConfigService} from '../../../core/service/app-config.service'; +import {FaviconService} from './favicon-service'; type ColorPalette = Record; @@ -30,6 +31,7 @@ export class ThemeConfiguratorComponent implements OnInit { readonly config = inject(PrimeNG); readonly configService = inject(AppConfigService); readonly platformId = inject(PLATFORM_ID); + readonly faviconService = inject(FaviconService); readonly surfaces: Palette[] = [ { @@ -172,11 +174,21 @@ export class ThemeConfiguratorComponent implements OnInit { readonly selectedPrimaryColor = computed(() => this.configService.appState().primary); readonly selectedSurfaceColor = computed(() => this.configService.appState().surface); + readonly faviconColor = computed(() => { + const name = this.selectedPrimaryColor() ?? 'green'; + const presetPalette = (Aura.primitive ?? {}) as Record; + const colorPalette = presetPalette[name]; + return colorPalette?.[500] ?? name; + }); + + private readonly _faviconSyncEffect = effect(() => { + this.faviconService.updateFavicon(this.faviconColor()); + }); readonly primaryColors = computed(() => { const presetPalette = (Aura.primitive ?? {}) as Record; const colors = ['emerald', 'green', 'lime', 'orange', 'amber', 'yellow', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']; - return [{ name: 'noir', palette: {} }].concat( + return [{name: 'noir', palette: {}}].concat( colors.map(name => ({ name, palette: presetPalette[name] ?? {} @@ -198,7 +210,7 @@ export class ThemeConfiguratorComponent implements OnInit { if (color.name === 'noir') { return { semantic: { - primary: { ...(surface?.palette ?? {}) }, + primary: {...(surface?.palette ?? {})}, colorScheme: { dark: { primary: { @@ -262,6 +274,6 @@ export class ThemeConfiguratorComponent implements OnInit { onPresetChange(): void { const surface = this.surfaces.find(s => s.name === this.selectedSurfaceColor()); const surfacePalette = surface?.palette ?? {}; - $t().preset(Aura).preset(this.getPresetExt()).surfacePalette(surfacePalette).use({ useDefaultOptions: true }); + $t().preset(Aura).preset(this.getPresetExt()).surfacePalette(surfacePalette).use({useDefaultOptions: true}); } } From 3f286ef575f9fc8093d0a43eafbcbdff1458bade Mon Sep 17 00:00:00 2001 From: "aditya.chandel" Date: Sat, 28 Jun 2025 19:03:40 -0600 Subject: [PATCH 2/7] Implement click-to-filter for series and publisher from book metadata --- .../metadata-viewer.component.html | 32 +++++++++---- .../metadata-viewer.component.ts | 47 +++++++++---------- 2 files changed, 44 insertions(+), 35 deletions(-) diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html index 8f49d42f0..df6de3273 100644 --- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -29,8 +29,13 @@
- @if (book?.metadata!.seriesName) { -

{{ book?.metadata!.seriesName }} #{{ book?.metadata!.seriesNumber }}

+ @if (book?.metadata?.seriesName) { +

+ {{ book?.metadata?.seriesName }} + @if (book?.metadata?.seriesNumber) { + #{{ book?.metadata?.seriesNumber }} + } +

}

{{ book?.metadata!.title }}

@@ -163,7 +168,16 @@

-

Publisher: {{ book?.metadata!.publisher || '-' }}

+

+ Publisher: + @if (book?.metadata?.publisher) { + + {{ book?.metadata?.publisher }} + + } @else { + - + } +

Published: {{ book?.metadata!.publishedDate || '-' }}

Language: {{ book?.metadata!.language || '-' }}

ISBN 10: {{ book?.metadata!.isbn10 || '-' }}

@@ -311,12 +325,12 @@ @if (book.metadata!.description && book.metadata!.description.length > 100) {
} diff --git a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index b22c3733f..bde55c22c 100644 --- a/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/book/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -374,47 +374,42 @@ export class MetadataViewerComponent implements OnInit, OnChanges { } goToAuthorBooks(author: string): void { - if (this.metadataCenterViewMode === 'dialog') { - this.dialogRef?.close(); - setTimeout(() => this.navigateToAuthorBooks(author), 200); - } else { - this.navigateToAuthorBooks(author); - } - } - - private navigateToAuthorBooks(author: string): void { - this.router.navigate(['/all-books'], { - queryParams: { - view: 'grid', - sort: 'title', - direction: 'asc', - sidebar: true, - filter: `author:${author}` - } - }); + this.handleMetadataClick('author', author); } goToCategory(category: string): void { - if (this.metadataCenterViewMode === 'dialog') { - this.dialogRef?.close(); - setTimeout(() => this.navigateToCategory(category), 200); - } else { - this.navigateToCategory(category); - } + this.handleMetadataClick('category', category); } - private navigateToCategory(category: string): void { + goToSeries(seriesName: string): void { + this.handleMetadataClick('series', seriesName); + } + + goToPublisher(publisher: string): void { + this.handleMetadataClick('publisher', publisher); + } + + private navigateToFilteredBooks(filterKey: string, filterValue: string): void { this.router.navigate(['/all-books'], { queryParams: { view: 'grid', sort: 'title', direction: 'asc', sidebar: true, - filter: `category:${category}` + filter: `${filterKey}:${filterValue}` } }); } + private handleMetadataClick(filterKey: string, filterValue: string): void { + if (this.metadataCenterViewMode === 'dialog') { + this.dialogRef?.close(); + setTimeout(() => this.navigateToFilteredBooks(filterKey, filterValue), 200); + } else { + this.navigateToFilteredBooks(filterKey, filterValue); + } + } + getStatusSeverity(status: string): 'success' | 'secondary' | 'info' | 'warn' | 'danger' | undefined { const normalized = status?.toUpperCase(); if (['UNREAD', 'PAUSED'].includes(normalized)) return 'secondary'; From 98bd69164bf78371a001f271e1cf96364750a6e6 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" Date: Sat, 28 Jun 2025 21:52:04 -0600 Subject: [PATCH 3/7] Update discord invite link --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 580237450..39d622772 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ![License](https://img.shields.io/github/license/adityachandelgit/BookLore) ![Issues](https://img.shields.io/github/issues/adityachandelgit/BookLore) ![Stars](https://img.shields.io/github/stars/adityachandelgit/BookLore?style=social) -[![Join us on Discord](https://img.shields.io/badge/Chat-Discord-blue?logo=discord&style=flat)](https://discord.gg/yXdkBNCK) +[![Join us on Discord](https://img.shields.io/badge/Chat-Discord-blue?logo=discord&style=flat)](https://discord.gg/Ee5hd458Uz) BookLore is a self-hosted web app for organizing and managing your personal book collection. It provides an intuitive interface to browse, read, and track your progress across PDFs and eBooks. With robust metadata management, multi-user support, and a sleek, modern UI, BookLore makes it easy to build and explore your personal library. @@ -145,7 +145,7 @@ Example implementations: - ๐Ÿž Found a bug? [Open an issue](https://github.com/adityachandelgit/BookLore/issues) - โœจ Want to contribute? [Check out CONTRIBUTING.md](https://github.com/adityachandelgit/BookLore/blob/master/CONTRIBUTING.md) - ๐Ÿ’ฌ Ask questions or share feedback: [Discussions](https://github.com/adityachandelgit/BookLore/discussions) -- ๐Ÿ’ฌ **Join our Discord**: [Click here to chat with the community](https://discord.gg/yXdkBNCK) +- ๐Ÿ’ฌ **Join our Discord**: [Click here to chat with the community](https://discord.gg/Ee5hd458Uz) ## ๐Ÿ‘จโ€๐Ÿ’ป Contributors & Developers From f7db157689dc6099edd857eba2a37ccfc2c8204f Mon Sep 17 00:00:00 2001 From: "aditya.chandel" Date: Sun, 29 Jun 2025 00:50:19 -0600 Subject: [PATCH 4/7] Resolve broken Pocket ID auth and occasional Authentik failures --- .../security/DualJwtAuthenticationFilter.java | 76 +++++++---------- .../security/DynamicOidcJwtProcessor.java | 82 +++++++++++++++++++ .../config/security/OidcTokenValidator.java | 64 --------------- .../security/WebSocketAuthInterceptor.java | 25 +++--- .../custom/BookLoreUserTransformer.java | 11 ++- .../dto/settings/OidcProviderDetails.java | 1 - .../user/DefaultSettingInitializer.java | 3 +- .../service/user/UserDefaultsService.java | 7 +- booklore-ui/src/app/app.component.html | 17 +++- booklore-ui/src/app/app.component.scss | 49 +++++++++++ booklore-ui/src/app/app.component.ts | 7 ++ .../src/app/auth-initialization-service.ts | 12 +++ booklore-ui/src/app/auth-initializer.ts | 33 ++++---- booklore-ui/src/app/auth.guard.ts | 18 ++-- .../core/component/login/login.component.ts | 2 +- .../src/app/core/model/app-settings.model.ts | 1 - .../authentication-settings.component.html | 15 +--- .../authentication-settings.component.ts | 52 +----------- .../oidc-callback/oidc-callback.component.ts | 17 ++-- .../app/core/service/app-config.service.ts | 2 +- .../src/app/core/service/auth.service.ts | 19 +++-- .../layout-topbar/app.topbar.component.ts | 1 - 22 files changed, 278 insertions(+), 236 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/DynamicOidcJwtProcessor.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/OidcTokenValidator.java create mode 100644 booklore-ui/src/app/auth-initialization-service.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DualJwtAuthenticationFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DualJwtAuthenticationFilter.java index 4ae4530f7..764c57f06 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DualJwtAuthenticationFilter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DualJwtAuthenticationFilter.java @@ -10,18 +10,7 @@ import com.adityachandel.booklore.model.entity.UserPermissionsEntity; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.user.UserProvisioningService; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.jwk.source.DefaultJWKSetCache; -import com.nimbusds.jose.jwk.source.JWKSetCache; -import com.nimbusds.jose.jwk.source.JWKSource; -import com.nimbusds.jose.jwk.source.RemoteJWKSet; -import com.nimbusds.jose.proc.JWSKeySelector; -import com.nimbusds.jose.proc.JWSVerificationKeySelector; -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jose.util.DefaultResourceRetriever; import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; -import com.nimbusds.jwt.proc.DefaultJWTProcessor; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -37,14 +26,11 @@ import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.time.Duration; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; @Slf4j @Component @@ -56,6 +42,9 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter { private final UserRepository userRepository; private final AppSettingService appSettingService; private final UserProvisioningService userProvisioningService; + private static final ConcurrentMap userLocks = new ConcurrentHashMap<>(); + private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { @@ -103,50 +92,41 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter { private void authenticateOidcUser(String token, HttpServletRequest request) { try { OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); - String jwksUrl = providerDetails.getJwksUrl(); - if (jwksUrl == null || jwksUrl.isEmpty()) { - log.error("JWKS URL is not configured."); - throw ApiError.UNAUTHORIZED.createException("JWKS URL is not configured."); - } + JWTClaimsSet claimsSet = dynamicOidcJwtProcessor.getProcessor().process(token, null); - List defaultOidcUserPermissions = appSettingService.getAppSettings().getOidcAutoProvisionDetails().getDefaultPermissions(); - OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); - URL jwksURL = new URI(jwksUrl).toURL(); - - DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000); - Duration ttl = Duration.ofHours(6); - Duration refresh = Duration.ofHours(1); - JWKSetCache jwkSetCache = new DefaultJWKSetCache(ttl.toMillis(), refresh.toMillis(), TimeUnit.MILLISECONDS); - JWKSource jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever, jwkSetCache); - - ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); - JWSKeySelector keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource); - jwtProcessor.setJWSKeySelector(keySelector); - - JWTClaimsSet claimsSet = jwtProcessor.process(token, null); Date expirationTime = claimsSet.getExpirationTime(); if (expirationTime == null || expirationTime.before(new Date())) { log.warn("OIDC token is expired or missing exp claim"); throw ApiError.UNAUTHORIZED.createException("Token has expired or is invalid."); } + OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); String username = claimsSet.getStringClaim(claimMapping.getUsername()); String email = claimsSet.getStringClaim(claimMapping.getEmail()); String name = claimsSet.getStringClaim(claimMapping.getName()); - boolean autoProvisionOidcUsers = appSettingService.getAppSettings().getOidcAutoProvisionDetails().isEnableAutoProvisioning(); - OidcAutoProvisionDetails oidcAutoProvisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails(); + OidcAutoProvisionDetails provisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails(); + boolean autoProvision = provisionDetails != null && provisionDetails.isEnableAutoProvisioning(); - Optional userOpt = userRepository.findByUsername(username); - if (userOpt.isEmpty()) { - if (!autoProvisionOidcUsers) { - log.warn("User '{}' not found and auto-provisioning is disabled", username); - throw ApiError.UNAUTHORIZED.createException("User not found and auto-provisioning is disabled."); - } - log.info("Provisioning new OIDC user '{}'", username); - } - - BookLoreUserEntity entity = userOpt.orElseGet(() -> userProvisioningService.provisionOidcUser(username, email, name, oidcAutoProvisionDetails)); + BookLoreUserEntity entity = userRepository.findByUsername(username) + .orElseGet(() -> { + if (!autoProvision) { + log.warn("User '{}' not found and auto-provisioning is disabled.", username); + throw ApiError.UNAUTHORIZED.createException("User not found and auto-provisioning is disabled."); + } + Object lock = userLocks.computeIfAbsent(username, k -> new Object()); + try { + synchronized (lock) { + return userRepository.findByUsername(username) + .orElseGet(() -> { + log.info("Provisioning new OIDC user '{}'", username); + return userProvisioningService.provisionOidcUser(username, email, name, provisionDetails); + }); + } + } finally { + userLocks.remove(username); + } + }); BookLoreUser user = bookLoreUserTransformer.toDTO(entity); List authorities = getAuthorities(entity.getPermissions()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DynamicOidcJwtProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DynamicOidcJwtProcessor.java new file mode 100644 index 000000000..a50c2b17d --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/DynamicOidcJwtProcessor.java @@ -0,0 +1,82 @@ +package com.adityachandel.booklore.config.security; + +import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.jwk.source.DefaultJWKSetCache; +import com.nimbusds.jose.jwk.source.JWKSetCache; +import com.nimbusds.jose.jwk.source.JWKSource; +import com.nimbusds.jose.jwk.source.RemoteJWKSet; +import com.nimbusds.jose.proc.JWSKeySelector; +import com.nimbusds.jose.proc.JWSVerificationKeySelector; +import com.nimbusds.jose.proc.SecurityContext; +import com.nimbusds.jose.util.DefaultResourceRetriever; +import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; +import com.nimbusds.jwt.proc.DefaultJWTProcessor; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.net.URL; +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Component +@RequiredArgsConstructor +public class DynamicOidcJwtProcessor { + private final AppSettingService appSettingService; + + private volatile ConfigurableJWTProcessor jwtProcessor; + private volatile String currentIssuerUri; + + public synchronized ConfigurableJWTProcessor getProcessor() throws Exception { + String issuerUri = appSettingService.getAppSettings().getOidcProviderDetails().getIssuerUri(); + if (jwtProcessor == null || !issuerUri.equals(currentIssuerUri)) { + this.jwtProcessor = buildProcessor(issuerUri); + this.currentIssuerUri = issuerUri; + } + return jwtProcessor; + } + + private ConfigurableJWTProcessor buildProcessor(String issuerUri) throws Exception { + OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); + + if (providerDetails == null || providerDetails.getIssuerUri() == null || providerDetails.getIssuerUri().isEmpty()) { + throw new IllegalStateException("OIDC issuer URI is not configured in app settings."); + } + + String discoveryUri = providerDetails.getIssuerUri() + "/.well-known/openid-configuration"; + log.info("Fetching OIDC discovery document from {}", discoveryUri); + + URL jwksUrl = fetchJwksUri(discoveryUri); + + DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000); + + Duration ttl = Duration.ofHours(6); + Duration refresh = Duration.ofHours(1); + JWKSetCache jwkSetCache = new DefaultJWKSetCache(ttl.toMillis(), refresh.toMillis(), TimeUnit.MILLISECONDS); + + JWKSource jwkSource = new RemoteJWKSet<>(jwksUrl, resourceRetriever, jwkSetCache); + + JWSKeySelector keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource); + ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); + jwtProcessor.setJWSKeySelector(keySelector); + + return jwtProcessor; + } + + private URL fetchJwksUri(String discoveryUri) throws Exception { + var restClient = org.springframework.web.client.RestClient.create(); + var discoveryDoc = restClient.get() + .uri(discoveryUri) + .retrieve() + .body(new org.springframework.core.ParameterizedTypeReference>() {}); + + String jwksUri = (String) discoveryDoc.get("jwks_uri"); + if (jwksUri == null || jwksUri.isEmpty()) { + throw new IllegalStateException("jwks_uri not found in OIDC discovery document."); + } + return new URL(jwksUri); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/OidcTokenValidator.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/OidcTokenValidator.java deleted file mode 100644 index f5a754af3..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/OidcTokenValidator.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.adityachandel.booklore.config.security; - -import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; -import com.adityachandel.booklore.service.appsettings.AppSettingService; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.jwk.source.JWKSource; -import com.nimbusds.jose.jwk.source.RemoteJWKSet; -import com.nimbusds.jose.proc.JWSKeySelector; -import com.nimbusds.jose.proc.JWSVerificationKeySelector; -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jose.util.DefaultResourceRetriever; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; -import com.nimbusds.jwt.proc.DefaultJWTProcessor; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; - -import java.net.URI; -import java.net.URL; -import java.util.Collections; -import java.util.Date; - -@Slf4j -@Component -@RequiredArgsConstructor -public class OidcTokenValidator { - - private final AppSettingService appSettingService; - - public Authentication validate(String token) { - if (!appSettingService.getAppSettings().isOidcEnabled()) { - return null; - } - try { - OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); - String jwksUrl = providerDetails.getJwksUrl(); - if (jwksUrl == null || jwksUrl.isEmpty()) { - log.error("JWKS URL is not configured"); - return null; - } - - URL jwksURL = new URI(jwksUrl).toURL(); - DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000); - JWKSource jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever); - ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor<>(); - JWSKeySelector keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource); - jwtProcessor.setJWSKeySelector(keySelector); - - JWTClaimsSet claimsSet = jwtProcessor.process(token, null); - Date expirationTime = claimsSet.getExpirationTime(); - if (expirationTime == null || expirationTime.before(new Date())) { - log.warn("OIDC token is expired or missing exp claim"); - return null; - } - return new UsernamePasswordAuthenticationToken("oidc-user", null, Collections.emptyList()); - } catch (Exception e) { - log.error("OIDC token validation failed", e); - return null; - } - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java index 12dd6cb16..4f85a7f91 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java @@ -1,5 +1,6 @@ package com.adityachandel.booklore.config.security; +import com.nimbusds.jwt.JWTClaimsSet; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; @@ -25,7 +26,7 @@ import java.util.List; public class WebSocketAuthInterceptor implements ChannelInterceptor { private final JwtUtils jwtUtils; - private final OidcTokenValidator oidcTokenValidator; + private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; @Override public Message preSend(Message message, MessageChannel channel) { @@ -55,15 +56,19 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor { } private Authentication authenticateToken(String token) { - if (jwtUtils.validateToken(token)) { - String username = jwtUtils.extractUsername(token); - return new UsernamePasswordAuthenticationToken( - username, - null, - Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) - ); + try { + if (jwtUtils.validateToken(token)) { + String username = jwtUtils.extractUsername(token); + return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); + } + JWTClaimsSet claims = dynamicOidcJwtProcessor.getProcessor().process(token, null); + if (claims != null) { + String username = claims.getSubject(); + return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); + } + } catch (Exception e) { + log.error("Token authentication failed", e); } - - return oidcTokenValidator.validate(token); + return null; } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java index 2c0555665..ca230398c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/custom/BookLoreUserTransformer.java @@ -11,6 +11,7 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import java.util.Collections; import java.util.stream.Collectors; @Slf4j @@ -72,7 +73,15 @@ public class BookLoreUserTransformer { } bookLoreUser.setUserSettings(userSettings); - bookLoreUser.setAssignedLibraries(userEntity.getLibraries().stream().map(libraryMapper::toLibrary).collect(Collectors.toList())); + if (userEntity.getLibraries() != null) { + bookLoreUser.setAssignedLibraries( + userEntity.getLibraries().stream() + .map(libraryMapper::toLibrary) + .collect(Collectors.toList()) + ); + } else { + bookLoreUser.setAssignedLibraries(Collections.emptyList()); + } bookLoreUser.setProvisioningMethod(userEntity.getProvisioningMethod()); return bookLoreUser; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/OidcProviderDetails.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/OidcProviderDetails.java index 142368d05..5c84be764 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/OidcProviderDetails.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/OidcProviderDetails.java @@ -7,7 +7,6 @@ public class OidcProviderDetails { private String providerName; private String clientId; private String issuerUri; - private String jwksUrl; private ClaimMapping claimMapping; @Data diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultSettingInitializer.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultSettingInitializer.java index 3a340d7ff..bac2602f7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultSettingInitializer.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultSettingInitializer.java @@ -44,8 +44,7 @@ public class DefaultSettingInitializer { } private void addSettingIfMissing(BookLoreUserEntity user, UserSettingKey key, Object value) { - boolean exists = user.getSettings().stream() - .anyMatch(s -> s.getSettingKey().equals(key.getDbKey())); + boolean exists = user.getSettings().stream().anyMatch(s -> s.getSettingKey().equals(key.getDbKey())); if (!exists) { try { String serializedValue = key.isJson() diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserDefaultsService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserDefaultsService.java index 7e8cdaa8a..d2c127bd6 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserDefaultsService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/UserDefaultsService.java @@ -37,11 +37,14 @@ public class UserDefaultsService { private void add(BookLoreUserEntity user, UserSettingKey key, Object value) { try { - String json = objectMapper.writeValueAsString(value); + String storedValue = key.isJson() + ? objectMapper.writeValueAsString(value) + : value.toString(); + user.getSettings().add(UserSettingEntity.builder() .user(user) .settingKey(key.getDbKey()) - .settingValue(json) + .settingValue(storedValue) .build()); } catch (Exception e) { log.error("Error serializing setting {} for user {}", key, user.getUsername(), e); diff --git a/booklore-ui/src/app/app.component.html b/booklore-ui/src/app/app.component.html index b899f0920..4a654f4bb 100644 --- a/booklore-ui/src/app/app.component.html +++ b/booklore-ui/src/app/app.component.html @@ -1,3 +1,14 @@ - - - +@if (loading) { +
+
+ +

Loading Bookloreโ€ฆ

+

Please wait while we get things ready.

+
+
+
+} @else { + + + +} diff --git a/booklore-ui/src/app/app.component.scss b/booklore-ui/src/app/app.component.scss index e69de29bb..397661ebe 100644 --- a/booklore-ui/src/app/app.component.scss +++ b/booklore-ui/src/app/app.component.scss @@ -0,0 +1,49 @@ +.splash-screen { + display: flex; + align-items: center; + justify-content: center; + height: 100dvh; + background-color: #0e0e10; + color: #e5e5e5; + text-align: center; +} + +.splash-content { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; +} + +.logo { + width: 64px; + height: 64px; + opacity: 0.9; +} + +h1 { + font-size: 1.8rem; + margin: 0; +} + +p { + font-size: 1rem; + color: #a0a0a0; + margin: 0; +} + +.loader { + width: 40px; + height: 40px; + border: 4px solid #818cf8; + border-top: 4px solid transparent; + border-radius: 50%; + animation: spin 1s linear infinite; + margin-top: 1rem; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index 2593ae9af..8d8e6467e 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -7,6 +7,7 @@ import {parseLogNotification} from './shared/websocket/model/log-notification.mo import {ConfirmDialog} from 'primeng/confirmdialog'; import {Toast} from 'primeng/toast'; import {RouterOutlet} from '@angular/router'; +import {AuthInitializationService} from './auth-initialization-service'; @Component({ selector: 'app-root', @@ -17,12 +18,18 @@ import {RouterOutlet} from '@angular/router'; }) export class AppComponent implements OnInit { + loading = true; + private authInit = inject(AuthInitializationService); private bookService = inject(BookService); private rxStompService = inject(RxStompService); private eventService = inject(EventService); ngOnInit(): void { + this.authInit.initialized$.subscribe(ready => { + this.loading = !ready; + }); + this.rxStompService.watch('/topic/book-add').subscribe((message: Message) => { this.bookService.handleNewlyCreatedBook(JSON.parse(message.body)); }); diff --git a/booklore-ui/src/app/auth-initialization-service.ts b/booklore-ui/src/app/auth-initialization-service.ts new file mode 100644 index 000000000..829ff7f58 --- /dev/null +++ b/booklore-ui/src/app/auth-initialization-service.ts @@ -0,0 +1,12 @@ +import {Injectable} from '@angular/core'; +import {BehaviorSubject} from 'rxjs'; + +@Injectable({ providedIn: 'root' }) +export class AuthInitializationService { + private initialized = new BehaviorSubject(false); + initialized$ = this.initialized.asObservable(); + + markAsInitialized() { + this.initialized.next(true); + } +} diff --git a/booklore-ui/src/app/auth-initializer.ts b/booklore-ui/src/app/auth-initializer.ts index ec0671a40..2b6186c71 100644 --- a/booklore-ui/src/app/auth-initializer.ts +++ b/booklore-ui/src/app/auth-initializer.ts @@ -4,6 +4,7 @@ import {OAuthEvent, OAuthService} from 'angular-oauth2-oidc'; import {AppSettingsService} from './core/service/app-settings.service'; import {AuthService, websocketInitializer} from './core/service/auth.service'; import {filter} from 'rxjs/operators'; +import {AuthInitializationService} from './auth-initialization-service'; export function initializeAuthFactory() { return () => { @@ -11,12 +12,14 @@ export function initializeAuthFactory() { const appSettingsService = inject(AppSettingsService); const authService = inject(AuthService); const router = inject(Router); + const authInitService = inject(AuthInitializationService); return new Promise((resolve) => { const sub = appSettingsService.appSettings$.subscribe(settings => { if (settings) { if (settings.oidcEnabled && settings.oidcProviderDetails) { const details = settings.oidcProviderDetails; + oauthService.configure({ issuer: details.issuerUri, clientId: details.clientId, @@ -24,27 +27,28 @@ export function initializeAuthFactory() { redirectUri: window.location.origin + '/oauth2-callback', responseType: 'code', showDebugInformation: false, - requireHttps: true, + requireHttps: false, strictDiscoveryDocumentValidation: false, }); - oauthService.events - .pipe(filter((e: OAuthEvent) => - e.type === 'token_received' || e.type === 'token_refreshed' - )) - .subscribe((e: OAuthEvent) => { - const accessToken = oauthService.getAccessToken(); - const refreshToken = oauthService.getRefreshToken(); - authService.saveOidcTokens(accessToken, refreshToken ?? ''); - }); - oauthService.loadDiscoveryDocumentAndTryLogin() .then(() => { - oauthService.setupAutomaticSilentRefresh(); - websocketInitializer(authService); - resolve(); + console.log('[OIDC] Discovery document loaded and login attempted'); + if (oauthService.hasValidAccessToken()) { + console.log('[OIDC] Valid access token found after tryLogin'); + router.navigate(['/dashboard']); + oauthService.setupAutomaticSilentRefresh(); + websocketInitializer(authService); + authInitService.markAsInitialized(); + resolve(); + } else { + console.log('[OIDC] No valid access token found, attempting silent login with prompt=none'); + oauthService.initCodeFlow(); + resolve(); + } }) .catch(err => { + authInitService.markAsInitialized(); console.error( 'OIDC initialization failed: Unable to complete OpenID Connect discovery or login. ' + 'This may be due to an incorrect issuer URL, client ID, or network issue. ' + @@ -60,6 +64,7 @@ export function initializeAuthFactory() { error: resolve }); } else { + authInitService.markAsInitialized(); resolve(); } sub.unsubscribe(); diff --git a/booklore-ui/src/app/auth.guard.ts b/booklore-ui/src/app/auth.guard.ts index 0622f6d2c..d5bd09f40 100644 --- a/booklore-ui/src/app/auth.guard.ts +++ b/booklore-ui/src/app/auth.guard.ts @@ -1,32 +1,32 @@ import { inject } from '@angular/core'; import { CanActivateFn } from '@angular/router'; import { Router } from '@angular/router'; -import { OAuthService } from 'angular-oauth2-oidc'; +import {AuthService} from './core/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 legacyToken = localStorage.getItem('accessToken_Internal'); + const internalAccessToken = authService.getInternalAccessToken(); - if (legacyToken) { + if (internalAccessToken) { try { - const payload = JSON.parse(atob(legacyToken.split('.')[1])); + const payload = JSON.parse(atob(internalAccessToken.split('.')[1])); if (payload.isDefaultPassword) { router.navigate(['/change-password']); return false; } return true; } catch (e) { - console.error('Invalid legacy token:', e); - localStorage.removeItem('accessToken'); + localStorage.removeItem('accessToken_Internal'); router.navigate(['/login']); return false; } } - const oidcToken = localStorage.getItem('accessToken_OIDC'); - - if (oidcToken) { + if (oauthService.hasValidAccessToken()) { return true; } diff --git a/booklore-ui/src/app/core/component/login/login.component.ts b/booklore-ui/src/app/core/component/login/login.component.ts index f415e0d30..eb5ee279d 100644 --- a/booklore-ui/src/app/core/component/login/login.component.ts +++ b/booklore-ui/src/app/core/component/login/login.component.ts @@ -77,6 +77,6 @@ export class LoginComponent implements OnInit { } loginWithOidc(): void { - this.oAuthService.initImplicitFlow(); + this.oAuthService.initCodeFlow(); } } diff --git a/booklore-ui/src/app/core/model/app-settings.model.ts b/booklore-ui/src/app/core/model/app-settings.model.ts index be6832e36..de5a792c3 100644 --- a/booklore-ui/src/app/core/model/app-settings.model.ts +++ b/booklore-ui/src/app/core/model/app-settings.model.ts @@ -28,7 +28,6 @@ export interface OidcProviderDetails { providerName: string; clientId: string; issuerUri: string; - jwksUrl: string; claimMapping: { username: string; email: string; diff --git a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html index f6fbfb66e..47d3cbd7b 100644 --- a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html +++ b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.html @@ -79,16 +79,7 @@ pInputText id="issuerUri" [(ngModel)]="oidcProvider.issuerUri" - placeholder="e.g. https://authentik.your-domain.com/application/o/booklore/" - class="w-full"/> -
-
- -
@@ -150,7 +141,7 @@ + (onChange)="saveOidcAutoProvisionSettings()">
@@ -193,7 +184,7 @@
- +
} diff --git a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.ts b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.ts index 38ec1aac4..71eb467c6 100644 --- a/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.ts +++ b/booklore-ui/src/app/core/security/oauth2-management/authentication-settings.component.ts @@ -30,7 +30,7 @@ import {LibraryService} from '../../../book/service/library.service'; Button, MultiSelect, ReactiveFormsModule -], + ], styleUrls: ['./authentication-settings.component.scss'] }) export class AuthenticationSettingsComponent implements OnInit { @@ -52,7 +52,6 @@ export class AuthenticationSettingsComponent implements OnInit { providerName: '', clientId: '', issuerUri: '', - jwksUrl: '', claimMapping: { username: '', email: '', @@ -98,7 +97,6 @@ export class AuthenticationSettingsComponent implements OnInit { providerName: settings.oidcProviderDetails?.providerName || '', clientId: settings.oidcProviderDetails?.clientId || '', issuerUri: settings.oidcProviderDetails?.issuerUri || '', - jwksUrl: settings.oidcProviderDetails?.jwksUrl || '', claimMapping: settings.oidcProviderDetails?.claimMapping || defaultClaimMapping }; @@ -112,51 +110,6 @@ export class AuthenticationSettingsComponent implements OnInit { return !!(p.providerName && p.clientId && p.issuerUri && p.claimMapping.name && p.claimMapping.email && p.claimMapping.username); } - saveAutoProvision(): void { - const payload = [ - {key: 'auto_provision_oidc_users', newValue: this.autoUserProvisioningEnabled} - ]; - this.appSettingsService.saveSettings(payload).subscribe({ - next: () => this.messageService.add({ - severity: 'success', - summary: 'Saved', - detail: 'Auto-provision setting saved.' - }), - error: () => this.messageService.add({ - severity: 'error', - summary: 'Error', - detail: 'Failed to save auto-provision setting.' - }) - }); - } - - onPermissionToggle(): void { - this.selectedPermissions = [ - 'permissionRead', - ...this.availablePermissions.filter(p => p.selected).map(p => p.value) - ]; - - const payload = [ - { - key: 'default_oidc_user_permissions', - newValue: this.selectedPermissions - } - ]; - - this.appSettingsService.saveSettings(payload).subscribe({ - next: () => this.messageService.add({ - severity: 'success', - summary: 'Saved', - detail: 'Default permissions updated.' - }), - error: () => this.messageService.add({ - severity: 'error', - summary: 'Error', - detail: 'Failed to update default permissions.' - }) - }); - } - toggleOidcEnabled(): void { if (!this.isOidcFormComplete()) return; const payload = [ @@ -200,8 +153,7 @@ export class AuthenticationSettingsComponent implements OnInit { }); } - - saveAutoProvisioningSettings(): void { + saveOidcAutoProvisionSettings(): void { const provisionDetails = { enableAutoProvisioning: this.autoUserProvisioningEnabled, defaultPermissions: [ diff --git a/booklore-ui/src/app/core/security/oidc-callback/oidc-callback.component.ts b/booklore-ui/src/app/core/security/oidc-callback/oidc-callback.component.ts index 4b9f6b85b..957c81313 100644 --- a/booklore-ui/src/app/core/security/oidc-callback/oidc-callback.component.ts +++ b/booklore-ui/src/app/core/security/oidc-callback/oidc-callback.component.ts @@ -15,21 +15,22 @@ export class OidcCallbackComponent implements OnInit { private authService = inject(AuthService); ngOnInit(): void { - this.oAuthService.loadDiscoveryDocumentAndTryLogin().then(() => { + /*this.oAuthService.tryLoginCodeFlow().then(info => { if (this.oAuthService.hasValidAccessToken()) { - this.authService.saveOidcTokens( - this.oAuthService.getAccessToken(), - this.oAuthService.getRefreshToken() - ); + const accessToken = this.oAuthService.getAccessToken(); + const refreshToken = this.oAuthService.getRefreshToken(); + this.authService.saveOidcTokens(accessToken, refreshToken ?? ''); + this.authService.getRxStompService().activate(); + this.oAuthService.setupAutomaticSilentRefresh(); this.router.navigate(['/dashboard']); } else { - console.error('Login failed or no valid tokens'); + console.error('OIDC code exchange failed'); this.router.navigate(['/login']); } }).catch(err => { - console.error('OIDC error during login:', err); + console.error('OIDC error:', err); this.router.navigate(['/login']); - }); + });*/ } } diff --git a/booklore-ui/src/app/core/service/app-config.service.ts b/booklore-ui/src/app/core/service/app-config.service.ts index d93ce55e7..e3d6e95e5 100644 --- a/booklore-ui/src/app/core/service/app-config.service.ts +++ b/booklore-ui/src/app/core/service/app-config.service.ts @@ -39,7 +39,7 @@ export class AppConfigService { return { preset: 'Aura', primary: 'green', - surface: 'viva', + surface: 'neutral', }; } diff --git a/booklore-ui/src/app/core/service/auth.service.ts b/booklore-ui/src/app/core/service/auth.service.ts index 46d9e0c01..fd23eb219 100644 --- a/booklore-ui/src/app/core/service/auth.service.ts +++ b/booklore-ui/src/app/core/service/auth.service.ts @@ -4,6 +4,9 @@ import {Observable, tap} from 'rxjs'; import {RxStompService} from '../../shared/websocket/rx-stomp.service'; import {API_CONFIG} from '../../config/api-config'; import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config'; +import {OAuthService} from 'angular-oauth2-oidc'; +import {AppSettingsService} from './app-settings.service'; +import {Router} from '@angular/router'; @Injectable({ providedIn: 'root', @@ -15,6 +18,8 @@ export class AuthService { private http = inject(HttpClient); private injector = inject(Injector); + private oAuthService = inject(OAuthService); + private router = inject(Router); internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> { return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe( @@ -54,17 +59,12 @@ export class AuthService { localStorage.setItem('refreshToken_Internal', refreshToken); } - saveOidcTokens(accessToken: string, refreshToken: string): void { - localStorage.setItem('accessToken_OIDC', accessToken); - localStorage.setItem('refreshToken_OIDC', refreshToken); - } - getInternalAccessToken(): string | null { return localStorage.getItem('accessToken_Internal'); } getOidcAccessToken(): string | null { - return localStorage.getItem('accessToken_OIDC'); + return this.oAuthService.getIdToken(); } getInternalRefreshToken(): string | null { @@ -74,9 +74,12 @@ export class AuthService { logout(): void { localStorage.removeItem('accessToken_Internal'); localStorage.removeItem('refreshToken_Internal'); - localStorage.removeItem('accessToken_OIDC'); - localStorage.removeItem('refreshToken_OIDC'); this.getRxStompService().deactivate(); + if (this.oAuthService.clientId) { + this.oAuthService.logOut(); + } else { + this.router.navigate(['/login']); + } } getRxStompService(): RxStompService { diff --git a/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts b/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts index e41ca5359..c507437e8 100644 --- a/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts +++ b/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts @@ -133,6 +133,5 @@ export class AppTopBarComponent implements OnDestroy { logout() { this.authService.logout(); - window.location.href = '/login'; } } From 6e48419dc740c0d2b5d2a227ad5e482f5ce0c68e Mon Sep 17 00:00:00 2001 From: danblu3 Date: Sun, 29 Jun 2025 21:26:56 +0000 Subject: [PATCH 5/7] Updating docs to be compat with booklore --- docs/OIDC-Setup-With-PocketID.md | 56 ++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 docs/OIDC-Setup-With-PocketID.md diff --git a/docs/OIDC-Setup-With-PocketID.md b/docs/OIDC-Setup-With-PocketID.md new file mode 100644 index 000000000..865a7e0d9 --- /dev/null +++ b/docs/OIDC-Setup-With-PocketID.md @@ -0,0 +1,56 @@ +# OIDC Setup With Pocket ID + +## A quick rundown of the technologies + +### What is Pocket ID? + +Pocket ID is a simple OIDC provider that allows users to authenticate with their passkeys to your services. + +The goal of Pocket ID is to be a simple and easy-to-use. There are other self-hosted OIDC providers like Keycloak or ORY Hydra but they are often too complex for simple use cases. + +Additionally, what makes Pocket ID special is that it only supports passkey authentication, which means you donโ€™t need a password. + +### What is OAuth2? + +OAuth2 (Open Authorization 2.0) is an industry-standard protocol for authorization. It allows applications (clients) to gain limited access to user accounts on an HTTP service without sharing the userโ€™s credentials. Instead, it uses access tokens to facilitate secure interactions. OAuth2 is commonly used in scenarios where users need to authenticate via a third-party service. + +### What is OpenID Connect (OIDC)? + +OIDC (OpenID Connect) is an identity layer built on top of OAuth2. While OAuth2 primarily handles authorization, OIDC adds authentication, enabling applications to verify a userโ€™s identity and obtain profile information. This makes OIDC suitable for SSO solutions, where user identity is central to access management. + +## Setting up a client in Pocket ID + +### Step 1: Install and Configure Pocket ID + +Before setting up the OIDC client, ensure that Pocket ID is installed and running by following the [setup guide](https://github.com/stonith404/pocket-id#setup). + +### Step 2: Add a client + +Once you have logged in and configured a PassKey you now need to create an OIDC client, this will let Pocket ID know about the application that needs to be configured, and will give you the relevant keys to add to the Booklore settings dialogue + +- Login to PocketID +- Go to OIDC Clients on the left side bar +- Click Add OIDC Client + - Name: Booklore [Can be anything you want] + - Callback URLs: `https://{host}/oauth2-callback` +- Tick Public & PKCE (This is required for Booklore to correctly authenticate with the client) +- Copy your Client ID to use later. +- Click show more details and copy the Certificate URL to use later +- Click Save + + +### Step 3: Configure Booklore OIDC Settings + +To enable OIDC authentication in Booklore, you need to set the following within the application: + +- Navigate to the settings cog at the top of the page +- Providername - PocketID +- Client ID - Copied in Step 2 +- Issuer URI - This is the URL where your MAIN page of PocketID is (id.host.com for example) +- JWKS URL - Copied in step 2 +- Leave the rest default +- Click Save + +### Step 4: Test the Integration + +Once configured, simply click Save Settings and then click the Enabled radio button to activate it. Simply log out and log back in and you should be working with no issues! Any issues please raise an issue on the [Github](https://github.com/adityachandelgit/BookLore/issues/new) From 5f72c9a01fccdecf9b3ca2c9a304dc9416dea6e5 Mon Sep 17 00:00:00 2001 From: danblu3 Date: Sun, 29 Jun 2025 21:31:43 +0000 Subject: [PATCH 6/7] Updating naming to BookLore and some formatting --- docs/OIDC-Setup-With-PocketID.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/OIDC-Setup-With-PocketID.md b/docs/OIDC-Setup-With-PocketID.md index 865a7e0d9..e4256ee7c 100644 --- a/docs/OIDC-Setup-With-PocketID.md +++ b/docs/OIDC-Setup-With-PocketID.md @@ -26,25 +26,25 @@ Before setting up the OIDC client, ensure that Pocket ID is installed and runnin ### Step 2: Add a client -Once you have logged in and configured a PassKey you now need to create an OIDC client, this will let Pocket ID know about the application that needs to be configured, and will give you the relevant keys to add to the Booklore settings dialogue +Once you have logged in and configured a PassKey you now need to create an OIDC client, this will let Pocket ID know about the application that needs to be configured, and will give you the relevant keys to add to the BookLore settings dialogue - Login to PocketID - Go to OIDC Clients on the left side bar - Click Add OIDC Client - - Name: Booklore [Can be anything you want] + - Name: BookLore [Can be anything you want] - Callback URLs: `https://{host}/oauth2-callback` -- Tick Public & PKCE (This is required for Booklore to correctly authenticate with the client) +- Tick Public & PKCE (This is required for BookLore to correctly authenticate with the client) - Copy your Client ID to use later. - Click show more details and copy the Certificate URL to use later - Click Save -### Step 3: Configure Booklore OIDC Settings +### Step 3: Configure BookLore OIDC Settings -To enable OIDC authentication in Booklore, you need to set the following within the application: +To enable OIDC authentication in BookLore, you need to set the following within the application: - Navigate to the settings cog at the top of the page -- Providername - PocketID +- Provider name - PocketID - Client ID - Copied in Step 2 - Issuer URI - This is the URL where your MAIN page of PocketID is (id.host.com for example) - JWKS URL - Copied in step 2 From 9b1eb4238135b9419b43835c7f6e7e171088e9b0 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" Date: Sun, 29 Jun 2025 16:19:51 -0600 Subject: [PATCH 7/7] Update OIDC documentation --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 39d622772..9171d663c 100644 --- a/README.md +++ b/README.md @@ -104,16 +104,17 @@ Once the containers are up, access BookLore in your browser at: http://localhost:6060 ``` -## ๐Ÿ”‘ OIDC/OAuth2 Authentication +## ๐Ÿ”‘ OIDC/OAuth2 Authentication (Authentik, Pocket ID, etc.) -> **Note:** This is an experimental feature and may not be fully stable BookLore supports optional OIDC/OAuth2 authentication for secure access. This feature allows you to integrate external authentication providers for a seamless login experience. -While the integration has been tested with **Authentik**, it should work with other OIDC providers like **Authelia** as well. The setup allows you to use either JWT-based local authentication or external providers, giving users the flexibility to choose their preferred method. +While the integration has been tested with **Authentik** and **Pocket ID**, it should work with other OIDC providers like **Authelia** as well. The setup allows you to use either JWT-based local authentication or external providers, giving users the flexibility to choose their preferred method. -For detailed instructions on setting up OIDC authentication with **Authentik**, refer to the [YouTube guide on configuring OIDC in BookLore](https://www.youtube.com/watch?v=r6Ufh9ldF9M), which provides step-by-step walkthroughs. +For detailed instructions on setting up OIDC authentication: +- ๐Ÿ“บ [YouTube video on configuring Authentik with BookLore](https://www.youtube.com/watch?v=r6Ufh9ldF9M) +- ๐Ÿ“˜ [Step-by-step setup guide for Pocket ID](docs/OIDC-Setup-With-PocketID.md) ## ๐Ÿ” Remote Authentication (Trusted Header SSO, Forward Auth)