Implement OIDC authentication
This commit is contained in:
committed by
Aditya Chandel
parent
548e09ae2c
commit
817b572c08
@@ -35,6 +35,7 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-configuration-processor'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-mail'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
|
||||
|
||||
// --- Database & Migration ---
|
||||
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.3'
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class ApplicationStartupRunner implements CommandLineRunner {
|
||||
|
||||
private final UserCreatorService userCreatorService;
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
if (!userCreatorService.doesAdminUserExist()) {
|
||||
userCreatorService.createAdminUser();
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -8,7 +8,7 @@ import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.RefreshTokenEntity;
|
||||
import com.adityachandel.booklore.repository.RefreshTokenRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||
import com.adityachandel.booklore.service.user.UserProvisioningService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -27,7 +27,7 @@ public class AuthenticationService {
|
||||
private final AppProperties appProperties;
|
||||
private final UserRepository userRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final UserCreatorService userCreatorService;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
@@ -54,7 +54,7 @@ public class AuthenticationService {
|
||||
|
||||
Optional<BookLoreUserEntity> user = userRepository.findByUsername(username);
|
||||
if (user.isEmpty() && appProperties.getRemoteAuth().isCreateNewUsers()) {
|
||||
user = Optional.of(userCreatorService.createRemoteUser(name, username, email, groups));
|
||||
user = Optional.of(userProvisioningService.provisionRemoteUser(name, username, email, groups));
|
||||
}
|
||||
|
||||
if (user.isEmpty()) {
|
||||
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.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;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
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;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
String token = extractToken(request);
|
||||
if (token == null) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateLocalUser(token, request);
|
||||
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
authenticateOidcUser(token, request);
|
||||
} else {
|
||||
log.debug("OIDC is disabled. Skipping OIDC authentication.");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("Authentication error: {}", ex.getMessage(), ex);
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void authenticateLocalUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = BookLoreUserTransformer.toDTO(entity);
|
||||
List<GrantedAuthority> authorities = getAuthorities(entity.getPermissions());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
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));
|
||||
|
||||
BookLoreUser user = BookLoreUserTransformer.toDTO(entity);
|
||||
List<GrantedAuthority> authorities = getAuthorities(entity.getPermissions());
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("OIDC authentication failed", e);
|
||||
throw ApiError.UNAUTHORIZED.createException("OIDC JWT validation failed");
|
||||
}
|
||||
}
|
||||
|
||||
private String extractToken(HttpServletRequest request) {
|
||||
String bearer = request.getHeader("Authorization");
|
||||
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
|
||||
}
|
||||
|
||||
private List<GrantedAuthority> getAuthorities(UserPermissionsEntity permissions) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
if (permissions != null) {
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_UPLOAD", permissions.isPermissionUpload());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_DOWNLOAD", permissions.isPermissionDownload());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_EDIT_METADATA", permissions.isPermissionEditMetadata());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_MANIPULATE_LIBRARY", permissions.isPermissionManipulateLibrary());
|
||||
addAuthorityIfPermissionGranted(authorities, "ROLE_ADMIN", permissions.isPermissionAdmin());
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
|
||||
private void addAuthorityIfPermissionGranted(List<GrantedAuthority> authorities, String role, boolean permissionGranted) {
|
||||
if (permissionGranted) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-19
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@@ -11,11 +12,8 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
@@ -24,17 +22,13 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final CustomOpdsUserDetailsService customOpdsUserDetailsService;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter, CustomOpdsUserDetailsService customOpdsUserDetailsService) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.customOpdsUserDetailsService = customOpdsUserDetailsService;
|
||||
}
|
||||
private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter;
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
@@ -46,19 +40,22 @@ public class SecurityConfig {
|
||||
http
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login", "/api/v1/auth/refresh", "/api/v1/auth/remote").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll()
|
||||
.requestMatchers("/api/v1/books/*/cover").permitAll()
|
||||
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui.html").permitAll()
|
||||
.requestMatchers("/api/v1/opds/**").authenticated()
|
||||
.requestMatchers(
|
||||
"/api/v1/auth/**",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**",
|
||||
"/ws/**",
|
||||
"/api/v1/books/*/cover",
|
||||
"/api/v1/settings",
|
||||
"/api/v1/setup",
|
||||
"/api/v1/setup/**"
|
||||
).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(customizer -> {
|
||||
customizer.realmName("Booklore OPDS");
|
||||
})
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
.httpBasic(customizer -> customizer.realmName("Booklore OPDS"))
|
||||
.addFilterBefore(dualJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
+52
-6
@@ -1,5 +1,16 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.service.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.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.Ordered;
|
||||
@@ -15,16 +26,20 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Slf4j
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
|
||||
@AllArgsConstructor
|
||||
public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
@@ -54,12 +69,43 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
}
|
||||
|
||||
private Authentication authenticateToken(String token) {
|
||||
if (!jwtUtils.validateToken(token)) {
|
||||
return null;
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
return new UsernamePasswordAuthenticationToken(username, null, authorities);
|
||||
}
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
|
||||
return new UsernamePasswordAuthenticationToken(username, null, authorities);
|
||||
if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
try {
|
||||
var 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;
|
||||
}
|
||||
}
|
||||
|
||||
// If not OIDC-enabled, return null (or could throw an error depending on the requirement)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -6,7 +6,7 @@ import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.RefreshTokenRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||
import com.adityachandel.booklore.service.user.UserProvisioningService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -24,13 +24,13 @@ import java.util.Map;
|
||||
public class AuthenticationController {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final UserCreatorService userCreatorService;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@PostMapping("/register")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> registerUser(@RequestBody @Valid UserCreateRequest userCreateRequest) {
|
||||
userCreatorService.registerUser(userCreateRequest);
|
||||
userProvisioningService.provisionInternalUser(userCreateRequest);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.exception.ErrorResponse;
|
||||
import com.adityachandel.booklore.model.dto.request.InitialUserRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.SuccessResponse;
|
||||
import com.adityachandel.booklore.service.user.UserProvisioningService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/setup")
|
||||
@RequiredArgsConstructor
|
||||
public class SetupController {
|
||||
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
|
||||
@GetMapping("/status")
|
||||
public ResponseEntity<?> getSetupStatus() {
|
||||
boolean isCompleted = userProvisioningService.isInitialUserAlreadyProvisioned();
|
||||
String message = isCompleted
|
||||
? "Initial setup has already been completed."
|
||||
: "Initial setup is pending. No users have been created yet.";
|
||||
return ResponseEntity.ok(new SuccessResponse<>(200, message, isCompleted));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> setupFirstUser(@RequestBody InitialUserRequest request) {
|
||||
if (userProvisioningService.isInitialUserAlreadyProvisioned()) {
|
||||
return ResponseEntity.status(403).body(new ErrorResponse(403, "Setup is disabled after the first user is created."));
|
||||
}
|
||||
userProvisioningService.provisionInitialUser(request);
|
||||
return ResponseEntity.ok(new SuccessResponse<>(200, "Admin user created successfully."));
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.adityachandel.booklore.mapper.custom;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
|
||||
public class BookLoreUserTransformer {
|
||||
|
||||
public static BookLoreUser toDTO(BookLoreUserEntity userEntity) {
|
||||
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
|
||||
permissions.setAdmin(userEntity.getPermissions().isPermissionAdmin());
|
||||
permissions.setCanUpload(userEntity.getPermissions().isPermissionUpload());
|
||||
permissions.setCanDownload(userEntity.getPermissions().isPermissionDownload());
|
||||
permissions.setCanEditMetadata(userEntity.getPermissions().isPermissionEditMetadata());
|
||||
permissions.setCanEmailBook(userEntity.getPermissions().isPermissionEmailBook());
|
||||
permissions.setCanManipulateLibrary(userEntity.getPermissions().isPermissionManipulateLibrary());
|
||||
|
||||
BookLoreUser bookLoreUser = new BookLoreUser();
|
||||
bookLoreUser.setId(userEntity.getId());
|
||||
bookLoreUser.setUsername(userEntity.getUsername());
|
||||
bookLoreUser.setName(userEntity.getName());
|
||||
bookLoreUser.setEmail(userEntity.getEmail());
|
||||
bookLoreUser.setDefaultPassword(userEntity.isDefaultPassword());
|
||||
bookLoreUser.setPermissions(permissions);
|
||||
bookLoreUser.setBookPreferences(userEntity.getBookPreferences());
|
||||
|
||||
return bookLoreUser;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
@@ -12,6 +13,7 @@ public class BookLoreUser {
|
||||
private boolean isDefaultPassword;
|
||||
private String name;
|
||||
private String email;
|
||||
private ProvisioningMethod provisioningMethod;
|
||||
private List<Library> assignedLibraries;
|
||||
private UserPermissions permissions;
|
||||
private BookPreferences bookPreferences;
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class InitialUserRequest {
|
||||
@NotBlank
|
||||
private String username;
|
||||
|
||||
@Email
|
||||
@NotBlank
|
||||
private String email;
|
||||
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
private String password;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class SuccessResponse<T> {
|
||||
|
||||
private final int status;
|
||||
private final String message;
|
||||
private final T data;
|
||||
private final LocalDateTime timestamp;
|
||||
|
||||
public SuccessResponse(int status, String message, T data) {
|
||||
this.status = status;
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
this.timestamp = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public SuccessResponse(int status, String message) {
|
||||
this(status, message, null);
|
||||
}
|
||||
}
|
||||
+6
@@ -6,6 +6,8 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@@ -17,4 +19,8 @@ public class AppSettings {
|
||||
private boolean similarBookRecommendation;
|
||||
private boolean opdsServerEnabled;
|
||||
private String uploadPattern;
|
||||
|
||||
private boolean oidcEnabled;
|
||||
private OidcProviderDetails oidcProviderDetails;
|
||||
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.adityachandel.booklore.model.dto.settings;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class OidcAutoProvisionDetails {
|
||||
private boolean enableAutoProvisioning;
|
||||
private List<String> defaultPermissions;
|
||||
private List<Long> defaultLibraryIds;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.model.dto.settings;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class OidcProviderDetails {
|
||||
private String providerName;
|
||||
private String clientId;
|
||||
private String issuerUri;
|
||||
private String jwksUrl;
|
||||
private ClaimMapping claimMapping;
|
||||
|
||||
@Data
|
||||
public static class ClaimMapping {
|
||||
private String username;
|
||||
private String name;
|
||||
private String email;
|
||||
}
|
||||
}
|
||||
+5
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.convertor.BookPreferencesConverter;
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -38,6 +39,10 @@ public class BookLoreUserEntity {
|
||||
@Column(unique = true)
|
||||
private String email;
|
||||
|
||||
@Column(name = "provisioning_method")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private ProvisioningMethod provisioningMethod;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum ProvisioningMethod {
|
||||
LOCAL, OIDC, REMOTE
|
||||
}
|
||||
+49
-16
@@ -2,15 +2,17 @@ package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.model.entity.AppSettingEntity;
|
||||
import com.adityachandel.booklore.repository.AppSettingsRepository;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -28,6 +30,9 @@ public class AppSettingService {
|
||||
public static final String SIMILAR_BOOK_RECOMMENDATION = "similar_book_recommendation";
|
||||
public static final String UPLOAD_FILE_PATTERN = "upload_file_pattern";
|
||||
public static final String OPDS_SERVER_ENABLED = "opds_server_enabled";
|
||||
public static final String OIDC_ENABLED = "oidc_enabled";
|
||||
public static final String OIDC_PROVIDER_DETAILS = "oidc_provider_details";
|
||||
public static final String OIDC_AUTO_PROVISION_DETAILS = "oidc_auto_provision_details";
|
||||
|
||||
private volatile AppSettings appSettings;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
@@ -50,10 +55,11 @@ public class AppSettingService {
|
||||
public void updateSetting(String name, Object val) throws JsonProcessingException {
|
||||
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
||||
if (setting == null) {
|
||||
throw new IllegalArgumentException("Setting not found for name: " + name);
|
||||
setting = new AppSettingEntity();
|
||||
setting.setName(name);
|
||||
}
|
||||
|
||||
if (QUICK_BOOK_MATCH.equals(name)) {
|
||||
if (QUICK_BOOK_MATCH.equals(name) || OIDC_PROVIDER_DETAILS.equals(name) || OIDC_AUTO_PROVISION_DETAILS.equals(name)) {
|
||||
setting.setVal(objectMapper.writeValueAsString(val));
|
||||
} else {
|
||||
setting.setVal(val.toString());
|
||||
@@ -66,43 +72,70 @@ public class AppSettingService {
|
||||
private void refreshCache() {
|
||||
lock.lock();
|
||||
try {
|
||||
this.appSettings = buildAppSettings();
|
||||
appSettings = buildAppSettings();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private AppSettings buildAppSettings() {
|
||||
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
||||
Map<String, String> settingsMap = settings.stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
||||
Map<String, String> settingsMap = appSettingsRepository.findAll().stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
||||
|
||||
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
|
||||
|
||||
if (settingsMap.containsKey(QUICK_BOOK_MATCH)) {
|
||||
try {
|
||||
MetadataRefreshOptions options = objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class);
|
||||
builder.metadataRefreshOptions(options);
|
||||
builder.metadataRefreshOptions(objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse setting: " + QUICK_BOOK_MATCH, e);
|
||||
throw new RuntimeException("Failed to parse " + QUICK_BOOK_MATCH, e);
|
||||
}
|
||||
}
|
||||
|
||||
String oidcProviderDetailsJson = settingsMap.get(OIDC_PROVIDER_DETAILS);
|
||||
if (oidcProviderDetailsJson != null && !oidcProviderDetailsJson.isBlank()) {
|
||||
try {
|
||||
builder.oidcProviderDetails(objectMapper.readValue(oidcProviderDetailsJson, OidcProviderDetails.class));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse " + OIDC_PROVIDER_DETAILS, e);
|
||||
}
|
||||
} else {
|
||||
builder.oidcProviderDetails(null);
|
||||
}
|
||||
|
||||
String oidcAutoProvisionDetailsJson = settingsMap.get(OIDC_AUTO_PROVISION_DETAILS);
|
||||
if (oidcAutoProvisionDetailsJson != null && !oidcAutoProvisionDetailsJson.isBlank()) {
|
||||
try {
|
||||
builder.oidcAutoProvisionDetails(objectMapper.readValue(oidcAutoProvisionDetailsJson, OidcAutoProvisionDetails.class));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse " + OIDC_AUTO_PROVISION_DETAILS, e);
|
||||
}
|
||||
} else {
|
||||
builder.oidcAutoProvisionDetails(null);
|
||||
}
|
||||
|
||||
builder.coverResolution(getOrCreateSetting(COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(getOrCreateSetting(AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(getOrCreateSetting(UPLOAD_FILE_PATTERN, ""));
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(OPDS_SERVER_ENABLED, "false")));
|
||||
builder.oidcEnabled(Boolean.parseBoolean(getOrCreateSetting(OIDC_ENABLED, "false")));
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private String getOrCreateSetting(String name, String defaultValue) {
|
||||
AppSettingEntity existing = appSettingsRepository.findByName(name);
|
||||
if (existing != null) {
|
||||
return existing.getVal();
|
||||
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
||||
if (setting != null) {
|
||||
return setting.getVal();
|
||||
}
|
||||
AppSettingEntity newSetting = new AppSettingEntity();
|
||||
newSetting.setName(name);
|
||||
newSetting.setVal(defaultValue);
|
||||
appSettingsRepository.save(newSetting);
|
||||
saveDefaultSetting(name, defaultValue);
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private void saveDefaultSetting(String name, String value) {
|
||||
AppSettingEntity setting = new AppSettingEntity();
|
||||
setting.setName(name);
|
||||
setting.setVal(value);
|
||||
appSettingsRepository.save(setting);
|
||||
}
|
||||
}
|
||||
+83
-48
@@ -2,40 +2,68 @@ package com.adityachandel.booklore.service.user;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.InitialUserRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class UserCreatorService {
|
||||
public class UserProvisioningService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserRepository userRepository;
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
|
||||
public boolean isInitialUserAlreadyProvisioned() {
|
||||
return userRepository.count() > 0;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void registerUser(UserCreateRequest request) {
|
||||
public void provisionInitialUser(InitialUserRequest request) {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername(request.getUsername());
|
||||
user.setEmail(request.getEmail());
|
||||
user.setName(request.getName());
|
||||
user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
|
||||
user.setDefaultPassword(false);
|
||||
user.setProvisioningMethod(ProvisioningMethod.LOCAL);
|
||||
user.setBookPreferences(buildDefaultBookPreferences());
|
||||
|
||||
UserPermissionsEntity perms = new UserPermissionsEntity();
|
||||
perms.setPermissionAdmin(true);
|
||||
perms.setPermissionUpload(true);
|
||||
perms.setPermissionDownload(true);
|
||||
perms.setPermissionEditMetadata(true);
|
||||
perms.setPermissionManipulateLibrary(true);
|
||||
perms.setPermissionEmailBook(true);
|
||||
|
||||
user.setPermissions(perms);
|
||||
createUser(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void provisionInternalUser(UserCreateRequest request) {
|
||||
Optional<BookLoreUserEntity> existingUser = userRepository.findByUsername(request.getUsername());
|
||||
if (existingUser.isPresent()) {
|
||||
throw ApiError.USERNAME_ALREADY_TAKEN.createException(request.getUsername());
|
||||
@@ -47,6 +75,7 @@ public class UserCreatorService {
|
||||
user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
|
||||
user.setName(request.getName());
|
||||
user.setEmail(request.getEmail());
|
||||
user.setProvisioningMethod(ProvisioningMethod.LOCAL);
|
||||
|
||||
UserPermissionsEntity permissions = new UserPermissionsEntity();
|
||||
permissions.setUser(user);
|
||||
@@ -67,7 +96,38 @@ public class UserCreatorService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookLoreUserEntity createRemoteUser(String name, String username, String email, String groups) {
|
||||
public BookLoreUserEntity provisionOidcUser(String username, String email, String name, OidcAutoProvisionDetails oidcAutoProvisionDetails) {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername(username);
|
||||
user.setEmail(email);
|
||||
user.setName(name);
|
||||
user.setDefaultPassword(false);
|
||||
user.setPasswordHash("OIDC_USER_" + UUID.randomUUID());
|
||||
user.setProvisioningMethod(ProvisioningMethod.OIDC);
|
||||
user.setBookPreferences(buildDefaultBookPreferences());
|
||||
|
||||
UserPermissionsEntity perms = new UserPermissionsEntity();
|
||||
List<String> defaultPermissions = oidcAutoProvisionDetails.getDefaultPermissions();
|
||||
if (defaultPermissions != null) {
|
||||
perms.setPermissionUpload(defaultPermissions.contains("permissionUpload"));
|
||||
perms.setPermissionDownload(defaultPermissions.contains("permissionDownload"));
|
||||
perms.setPermissionEditMetadata(defaultPermissions.contains("permissionEditMetadata"));
|
||||
perms.setPermissionManipulateLibrary(defaultPermissions.contains("permissionManipulateLibrary"));
|
||||
perms.setPermissionEmailBook(defaultPermissions.contains("permissionEmailBook"));
|
||||
}
|
||||
user.setPermissions(perms);
|
||||
|
||||
List<Long> defaultLibraryIds = oidcAutoProvisionDetails.getDefaultLibraryIds();
|
||||
if(defaultLibraryIds != null && !defaultLibraryIds.isEmpty()) {
|
||||
List<LibraryEntity> libraries = libraryRepository.findAllById(defaultLibraryIds);
|
||||
user.setLibraries(new ArrayList<>(libraries));
|
||||
}
|
||||
return createUser(user);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Transactional
|
||||
public BookLoreUserEntity provisionRemoteUser(String name, String username, String email, String groups) {
|
||||
boolean isAdmin = false;
|
||||
if (groups != null && appProperties.getRemoteAuth().getAdminGroup() != null) {
|
||||
String groupsContent = groups.trim();
|
||||
@@ -84,7 +144,8 @@ public class UserCreatorService {
|
||||
user.setName(name != null ? name : username);
|
||||
user.setEmail(email);
|
||||
user.setDefaultPassword(false);
|
||||
user.setPasswordHash(passwordEncoder.encode(RandomStringUtils.secure().nextAlphanumeric(32)));
|
||||
user.setProvisioningMethod(ProvisioningMethod.REMOTE);
|
||||
user.setPasswordHash("RemoteUser_" + RandomStringUtils.secure().nextAlphanumeric(32));
|
||||
|
||||
UserPermissionsEntity permissions = new UserPermissionsEntity();
|
||||
permissions.setUser(user);
|
||||
@@ -105,44 +166,19 @@ public class UserCreatorService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void createAdminUser() {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername("admin");
|
||||
user.setPasswordHash(passwordEncoder.encode("admin123"));
|
||||
user.setDefaultPassword(true);
|
||||
user.setName("Administrator");
|
||||
user.setEmail("admin@email.com");
|
||||
|
||||
UserPermissionsEntity permissions = new UserPermissionsEntity();
|
||||
permissions.setUser(user);
|
||||
permissions.setPermissionUpload(true);
|
||||
permissions.setPermissionDownload(true);
|
||||
permissions.setPermissionManipulateLibrary(true);
|
||||
permissions.setPermissionEditMetadata(true);
|
||||
permissions.setPermissionEmailBook(true);
|
||||
permissions.setPermissionAdmin(true);
|
||||
|
||||
user.setPermissions(permissions);
|
||||
user.setBookPreferences(buildDefaultBookPreferences());
|
||||
|
||||
createUser(user);
|
||||
log.info("Created admin user {}", user.getUsername());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
BookLoreUserEntity createUser(BookLoreUserEntity user) {
|
||||
ShelfEntity shelfEntity = ShelfEntity.builder()
|
||||
.user(user)
|
||||
.name("Favorites")
|
||||
.icon("heart")
|
||||
.build();
|
||||
protected BookLoreUserEntity createUser(BookLoreUserEntity user) {
|
||||
user = userRepository.save(user);
|
||||
shelfRepository.save(shelfEntity);
|
||||
return user;
|
||||
}
|
||||
|
||||
public boolean doesAdminUserExist() {
|
||||
return userRepository.findByUsername("admin").isPresent();
|
||||
if (user.getShelves() == null || user.getShelves().isEmpty()) {
|
||||
ShelfEntity shelfEntity = ShelfEntity.builder()
|
||||
.user(user)
|
||||
.name("Favorites")
|
||||
.icon("heart")
|
||||
.build();
|
||||
shelfRepository.save(shelfEntity);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
private BookPreferences buildDefaultBookPreferences() {
|
||||
@@ -162,5 +198,4 @@ public class UserCreatorService {
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
ALTER TABLE app_settings
|
||||
MODIFY COLUMN name VARCHAR(255) NOT NULL,
|
||||
ADD UNIQUE INDEX uq_app_settings_name (name);
|
||||
|
||||
ALTER TABLE app_settings
|
||||
MODIFY COLUMN val TEXT NULL;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE users
|
||||
ADD COLUMN provisioning_method VARCHAR(50);
|
||||
@@ -62,7 +62,7 @@
|
||||
{
|
||||
"type": "initial",
|
||||
"maximumWarning": "500kB",
|
||||
"maximumError": "3MB"
|
||||
"maximumError": "3.5MB"
|
||||
},
|
||||
{
|
||||
"type": "anyComponentStyle",
|
||||
|
||||
Generated
+14
@@ -21,6 +21,7 @@
|
||||
"@stomp/rx-stomp": "2.0.1",
|
||||
"@stomp/stompjs": "7.1.1",
|
||||
"@tailwindcss/postcss": "^4.1.4",
|
||||
"angular-oauth2-oidc": "^19.0.0",
|
||||
"epubjs": "0.3.93",
|
||||
"jwt-decode": "4.0.0",
|
||||
"ng-lazyload-image": "9.1.3",
|
||||
@@ -6873,6 +6874,19 @@
|
||||
"typescript-eslint": "^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/angular-oauth2-oidc": {
|
||||
"version": "19.0.0",
|
||||
"resolved": "https://registry.npmjs.org/angular-oauth2-oidc/-/angular-oauth2-oidc-19.0.0.tgz",
|
||||
"integrity": "sha512-EogHyF7MpCJSjSKIyVmdB8pJu7dU5Ilj9VNVSnFbLng4F77PIlaE4egwKUlUvk0i4ZvmO9rLXNQCm05R7Tyhcw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.5.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@angular/common": ">=19.0.0",
|
||||
"@angular/core": ">=19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-colors": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz",
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"@stomp/rx-stomp": "2.0.1",
|
||||
"@stomp/stompjs": "7.1.1",
|
||||
"@tailwindcss/postcss": "^4.1.4",
|
||||
"angular-oauth2-oidc": "^19.0.0",
|
||||
"epubjs": "0.3.93",
|
||||
"jwt-decode": "4.0.0",
|
||||
"ng-lazyload-image": "9.1.3",
|
||||
|
||||
@@ -9,13 +9,26 @@ import {PdfViewerComponent} from './book/components/pdf-viewer/pdf-viewer.compon
|
||||
import {EpubViewerComponent} from './book/components/epub-viewer/component/epub-viewer.component';
|
||||
import {ChangePasswordComponent} from './core/component/change-password/change-password.component';
|
||||
import {BookMetadataCenterComponent} from './metadata/book-metadata-center/book-metadata-center.component';
|
||||
import {SetupComponent} from './setup/setup.component';
|
||||
import {SetupGuard} from './setup/setup.guard';
|
||||
import {SetupRedirectGuard} from './setup/setup-redirect.guard';
|
||||
import {EmptyComponent} from './empty/empty.component';
|
||||
import {LoginGuard} from './setup/ login.guard';
|
||||
import {OidcCallbackComponent} from './oidc-callback/oidc-callback.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
redirectTo: 'dashboard',
|
||||
pathMatch: 'full'
|
||||
canActivate: [SetupRedirectGuard],
|
||||
pathMatch: 'full',
|
||||
component: EmptyComponent
|
||||
},
|
||||
{
|
||||
path: 'setup',
|
||||
component: SetupComponent,
|
||||
canActivate: [SetupGuard]
|
||||
},
|
||||
{path: 'oauth2-callback', component: OidcCallbackComponent},
|
||||
{
|
||||
path: '',
|
||||
component: AppLayoutComponent,
|
||||
@@ -38,7 +51,19 @@ export const routes: Routes = [
|
||||
component: EpubViewerComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{path: 'login', component: LoginComponent},
|
||||
{path: 'change-password', component: ChangePasswordComponent},
|
||||
{path: '**', redirectTo: 'login', pathMatch: 'full'}
|
||||
{
|
||||
path: 'login',
|
||||
component: LoginComponent,
|
||||
canActivate: [LoginGuard]
|
||||
},
|
||||
{
|
||||
path: 'change-password',
|
||||
component: ChangePasswordComponent,
|
||||
canActivate: [SetupGuard]
|
||||
},
|
||||
{
|
||||
path: '**',
|
||||
redirectTo: 'login',
|
||||
pathMatch: 'full'
|
||||
}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import {inject} from '@angular/core';
|
||||
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';
|
||||
|
||||
export function initializeAuthFactory() {
|
||||
return () => {
|
||||
const oauthService = inject(OAuthService);
|
||||
const appSettingsService = inject(AppSettingsService);
|
||||
const authService = inject(AuthService);
|
||||
|
||||
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,
|
||||
scope: 'openid profile email offline_access',
|
||||
redirectUri: window.location.origin + '/oauth2-callback',
|
||||
responseType: 'code',
|
||||
showDebugInformation: 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();
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
sub.unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -4,23 +4,24 @@ import {Router} from '@angular/router';
|
||||
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, Observable, throwError} from 'rxjs';
|
||||
import {AuthService} from './core/service/auth.service';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
|
||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
const token = authService.getToken();
|
||||
let authReq = req;
|
||||
|
||||
if (token) {
|
||||
authReq = req.clone({
|
||||
setHeaders: {Authorization: `Bearer ${token}`}
|
||||
});
|
||||
}
|
||||
const internalToken = authService.getInternalAccessToken();
|
||||
const oidcToken = authService.getOidcAccessToken();
|
||||
const token = internalToken || oidcToken;
|
||||
|
||||
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
||||
|
||||
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||
|
||||
return next(authReq).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
return handle401Error(authService, authReq, next, router);
|
||||
return handle401Error(authService, authReq, next, router, !!internalToken);
|
||||
}
|
||||
return throwError(() => error);
|
||||
})
|
||||
@@ -30,32 +31,49 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<any>, next: HttpHandlerFn, router: Router): Observable<any> {
|
||||
if (!isRefreshing) {
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<any>, next: HttpHandlerFn, router: Router, isInternal: boolean): Observable<any> {
|
||||
if (!isRefreshing && isInternal) {
|
||||
isRefreshing = true;
|
||||
refreshTokenSubject.next(null);
|
||||
|
||||
return authService.refreshToken().pipe(
|
||||
switchMap((response) => {
|
||||
return authService.internalRefreshToken().pipe(
|
||||
switchMap(response => {
|
||||
isRefreshing = false;
|
||||
refreshTokenSubject.next(response.accessToken);
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
authService.saveTokens(response.accessToken, response.refreshToken);
|
||||
const { accessToken, refreshToken } = response;
|
||||
if (accessToken && refreshToken) {
|
||||
authService.saveInternalTokens(accessToken, refreshToken);
|
||||
refreshTokenSubject.next(accessToken);
|
||||
}
|
||||
return next(request.clone({setHeaders: {Authorization: `Bearer ${response.accessToken}`}}));
|
||||
return next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
||||
}));
|
||||
}),
|
||||
catchError((err) => {
|
||||
catchError(err => {
|
||||
isRefreshing = false;
|
||||
authService.logout();
|
||||
router.navigate(['/login']);
|
||||
forceLogout(authService, router);
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
} else {
|
||||
}
|
||||
|
||||
if (isRefreshing && isInternal) {
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap((token) => next(request.clone({setHeaders: {Authorization: `Bearer ${token}`}})))
|
||||
switchMap(token =>
|
||||
next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
}))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
forceLogout(authService, router, isInternal ? 'Session expired, please log in again.' : 'OIDC token expired, please log in again.');
|
||||
return throwError(() => new Error('Authentication failed, please log in.'));
|
||||
}
|
||||
|
||||
function forceLogout(authService: AuthService, router: Router, message?: string): void {
|
||||
authService.logout();
|
||||
router.navigate(['/login']);
|
||||
if (message) console.warn(message);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {CanActivateFn, Router} from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn } from '@angular/router';
|
||||
import { Router } from '@angular/router';
|
||||
import { OAuthService } from 'angular-oauth2-oidc';
|
||||
|
||||
export const AuthGuard: CanActivateFn = (route, state) => {
|
||||
const router = inject(Router);
|
||||
const token = localStorage.getItem('accessToken');
|
||||
|
||||
if (!token) {
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
const legacyToken = localStorage.getItem('accessToken_Internal');
|
||||
|
||||
if (legacyToken) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(legacyToken.split('.')[1]));
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Invalid legacy token:', e);
|
||||
localStorage.removeItem('accessToken');
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
const oidcToken = localStorage.getItem('accessToken_OIDC');
|
||||
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
if (oidcToken) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -101,7 +101,7 @@
|
||||
</div>
|
||||
<div class="no-books-container" *ngIf="!bookState?.error && bookState?.loaded && bookState?.books?.length === 0">
|
||||
<p class="no-books-text">
|
||||
{{ entityType === EntityType.LIBRARY ? "This library has no books!" : "This shelf has no books!" }}
|
||||
This collection has no books!
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
<div class="login-container">
|
||||
<div class="login-container" >
|
||||
<div class="login-wrapper">
|
||||
<h1 class="app-title">BookLore</h1>
|
||||
<p-card class="login-card p-fluid">
|
||||
<ng-template pTemplate="title">Login</ng-template>
|
||||
|
||||
<p-card class="w-96">
|
||||
<ng-template pTemplate="title">
|
||||
<div class="text-center pb-2">Login</div>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="content">
|
||||
<form #loginForm="ngForm" (ngSubmit)="login()">
|
||||
<div class="p-field">
|
||||
<form class="flex flex-col gap-4" #loginForm="ngForm" (ngSubmit)="login()">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="username">Username</label>
|
||||
<input pInputText id="username" [(ngModel)]="username" name="username" required fluid/>
|
||||
<input fluid pInputText id="username" [(ngModel)]="username" name="username" required/>
|
||||
</div>
|
||||
|
||||
<div class="p-field">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="password">Password</label>
|
||||
<p-password id="password" [(ngModel)]="password" name="password" [feedback]="false" fluid required></p-password>
|
||||
<p-password fluid id="password" [(ngModel)]="password" name="password" [feedback]="false" required></p-password>
|
||||
</div>
|
||||
|
||||
<div class="p-mt-3">
|
||||
<p-button type="submit" label="Login" icon="pi pi-sign-in" class="p-fluid"></p-button>
|
||||
<div class="flex flex-col gap-3 mt-4">
|
||||
<p-button
|
||||
fluid
|
||||
severity="primary"
|
||||
type="submit"
|
||||
label="Login"
|
||||
icon="pi pi-sign-in"
|
||||
[disabled]="!loginForm.valid || !username || !password">
|
||||
</p-button>
|
||||
<p-message *ngIf="errorMessage" severity="error" text="{{ errorMessage }}"></p-message>
|
||||
<div *ngIf="oidcEnabled">
|
||||
<p-divider></p-divider>
|
||||
<p-button fluid severity="info" type="button" label="Login with OIDC" icon="pi pi-id-card" (click)="loginWithOidc()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-message *ngIf="errorMessage" severity="error" text="{{ errorMessage }}"></p-message>
|
||||
</form>
|
||||
</ng-template>
|
||||
</p-card>
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
.login-container {
|
||||
@apply flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-900 via-cyan-600 to-blue-400 relative;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(to bottom right, #1e3a8a, #06b6d4, #3b82f6);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.login-wrapper {
|
||||
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
position: absolute;
|
||||
top: 25%;
|
||||
transform: translateY(-25%);
|
||||
}
|
||||
|
||||
.app-title {
|
||||
@apply text-5xl font-extrabold text-white drop-shadow-lg;
|
||||
font-size: 3rem;
|
||||
font-weight: 800;
|
||||
color: white;
|
||||
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
@apply w-96 shadow-lg rounded-xl bg-opacity-90 backdrop-blur-lg;
|
||||
}
|
||||
|
||||
form {
|
||||
@apply flex flex-col gap-4;
|
||||
}
|
||||
|
||||
.p-field {
|
||||
@apply flex flex-col gap-2;
|
||||
}
|
||||
|
||||
p-button {
|
||||
@apply mt-4;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Component} from '@angular/core';
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {AuthService} from '../../service/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
@@ -9,6 +9,12 @@ import {Button} from 'primeng/button';
|
||||
import {Message} from 'primeng/message';
|
||||
import {PrimeTemplate} from 'primeng/api';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {AppSettingsService} from '../../service/app-settings.service';
|
||||
import {AppSettings} from '../../model/app-settings.model';
|
||||
import {Observable} from 'rxjs';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
@@ -20,26 +26,38 @@ import {InputText} from 'primeng/inputtext';
|
||||
Button,
|
||||
Message,
|
||||
PrimeTemplate,
|
||||
InputText
|
||||
InputText,
|
||||
Divider
|
||||
],
|
||||
templateUrl: './login.component.html',
|
||||
styleUrl: './login.component.scss'
|
||||
styleUrls: ['./login.component.scss']
|
||||
})
|
||||
export class LoginComponent {
|
||||
export class LoginComponent implements OnInit {
|
||||
username = '';
|
||||
password = '';
|
||||
errorMessage = '';
|
||||
oidcEnabled = false;
|
||||
|
||||
constructor(private authService: AuthService, private router: Router) {
|
||||
this.authService.remoteLogin().subscribe({
|
||||
next: () => {
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
});
|
||||
private authService = inject(AuthService);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private router = inject(Router);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$
|
||||
.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(settings => {
|
||||
this.oidcEnabled = settings?.oidcEnabled;
|
||||
});
|
||||
}
|
||||
|
||||
login(): void {
|
||||
this.authService.login({username: this.username, password: this.password}).subscribe({
|
||||
this.authService.internalLogin({username: this.username, password: this.password}).subscribe({
|
||||
next: (response) => {
|
||||
if (response.isDefaultPassword === 'true') {
|
||||
this.router.navigate(['/change-password']);
|
||||
@@ -56,4 +74,8 @@ export class LoginComponent {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loginWithOidc(): void {
|
||||
this.oAuthService.initImplicitFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
||||
|
||||
export interface OidcProviderDetails {
|
||||
providerName: string;
|
||||
clientId: string;
|
||||
issuerUri: string;
|
||||
jwksUrl: string;
|
||||
claimMapping: {
|
||||
username: string;
|
||||
email: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OidcAutoProvisionDetails {
|
||||
enableAutoProvisioning: boolean;
|
||||
defaultPermissions: string[];
|
||||
defaultLibraryIds: number[];
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
autoBookSearch: boolean;
|
||||
similarBookRecommendation: boolean;
|
||||
@@ -7,4 +25,7 @@ export interface AppSettings {
|
||||
coverResolution: string;
|
||||
uploadPattern: string;
|
||||
opdsServerEnabled: boolean;
|
||||
oidcEnabled: boolean;
|
||||
oidcProviderDetails: OidcProviderDetails;
|
||||
oidcAutoProvisionDetails: OidcAutoProvisionDetails;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {AppSettings} from '../model/app-settings.model';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
|
||||
@@ -3,6 +3,7 @@ import {HttpClient} from '@angular/common/http';
|
||||
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';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -15,62 +16,76 @@ export class AuthService {
|
||||
private http = inject(HttpClient);
|
||||
private injector = inject(Injector);
|
||||
|
||||
login(credentials: { username: string; password: string }): Observable<any> {
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<any> {
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.getRxStompService().activate();
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
this.initializeWebSocketConnection();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
remoteLogin(): Observable<any> {
|
||||
return this.http.get<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/remote`).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.getRxStompService().activate();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = this.getRefreshToken();
|
||||
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = this.getInternalRefreshToken();
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
saveTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', refreshToken);
|
||||
saveInternalTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken_Internal', accessToken);
|
||||
localStorage.setItem('refreshToken_Internal', refreshToken);
|
||||
}
|
||||
|
||||
getToken(): string | null {
|
||||
return localStorage.getItem('accessToken');
|
||||
saveOidcTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken_OIDC', accessToken);
|
||||
localStorage.setItem('refreshToken_OIDC', refreshToken);
|
||||
}
|
||||
|
||||
getRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken');
|
||||
getInternalAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_Internal');
|
||||
}
|
||||
|
||||
getOidcAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_OIDC');
|
||||
}
|
||||
|
||||
getInternalRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken_Internal');
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
localStorage.removeItem('refreshToken_Internal');
|
||||
localStorage.removeItem('accessToken_OIDC');
|
||||
localStorage.removeItem('refreshToken_OIDC');
|
||||
this.getRxStompService().deactivate();
|
||||
}
|
||||
|
||||
private getRxStompService(): RxStompService {
|
||||
getRxStompService(): RxStompService {
|
||||
if (!this.rxStompService) {
|
||||
this.rxStompService = this.injector.get(RxStompService);
|
||||
}
|
||||
return this.rxStompService;
|
||||
}
|
||||
|
||||
initializeWebSocketConnection(): void {
|
||||
const token = this.getOidcAccessToken() || this.getInternalAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
const stompService = this.getRxStompService();
|
||||
const config = createRxStompConfig(this);
|
||||
stompService.updateConfig(config);
|
||||
stompService.activate();
|
||||
}
|
||||
}
|
||||
|
||||
export function websocketInitializer(authService: AuthService): () => void {
|
||||
return () => authService.initializeWebSocketConnection();
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<p>empty works!</p>
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-empty',
|
||||
imports: [],
|
||||
templateUrl: './empty.component.html',
|
||||
styleUrl: './empty.component.scss'
|
||||
})
|
||||
export class EmptyComponent {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
<div class="w-full h-[calc(100vh-12.1rem)] overflow-y-auto border rounded-lg enclosing-container">
|
||||
|
||||
<div class="p-4">
|
||||
<p class="text-xl gap-2 pb-4 pt-6">Internal Authentication:</p>
|
||||
<div class="flex items-center gap-4 pl-6">
|
||||
<label class="text-lg">Enabled</label>
|
||||
<p-checkbox
|
||||
[(ngModel)]="internalAuthEnabled"
|
||||
[binary]="true"
|
||||
[disabled]="true">
|
||||
</p-checkbox>
|
||||
<div class="flex items-center gap-2 pl-4 text-sm text-gray-400">
|
||||
<i class="pi pi-info-circle text-blue-500"></i>
|
||||
<span>
|
||||
Internal authentication is always enabled and cannot be disabled. However, OIDC can be used alongside internal authentication if OIDC is enabled.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="p-4">
|
||||
<p class="text-xl pb-4 pt-2">OIDC Authentication (Experimental):</p>
|
||||
<div class="flex items-center gap-4">
|
||||
<label class="text-lg pl-6">Enabled</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcEnabled"
|
||||
[disabled]="!isOidcFormComplete()"
|
||||
(onChange)="toggleOidcEnabled()">
|
||||
</p-toggleswitch>
|
||||
<div *ngIf="!isOidcFormComplete()" class="text-sm text-gray-400">
|
||||
(Fill all required fields to enable)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-lg pt-8">OIDC Provider Settings:</p>
|
||||
<div class="pl-6 space-y-6 p-4 m-4 custom-border">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-4xl">
|
||||
<div>
|
||||
<label for="providerName" class="mb-1">Provider Name</label>
|
||||
<input
|
||||
pInputText
|
||||
id="providerName"
|
||||
[(ngModel)]="oidcProvider.providerName"
|
||||
placeholder="e.g. Authentik"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="clientId" class="mb-1">Client ID</label>
|
||||
<input
|
||||
pInputText
|
||||
id="clientId"
|
||||
[(ngModel)]="oidcProvider.clientId"
|
||||
placeholder="e.g. my-client-id"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2 items-center">
|
||||
<label for="scope" class="mb-1">Scope</label>
|
||||
<input
|
||||
pInputText
|
||||
id="scope"
|
||||
class="w-full"
|
||||
[readonly]="true"
|
||||
disabled="disabled"
|
||||
value="openid profile email offline_access"/>
|
||||
<div class="flex items-center gap-2 text-sm text-gray-400 mt-2 pl-1">
|
||||
<i class="pi pi-info-circle text-blue-500 mt-1"></i>
|
||||
<span>
|
||||
Required scopes for OIDC login and token exchange. Must be supported and advertised in the provider’s discovery metadata.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label for="issuerUri" class="mb-1">Issuer URI</label>
|
||||
<input
|
||||
pInputText
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
placeholder="e.g. https://auth.example.com/realms/myrealm"
|
||||
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://auth.example.com/realms/myrealm/protocol/openid-connect/certs"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label for="claimUsername" class="mb-1">Username Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimUsername"
|
||||
[(ngModel)]="oidcProvider.claimMapping.username"
|
||||
placeholder="e.g. preferred_username"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="claimEmail" class="mb-1">Email Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimEmail"
|
||||
[(ngModel)]="oidcProvider.claimMapping.email"
|
||||
placeholder="e.g. email"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div>
|
||||
<label for="claimName" class="mb-1">Display Name Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimName"
|
||||
[(ngModel)]="oidcProvider.claimMapping.name"
|
||||
placeholder="e.g. name or given_name"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-start gap-2 text-sm text-gray-400 mt-2 pl-1">
|
||||
<i class="pi pi-info-circle text-blue-500 mt-1"></i>
|
||||
<span>
|
||||
These claims are used by Booklore to provision new OIDC users with their name, username, and email. Ensure they match the claims provided by your OIDC provider.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
type="button"
|
||||
label="Save Settings"
|
||||
class="p-button-primary w-full sm:w-auto"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="oidcEnabled">
|
||||
<p class="text-lg pt-6">OIDC User Provisioning:</p>
|
||||
<div class="pl-6 space-y-6 p-4 m-4 custom-border">
|
||||
<div>
|
||||
<p class="text-xl pb-3">Automatic user provisioning:</p>
|
||||
<div class="flex items-center gap-4 pl-6">
|
||||
<label class="text-lg">Enabled</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="autoUserProvisioningEnabled"
|
||||
inputId="autoProvision"
|
||||
(onChange)="saveAutoProvision()">
|
||||
</p-toggleswitch>
|
||||
<div class="flex items-center gap-2 text-sm text-gray-400">
|
||||
<i class="pi pi-info-circle text-blue-500"></i>
|
||||
<span>
|
||||
Enabling auto-provisioning ensures that new users are automatically created with the selected default permissions. If turned off, users must be manually created in Booklore before they can log in.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="autoUserProvisioningEnabled">
|
||||
<p class="text-lg pt-8">Default permissions for auto-provisioned users:</p>
|
||||
<div class="flex items-center gap-2 pl-6 pt-2">
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[disabled]="true"
|
||||
[ngModel]="true"
|
||||
inputId="permissionRead">
|
||||
</p-checkbox>
|
||||
<label class="text-sm">Read Books</label>
|
||||
</div>
|
||||
|
||||
<div *ngFor="let perm of availablePermissions" class="flex items-center gap-2 pl-6">
|
||||
<p-checkbox
|
||||
[(ngModel)]="perm.selected"
|
||||
[binary]="true"
|
||||
[inputId]="perm.value">
|
||||
</p-checkbox>
|
||||
<label [for]="perm.value" class="text-sm">{{ perm.label }}</label>
|
||||
</div>
|
||||
|
||||
<p class="text-lg pb-3 pt-6">Default libraries for auto-provisioned users:</p>
|
||||
<div class="pl-6">
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
placeholder="Select Libraries"
|
||||
appendTo="body">
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
<div class="mt-8">
|
||||
<p-button label="Save Settings" [outlined]="true" (click)="saveAutoProvisioningSettings()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.custom-border {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--card-border);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Button} from 'primeng/button';
|
||||
import {DropdownModule} from 'primeng/dropdown';
|
||||
import {NgForOf, NgIf} from '@angular/common';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {ToggleSwitch} from 'primeng/toggleswitch';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AppSettingsService} from '../core/service/app-settings.service';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AppSettings, OidcProviderDetails} from '../core/model/app-settings.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {Library} from '../book/model/library.model';
|
||||
import {LibraryService} from '../book/service/library.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-authentication-settings',
|
||||
templateUrl: './authentication-settings.component.html',
|
||||
standalone: true,
|
||||
imports: [
|
||||
FormsModule,
|
||||
InputText,
|
||||
DropdownModule,
|
||||
NgIf,
|
||||
NgForOf,
|
||||
Checkbox,
|
||||
ToggleSwitch,
|
||||
Divider,
|
||||
Button,
|
||||
MultiSelect,
|
||||
ReactiveFormsModule
|
||||
],
|
||||
styleUrls: ['./authentication-settings.component.scss']
|
||||
})
|
||||
export class AuthenticationSettingsComponent implements OnInit {
|
||||
availablePermissions = [
|
||||
{label: 'Upload Books', value: 'permissionUpload', selected: false},
|
||||
{label: 'Download Books', value: 'permissionDownload', selected: false},
|
||||
{label: 'Edit Book Metadata', value: 'permissionEditMetadata', selected: false},
|
||||
{label: 'Email Book', value: 'permissionEmailBook', selected: false}
|
||||
];
|
||||
|
||||
internalAuthEnabled = true;
|
||||
autoUserProvisioningEnabled = false;
|
||||
selectedPermissions: string[] = [];
|
||||
oidcEnabled = false;
|
||||
allLibraries: Library[] = [];
|
||||
editingLibraryIds: number[] = [];
|
||||
|
||||
oidcProvider: OidcProviderDetails = {
|
||||
providerName: '',
|
||||
clientId: '',
|
||||
issuerUri: '',
|
||||
jwksUrl: '',
|
||||
claimMapping: {
|
||||
username: '',
|
||||
email: '',
|
||||
name: ''
|
||||
}
|
||||
};
|
||||
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$.pipe(
|
||||
filter((settings): settings is AppSettings => settings != null),
|
||||
take(1)
|
||||
).subscribe(settings => this.loadSettings(settings));
|
||||
|
||||
this.libraryService.getAllLibrariesFromAPI().subscribe({
|
||||
next: (libraries) => {
|
||||
this.allLibraries = libraries;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load libraries'});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
loadSettings(settings: AppSettings): void {
|
||||
this.oidcEnabled = settings.oidcEnabled;
|
||||
|
||||
const details = settings.oidcAutoProvisionDetails;
|
||||
|
||||
this.autoUserProvisioningEnabled = details?.enableAutoProvisioning ?? false;
|
||||
this.selectedPermissions = details?.defaultPermissions ?? [];
|
||||
this.editingLibraryIds = details?.defaultLibraryIds ?? [];
|
||||
|
||||
const defaultClaimMapping = {
|
||||
username: 'preferred_username',
|
||||
email: 'email',
|
||||
name: 'given_name'
|
||||
};
|
||||
|
||||
this.oidcProvider = {
|
||||
providerName: settings.oidcProviderDetails?.providerName || '',
|
||||
clientId: settings.oidcProviderDetails?.clientId || '',
|
||||
issuerUri: settings.oidcProviderDetails?.issuerUri || '',
|
||||
jwksUrl: settings.oidcProviderDetails?.jwksUrl || '',
|
||||
claimMapping: settings.oidcProviderDetails?.claimMapping || defaultClaimMapping
|
||||
};
|
||||
|
||||
this.availablePermissions.forEach(perm => {
|
||||
perm.selected = this.selectedPermissions.includes(perm.value);
|
||||
});
|
||||
}
|
||||
|
||||
isOidcFormComplete(): boolean {
|
||||
const p = this.oidcProvider;
|
||||
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 = [
|
||||
{
|
||||
key: 'oidc_enabled',
|
||||
newValue: this.oidcEnabled
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'OIDC setting updated.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update OIDC setting.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
saveOidcProvider(): void {
|
||||
const payload = [
|
||||
{
|
||||
key: 'oidc_provider_details',
|
||||
newValue: this.oidcProvider
|
||||
}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'OIDC provider settings saved.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save OIDC provider settings.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
saveAutoProvisioningSettings(): void {
|
||||
const provisionDetails = {
|
||||
enableAutoProvisioning: this.autoUserProvisioningEnabled,
|
||||
defaultPermissions: [
|
||||
'permissionRead',
|
||||
...this.availablePermissions.filter(p => p.selected).map(p => p.value)
|
||||
],
|
||||
defaultLibraryIds: this.editingLibraryIds
|
||||
};
|
||||
|
||||
const payload = [
|
||||
{
|
||||
key: 'oidc_auto_provision_details',
|
||||
newValue: provisionDetails
|
||||
}
|
||||
];
|
||||
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'OIDC auto-provisioning settings saved.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save OIDC auto-provisioning settings.'
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AuthService} from '../core/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-oidc-callback',
|
||||
templateUrl: './oidc-callback.component.html',
|
||||
styleUrls: ['./oidc-callback.component.scss']
|
||||
})
|
||||
export class OidcCallbackComponent implements OnInit {
|
||||
|
||||
private router = inject(Router);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.oAuthService.loadDiscoveryDocumentAndTryLogin().then(() => {
|
||||
if (this.oAuthService.hasValidAccessToken()) {
|
||||
this.authService.saveOidcTokens(
|
||||
this.oAuthService.getAccessToken(),
|
||||
this.oAuthService.getRefreshToken()
|
||||
);
|
||||
this.authService.getRxStompService().activate();
|
||||
this.router.navigate(['/dashboard']);
|
||||
} else {
|
||||
console.error('Login failed or no valid tokens');
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error('OIDC error during login:', err);
|
||||
this.router.navigate(['/login']);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-lg py-1">Epub:</p>
|
||||
<p class="text-lg py-1">Epub:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<div *ngFor="let item of individualOrGlobal" class="flex items-center gap-2">
|
||||
<p-radiobutton
|
||||
@@ -120,9 +120,9 @@
|
||||
|
||||
<p class="text-lg py-1">Font Size:</p>
|
||||
<div class="flex gap-4 justify-start items-center">
|
||||
<p-button icon="pi pi-minus" rounded="true" (click)="decreaseFontSize()"></p-button>
|
||||
<p-button icon="pi pi-minus" rounded="true" size="small" (click)="decreaseFontSize()"></p-button>
|
||||
<p>{{ fontSize }}%</p>
|
||||
<p-button icon="pi pi-plus" rounded="true" (click)="increaseFontSize()"></p-button>
|
||||
<p-button icon="pi pi-plus" rounded="true" size="small" (click)="increaseFontSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
<div class="rounded-xl overflow-hidden">
|
||||
<p-tabs [(value)]="activeTab">
|
||||
<p-tablist>
|
||||
<p-tab [value]="SettingsTab.BookReader">Book Reader</p-tab>
|
||||
<p-tab [value]="SettingsTab.BookReader">Reader Settings</p-tab>
|
||||
<ng-container *ngIf="userData.permissions.admin">
|
||||
<p-tab [value]="SettingsTab.UserManagement">User Management</p-tab>
|
||||
<p-tab [value]="SettingsTab.Email">Email Setting</p-tab>
|
||||
<p-tab [value]="SettingsTab.GlobalSettings">Other Settings</p-tab>
|
||||
<p-tab [value]="SettingsTab.GlobalSettings">Admin Settings</p-tab>
|
||||
<p-tab [value]="SettingsTab.AuthenticationSettings">Authentication Settings</p-tab>
|
||||
</ng-container>
|
||||
</p-tablist>
|
||||
|
||||
@@ -24,6 +25,9 @@
|
||||
<p-tabpanel [value]="SettingsTab.GlobalSettings">
|
||||
<app-global-preferences></app-global-preferences>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.AuthenticationSettings">
|
||||
<app-authentication-settings></app-authentication-settings>
|
||||
</p-tabpanel>
|
||||
</ng-container>
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
|
||||
@@ -8,12 +8,14 @@ import {GlobalPreferencesComponent} from './global-preferences/global-preference
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {Subscription} from 'rxjs';
|
||||
import {UserManagementComponent} from './user-management/user-management.component';
|
||||
import {AuthenticationSettingsComponent} from '../oauth2-management/authentication-settings.component';
|
||||
|
||||
export enum SettingsTab {
|
||||
BookReader = 'book-reader',
|
||||
UserManagement = 'user-management',
|
||||
Email = 'email',
|
||||
GlobalSettings = 'global-settings'
|
||||
GlobalSettings = 'global-settings',
|
||||
AuthenticationSettings = 'auth-settings'
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -29,7 +31,8 @@ export enum SettingsTab {
|
||||
AsyncPipe,
|
||||
EmailComponent,
|
||||
GlobalPreferencesComponent,
|
||||
UserManagementComponent
|
||||
UserManagementComponent,
|
||||
AuthenticationSettingsComponent
|
||||
],
|
||||
templateUrl: './settings.component.html',
|
||||
styleUrl: './settings.component.scss'
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<p-table [value]="users" class="mt-4">
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>Provisioning</th>
|
||||
<th>Username</th>
|
||||
<th>Full Name</th>
|
||||
<th>Email</th>
|
||||
@@ -26,6 +27,9 @@
|
||||
|
||||
<ng-template pTemplate="body" let-user>
|
||||
<tr>
|
||||
<td>
|
||||
{{ (user.provisioningMethod || 'LOCAL') | lowercase | titlecase }}
|
||||
</td>
|
||||
<td>{{ user.username }}</td>
|
||||
<td>
|
||||
<input *ngIf="user.isEditing" type="text" [(ngModel)]="user.name" class="p-inputtext w-full"/>
|
||||
|
||||
@@ -4,7 +4,7 @@ import {Button} from 'primeng/button';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {CreateUserDialogComponent} from './create-user-dialog/create-user-dialog.component';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {NgIf, NgStyle} from '@angular/common';
|
||||
import {LowerCasePipe, NgIf, NgStyle, TitleCasePipe} from '@angular/common';
|
||||
import {User, UserService} from './user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
@@ -25,7 +25,9 @@ import {Password} from 'primeng/password';
|
||||
NgStyle,
|
||||
MultiSelect,
|
||||
Dialog,
|
||||
Password
|
||||
Password,
|
||||
LowerCasePipe,
|
||||
TitleCasePipe
|
||||
],
|
||||
templateUrl: './user-management.component.html',
|
||||
styleUrls: ['./user-management.component.scss'],
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface User {
|
||||
canManipulateLibrary: boolean;
|
||||
};
|
||||
bookPreferences: UserBookPreferences;
|
||||
provisioningMethod?: 'LOCAL' | 'OIDC' | 'REMOTE';
|
||||
}
|
||||
|
||||
export interface UserBookPreferences {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { CanActivate, Router } from '@angular/router';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, map, catchError, of } from 'rxjs';
|
||||
import { API_CONFIG } from '../config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class LoginGuard implements CanActivate {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
private http = inject(HttpClient);
|
||||
private router = inject(Router);
|
||||
|
||||
canActivate(): Observable<boolean> {
|
||||
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
|
||||
map(res => {
|
||||
if (!res.data) {
|
||||
this.router.navigate(['/setup']);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
catchError(() => {
|
||||
this.router.navigate(['/setup']);
|
||||
return of(false);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import { CanActivate, Router } from '@angular/router';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, map } from 'rxjs';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SetupRedirectGuard implements CanActivate {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private router = inject(Router);
|
||||
|
||||
canActivate(): Observable<boolean> {
|
||||
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
|
||||
map(res => {
|
||||
if (!res.data) {
|
||||
this.router.navigate(['/setup']);
|
||||
} else {
|
||||
this.router.navigate(['/dashboard']);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<div class="setup-container">
|
||||
<div class="setup-wrapper">
|
||||
<h1 class="app-title">BookLore</h1>
|
||||
<p-card class="w-96">
|
||||
<ng-template pTemplate="title">
|
||||
<div class="text-center pb-2">Initial Admin Setup</div>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="content">
|
||||
<form class="flex flex-col gap-4" [formGroup]="setupForm" (ngSubmit)="onSubmit()">
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="name">Username</label>
|
||||
<input pInputText id="name" type="text" formControlName="username" required />
|
||||
<small class="text-red-500" *ngIf="setupForm.get('username')?.invalid && setupForm.get('username')?.touched">
|
||||
Username is required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="name">Name</label>
|
||||
<input pInputText id="name" type="text" formControlName="name" required />
|
||||
<small class="text-red-500" *ngIf="setupForm.get('name')?.invalid && setupForm.get('name')?.touched">
|
||||
Name is required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="email">Email</label>
|
||||
<input pInputText id="email" type="email" formControlName="email" required />
|
||||
<small class="text-red-500" *ngIf="setupForm.get('email')?.invalid && setupForm.get('email')?.touched">
|
||||
Valid email is required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="password">Password</label>
|
||||
<p-password fluid id="password" formControlName="password" [feedback]="false" required></p-password>
|
||||
<small class="text-red-500" *ngIf="setupForm.get('password')?.invalid && setupForm.get('password')?.touched">
|
||||
Minimum 6 characters required.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-3 mt-4">
|
||||
<p-button fluid severity="success" type="submit"
|
||||
[label]="loading ? 'Creating…' : 'Create Admin Account'"
|
||||
[disabled]="loading || setupForm.invalid"
|
||||
icon="pi pi-user-plus">
|
||||
</p-button>
|
||||
<p-message *ngIf="error" severity="error" text="{{ error }}"></p-message>
|
||||
<p-message *ngIf="success" severity="success" text="Admin account created! Redirecting…"></p-message>
|
||||
</div>
|
||||
</form>
|
||||
</ng-template>
|
||||
</p-card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
.setup-container {
|
||||
@apply flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-900 via-cyan-600 to-blue-400 relative;
|
||||
}
|
||||
|
||||
.setup-wrapper {
|
||||
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
|
||||
}
|
||||
|
||||
.app-title {
|
||||
@apply text-5xl font-extrabold text-white drop-shadow-lg;
|
||||
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { SetupService } from './setup.service';
|
||||
import { NgIf } from '@angular/common';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { Card } from 'primeng/card';
|
||||
import { PrimeTemplate } from 'primeng/api';
|
||||
import { InputText } from 'primeng/inputtext';
|
||||
import { Password } from 'primeng/password';
|
||||
import { Button } from 'primeng/button';
|
||||
import { Message } from 'primeng/message';
|
||||
|
||||
@Component({
|
||||
selector: 'app-setup',
|
||||
templateUrl: './setup.component.html',
|
||||
styleUrls: ['./setup.component.scss'],
|
||||
standalone: true,
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
NgIf,
|
||||
Card,
|
||||
PrimeTemplate,
|
||||
InputText,
|
||||
Password,
|
||||
Button,
|
||||
Message
|
||||
]
|
||||
})
|
||||
export class SetupComponent {
|
||||
setupForm: FormGroup;
|
||||
loading = false;
|
||||
error: string | null = null;
|
||||
success = false;
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private setupService: SetupService,
|
||||
private router: Router
|
||||
) {
|
||||
this.setupForm = this.fb.group({
|
||||
name: ['', [Validators.required]],
|
||||
username: ['', [Validators.required]],
|
||||
email: ['', [Validators.required, Validators.email]],
|
||||
password: ['', [Validators.required, Validators.minLength(6)]],
|
||||
});
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.setupForm.invalid) return;
|
||||
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
this.setupService.createAdmin(this.setupForm.value).subscribe({
|
||||
next: () => {
|
||||
this.success = true;
|
||||
setTimeout(() => this.router.navigate(['/login']), 1500);
|
||||
},
|
||||
error: (err) => {
|
||||
this.loading = false;
|
||||
this.error =
|
||||
err?.error?.message || 'Failed to create admin user. Try again.';
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {
|
||||
CanActivate,
|
||||
Router,
|
||||
UrlTree
|
||||
} from '@angular/router';
|
||||
import {Observable} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SetupGuard implements CanActivate {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private router = inject(Router);
|
||||
|
||||
canActivate(): Observable<boolean | UrlTree> {
|
||||
return this.http.get<any>(`${this.url}/status`).pipe(
|
||||
map(response => {
|
||||
if (response?.data === true) {
|
||||
return this.router.createUrlTree(['/login']);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
export interface SetupPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SetupService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
createAdmin(payload: SetupPayload): Observable<void> {
|
||||
return this.http.post<void>(this.url, payload);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import {RxStompConfig} from '@stomp/rx-stomp';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
|
||||
export function createRxStompConfig(authService: AuthService): RxStompConfig {
|
||||
return {
|
||||
@@ -9,10 +9,17 @@ export function createRxStompConfig(authService: AuthService): RxStompConfig {
|
||||
heartbeatOutgoing: 20000,
|
||||
reconnectDelay: 200,
|
||||
beforeConnect: (stomp) => {
|
||||
stomp.stompClient.connectHeaders = {'Authorization': `Bearer ${authService.getToken()}`};
|
||||
const oidcToken = authService.getOidcAccessToken();
|
||||
const internalToken = authService.getInternalAccessToken();
|
||||
const token = oidcToken || internalToken;
|
||||
if (token) {
|
||||
stomp.stompClient.connectHeaders = {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
},
|
||||
debug: (msg: string): void => {
|
||||
//console.log(new Date(), msg);
|
||||
// console.log(new Date(), msg);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { RxStomp } from '@stomp/rx-stomp';
|
||||
import {RxStomp, RxStompConfig} from '@stomp/rx-stomp';
|
||||
import { AuthService } from '../../core/service/auth.service';
|
||||
import { createRxStompConfig } from './rx-stomp.config';
|
||||
|
||||
@@ -7,9 +7,14 @@ import { createRxStompConfig } from './rx-stomp.config';
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class RxStompService extends RxStomp {
|
||||
|
||||
constructor(private authService: AuthService) {
|
||||
super();
|
||||
const stompConfig = createRxStompConfig(this.authService);
|
||||
this.configure(stompConfig);
|
||||
}
|
||||
|
||||
public updateConfig(config: RxStompConfig) {
|
||||
this.configure(config);
|
||||
}
|
||||
}
|
||||
|
||||
+13
-5
@@ -12,11 +12,22 @@ import {AppComponent} from './app/app.component';
|
||||
import Aura from '@primeng/themes/aura';
|
||||
import {routes} from './app/app.routes';
|
||||
import {AuthInterceptorService} from './app/auth-interceptor.service';
|
||||
import {AuthService} from './app/core/service/auth.service';
|
||||
import {AuthService, websocketInitializer} from './app/core/service/auth.service';
|
||||
import {provideOAuthClient} from 'angular-oauth2-oidc';
|
||||
import {APP_INITIALIZER, provideAppInitializer} from '@angular/core';
|
||||
import {initializeAuthFactory} from './app/auth-initializer';
|
||||
|
||||
bootstrapApplication(AppComponent, {
|
||||
providers: [
|
||||
{
|
||||
provide: APP_INITIALIZER,
|
||||
useFactory: websocketInitializer,
|
||||
deps: [AuthService],
|
||||
multi: true
|
||||
},
|
||||
provideHttpClient(withInterceptors([AuthInterceptorService])),
|
||||
provideOAuthClient(),
|
||||
provideAppInitializer(initializeAuthFactory()),
|
||||
provideRouter(routes),
|
||||
DialogService,
|
||||
MessageService,
|
||||
@@ -33,10 +44,7 @@ bootstrapApplication(AppComponent, {
|
||||
provideAnimationsAsync(),
|
||||
providePrimeNG({
|
||||
theme: {
|
||||
preset: Aura,
|
||||
options: {
|
||||
darkModeSelector: '.p-dark'
|
||||
}
|
||||
preset: Aura
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user