Merge pull request #622 from adityachandelgit/develop

Merge Develop into Master for release
This commit is contained in:
Aditya Chandel
2025-06-29 16:21:01 -06:00
committed by GitHub
28 changed files with 428 additions and 281 deletions
+7 -6
View File
@@ -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.
@@ -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)
@@ -145,7 +146,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
@@ -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<String, Object> 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<String> 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<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever, jwkSetCache);
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
JWSKeySelector<SecurityContext> 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<BookLoreUserEntity> 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<GrantedAuthority> authorities = getAuthorities(entity.getPermissions());
@@ -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<SecurityContext> jwtProcessor;
private volatile String currentIssuerUri;
public synchronized ConfigurableJWTProcessor<SecurityContext> 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<SecurityContext> 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<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksUrl, resourceRetriever, jwkSetCache);
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
ConfigurableJWTProcessor<SecurityContext> 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<java.util.Map<String, Object>>() {});
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);
}
}
@@ -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<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever);
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
JWSKeySelector<SecurityContext> 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;
}
}
}
@@ -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;
}
}
@@ -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;
}
@@ -7,7 +7,6 @@ public class OidcProviderDetails {
private String providerName;
private String clientId;
private String issuerUri;
private String jwksUrl;
private ClaimMapping claimMapping;
@Data
@@ -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()
@@ -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);
+14 -3
View File
@@ -1,3 +1,14 @@
<p-confirmDialog />
<p-toast></p-toast>
<router-outlet></router-outlet>
@if (loading) {
<div class="splash-screen">
<div class="splash-content">
<img src="assets/favicon.svg" alt="Booklore logo" class="logo" />
<h1>Loading Booklore…</h1>
<p>Please wait while we get things ready.</p>
<div class="loader"></div>
</div>
</div>
} @else {
<p-confirmDialog />
<p-toast></p-toast>
<router-outlet></router-outlet>
}
+49
View File
@@ -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);
}
}
+7
View File
@@ -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));
});
@@ -0,0 +1,12 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthInitializationService {
private initialized = new BehaviorSubject<boolean>(false);
initialized$ = this.initialized.asObservable();
markAsInitialized() {
this.initialized.next(true);
}
}
+19 -14
View File
@@ -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<void>((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();
+9 -9
View File
@@ -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;
}
@@ -29,8 +29,13 @@
<div class="pl-6 flex flex-col">
<div class="flex flex-row items-center justify-between">
<div>
@if (book?.metadata!.seriesName) {
<p class="italic">{{ book?.metadata!.seriesName }} #{{ book?.metadata!.seriesNumber }}</p>
@if (book?.metadata?.seriesName) {
<p class="underline hover:opacity-80 cursor-pointer" (click)="goToSeries(book?.metadata?.seriesName!)">
{{ book?.metadata?.seriesName }}
@if (book?.metadata?.seriesNumber) {
#{{ book?.metadata?.seriesNumber }}
}
</p>
}
<div class="flex items-center gap-2">
<p class="text-2xl font-bold m-0">{{ book?.metadata!.title }}</p>
@@ -163,7 +168,16 @@
<p-menu #menu [popup]="true" [model]="readStatusMenuItems"></p-menu>
</p>
</div>
<p class="whitespace-nowrap max-w-[250px] overflow-hidden text-ellipsis"><span class="font-bold">Publisher:</span> {{ book?.metadata!.publisher || '-' }}</p>
<p class="whitespace-nowrap max-w-[250px] overflow-hidden text-ellipsis">
<span class="font-bold">Publisher: </span>
@if (book?.metadata?.publisher) {
<span class="underline hover:opacity-80 cursor-pointer" (click)="goToPublisher(book?.metadata?.publisher!)">
{{ book?.metadata?.publisher }}
</span>
} @else {
<span>-</span>
}
</p>
<p class="whitespace-nowrap"><span class="font-bold">Published:</span> {{ book?.metadata!.publishedDate || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ book?.metadata!.language || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ book?.metadata!.isbn10 || '-' }}</p>
@@ -311,12 +325,12 @@
@if (book.metadata!.description && book.metadata!.description.length > 100) {
<div class="text-left">
<button pButton
type="button"
[label]="isExpanded ? 'Show less' : 'Show more'"
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
iconPos="right"
class="p-button-text p-button-sm"
(click)="toggleExpand()">
type="button"
[label]="isExpanded ? 'Show less' : 'Show more'"
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
iconPos="right"
class="p-button-text p-button-sm"
(click)="toggleExpand()">
</button>
</div>
}
@@ -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';
@@ -77,6 +77,6 @@ export class LoginComponent implements OnInit {
}
loginWithOidc(): void {
this.oAuthService.initImplicitFlow();
this.oAuthService.initCodeFlow();
}
}
@@ -28,7 +28,6 @@ export interface OidcProviderDetails {
providerName: string;
clientId: string;
issuerUri: string;
jwksUrl: string;
claimMapping: {
username: string;
email: string;
@@ -79,16 +79,7 @@
pInputText
id="issuerUri"
[(ngModel)]="oidcProvider.issuerUri"
placeholder="e.g. https://authentik.your-domain.com/application/o/booklore/"
class="w-full"/>
</div>
<div class="md:col-span-2">
<label for="jwksUrl" class="mb-1">JWKS URL</label>
<input
pInputText
id="jwksUrl"
[(ngModel)]="oidcProvider.jwksUrl"
placeholder="e.g. https://authentik.your-domain.com/application/o/booklore/jwks/"
placeholder="e.g. https://authentik.domain.com/application/o/booklore/ or https://pocket-id.domain.com"
class="w-full"/>
</div>
<div class="md:col-span-2">
@@ -150,7 +141,7 @@
<p-toggleswitch
[(ngModel)]="autoUserProvisioningEnabled"
inputId="autoProvision"
(onChange)="saveAutoProvision()">
(onChange)="saveOidcAutoProvisionSettings()">
</p-toggleswitch>
<div class="flex items-center gap-2 text-sm text-gray-400">
<i class="pi pi-info-circle text-blue-500"></i>
@@ -193,7 +184,7 @@
</p-multiSelect>
</div>
<div class="mt-8">
<p-button label="Save Settings" [outlined]="true" (click)="saveAutoProvisioningSettings()"></p-button>
<p-button label="Save Settings" [outlined]="true" (click)="saveOidcAutoProvisionSettings()"></p-button>
</div>
</div>
}
@@ -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: [
@@ -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']);
});
});*/
}
}
@@ -39,7 +39,7 @@ export class AppConfigService {
return {
preset: 'Aura',
primary: 'green',
surface: 'viva',
surface: 'neutral',
};
}
@@ -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 {
@@ -133,6 +133,5 @@ export class AppTopBarComponent implements OnDestroy {
logout() {
this.authService.logout();
window.location.href = '/login';
}
}
@@ -0,0 +1,27 @@
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class FaviconService {
private svgTemplate = (color: string) => `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 126 126" fill="currentColor">
<path d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z" fill="${color}"/>
<path d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z" fill="white"/>
</svg>
`;
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;
}
}
@@ -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<string, string>;
@@ -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<string, ColorPalette>;
const colorPalette = presetPalette[name];
return colorPalette?.[500] ?? name;
});
private readonly _faviconSyncEffect = effect(() => {
this.faviconService.updateFavicon(this.faviconColor());
});
readonly primaryColors = computed<Palette[]>(() => {
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
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});
}
}
+56
View File
@@ -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
- 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
- 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)