feat: Add custom font support for EPUB reader (#2120)
* feat: Add custom font support for EPUB reader This commit introduces the ability to manage and use custom fonts in the EPUB reader. Key changes include: **Backend:** - Added `CustomFontService` for handling custom font operations. - Introduced `CustomFontController` for API endpoints. - Created `CustomFontEntity` and `CustomFontRepository` for database interactions. - Added `CustomFontMapper` and `CustomFontDto` for data transformation. - Updated `SecurityConfig` to include JWT filter for custom fonts. - Enhanced `GlobalExceptionHandler` to handle custom font-related exceptions. - Added database migrations: - `V83__Create_Custom_Font_Table.sql` for creating the custom font table. - `V84__Add_Custom_Font_To_Epub_Preferences.sql` for integrating custom fonts with EPUB preferences. **Frontend:** - Added `CustomFontsComponent` and `FontUploadDialogComponent` for managing custom fonts in the settings UI. - Updated `EpubReaderPreferencesComponent` to include custom font options. - Introduced `CustomFontService` and `CustomFontModel` for frontend logic and data handling. - Enhanced `SettingsComponent` to integrate custom font management. **Other Changes:** - Updated `EpubViewerPreferences` and `EpubViewerPreferencesEntity` to support custom fonts. - Modified existing components and services to accommodate the new feature. This feature enhances the user experience by allowing personalized font choices for EPUB reading. * fix: custom font does not apply after page layout changed * fix: duplicate API call when change EPUB global settings * fix: some code review items, extract shared filter logic and improve UX - Extract AbstractQueryParameterJwtFilter base class to reduce code duplication between CoverJwtFilter and CustomFontJwtFilter - Remove cssIdentifier and fontUrl fields from CustomFont model (no longer needed) - Add font name sanitization to prevent XSS and ensure data integrity - Improve error handling in CustomFontService with proper APIException usage - Replace RuntimeException handler with specific IllegalStateException and UnsupportedOperationException handlers in GlobalExceptionHandler - Add skeleton loading states for font previews and font dropdowns - Improve font loading state management in epub-reader component - Create shared custom-font.util.ts for dropdown population logic - Use reactive font$ subscription for real-time font updates in preferences - Make DB migrations idempotent with IF NOT EXISTS clauses - Optimize font file validation to read only header bytes instead of entire file * chore: re-version migration scripts * Fix: Kobo sync missing book covers (v1.16.4) (#2147) Co-authored-by: acx10 <acx10@users.noreply.github.com> * Fix: correctly update book cover hash on metadata refresh (#2149) Co-authored-by: acx10 <acx10@users.noreply.github.com> * Introduce Vitest as the frontend Angular testing framework for Booklore (#2150) Co-authored-by: acx10 <acx10@users.noreply.github.com> * Add Vitest frontend tests to CI with JUnit reporting and coverage (#2151) Co-authored-by: acx10 <acx10@users.noreply.github.com> * Update PR template to capture frontend test details * Add instructions for running Angular frontend tests --------- Co-authored-by: ACX <8075870+acx10@users.noreply.github.com> Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+16
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.config.security.filter.CoverJwtFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.CustomFontJwtFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.KoboAuthFilter;
|
||||
import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter;
|
||||
@@ -133,6 +134,21 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
@Order(5)
|
||||
public SecurityFilterChain customFontSecurityChain(HttpSecurity http, CustomFontJwtFilter customFontJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/custom-fonts/*/file")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(customFontJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(6)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
|
||||
if (appProperties.getSwagger().isEnabled()) {
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
|
||||
@AllArgsConstructor
|
||||
public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
protected final JwtUtils jwtUtils;
|
||||
protected final UserRepository userRepository;
|
||||
protected final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
protected final AppSettingService appSettingService;
|
||||
protected final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
// Extract token from query parameter (not from Authorization header)
|
||||
String token = request.getParameter("token");
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateLocalUser(token, request);
|
||||
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
authenticateOidcUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
protected 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);
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
protected void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
|
||||
var processor = dynamicOidcJwtProcessor.getProcessor();
|
||||
var claimsSet = processor.process(token, null);
|
||||
|
||||
if (claimsSet.getExpirationTime() == null ||
|
||||
claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
|
||||
throw new RuntimeException("OIDC token expired or invalid");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
String username = claimsSet.getStringClaim(claimMapping.getUsername());
|
||||
BookLoreUserEntity entity = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+9
-74
@@ -2,92 +2,27 @@ package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
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.time.Instant;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class CoverJwtFilter extends OncePerRequestFilter {
|
||||
public class CoverJwtFilter extends AbstractQueryParameterJwtFilter {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final AppSettingService appSettingService;
|
||||
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
public CoverJwtFilter(
|
||||
JwtUtils jwtUtils,
|
||||
UserRepository userRepository,
|
||||
BookLoreUserTransformer bookLoreUserTransformer,
|
||||
AppSettingService appSettingService,
|
||||
DynamicOidcJwtProcessor dynamicOidcJwtProcessor) {
|
||||
super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !path.startsWith("/api/v1/media/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
String token = request.getParameter("token");
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateLocalUser(token, request);
|
||||
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
authenticateOidcUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
|
||||
var processor = dynamicOidcJwtProcessor.getProcessor();
|
||||
var claimsSet = processor.process(token, null);
|
||||
|
||||
if (claimsSet.getExpirationTime() == null || claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
|
||||
throw new RuntimeException("OIDC token expired or invalid");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
String username = claimsSet.getStringClaim(claimMapping.getUsername());
|
||||
BookLoreUserEntity entity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CustomFontJwtFilter extends AbstractQueryParameterJwtFilter {
|
||||
|
||||
public CustomFontJwtFilter(
|
||||
JwtUtils jwtUtils,
|
||||
UserRepository userRepository,
|
||||
BookLoreUserTransformer bookLoreUserTransformer,
|
||||
AppSettingService appSettingService,
|
||||
DynamicOidcJwtProcessor dynamicOidcJwtProcessor) {
|
||||
super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
// Only filter requests to custom font file endpoints (e.g., /api/v1/custom-fonts/123/file)
|
||||
return !(path.startsWith("/api/v1/custom-fonts/") && path.endsWith("/file"));
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.service.customfont.CustomFontService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "Custom Fonts", description = "Endpoints for managing custom fonts for EPUB reader")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/custom-fonts")
|
||||
@RequiredArgsConstructor
|
||||
public class CustomFontController {
|
||||
|
||||
private final CustomFontService customFontService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Operation(summary = "Upload a custom font", description = "Upload a custom font file (.ttf, .otf, .woff, .woff2) for the authenticated user")
|
||||
@ApiResponse(responseCode = "200", description = "Font uploaded successfully")
|
||||
@ApiResponse(responseCode = "400", description = "Invalid file or quota exceeded")
|
||||
@PostMapping("/upload")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<CustomFontDto> uploadFont(
|
||||
@Parameter(description = "Font file (.ttf, .otf, .woff, .woff2)") @RequestParam("file") MultipartFile file,
|
||||
@Parameter(description = "Font display name") @RequestParam(value = "fontName", required = false) String fontName) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
CustomFontDto fontDto = customFontService.uploadFont(file, fontName, user.getId());
|
||||
return ResponseEntity.ok(fontDto);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get all user's custom fonts", description = "Retrieve all custom fonts for the authenticated user")
|
||||
@ApiResponse(responseCode = "200", description = "Fonts retrieved successfully")
|
||||
@GetMapping
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<List<CustomFontDto>> getUserFonts() {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
List<CustomFontDto> fonts = customFontService.getUserFonts(user.getId());
|
||||
return ResponseEntity.ok(fonts);
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete a custom font", description = "Delete a custom font file and database record")
|
||||
@ApiResponse(responseCode = "200", description = "Font deleted successfully")
|
||||
@ApiResponse(responseCode = "404", description = "Font not found or access denied")
|
||||
@DeleteMapping("/{fontId}")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<Void> deleteFont(@PathVariable Long fontId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
customFontService.deleteFont(fontId, user.getId());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Get font file", description = "Retrieve the font file for use in the browser")
|
||||
@ApiResponse(responseCode = "200", description = "Font file retrieved successfully")
|
||||
@ApiResponse(responseCode = "404", description = "Font not found or access denied")
|
||||
@GetMapping("/{fontId}/file")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<Resource> getFontFile(@PathVariable Long fontId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Resource resource = customFontService.getFontFile(fontId, user.getId());
|
||||
|
||||
// Get font format to set correct content type
|
||||
var format = customFontService.getFontFormat(fontId, user.getId());
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(format.getMimeType()))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline")
|
||||
.body(resource);
|
||||
}
|
||||
}
|
||||
+21
@@ -93,6 +93,27 @@ public class GlobalExceptionHandler {
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<ErrorResponse> handleIllegalArgumentException(IllegalArgumentException ex) {
|
||||
log.warn("Illegal argument: {}", ex.getMessage());
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalStateException.class)
|
||||
public ResponseEntity<ErrorResponse> handleIllegalStateException(IllegalStateException ex) {
|
||||
log.error("Illegal state: {}", ex.getMessage(), ex);
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnsupportedOperationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnsupportedOperationException(UnsupportedOperationException ex) {
|
||||
log.error("Unsupported operation: {}", ex.getMessage(), ex);
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), ex.getMessage());
|
||||
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
|
||||
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface CustomFontMapper {
|
||||
|
||||
CustomFontDto toDto(CustomFontEntity entity);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CustomFontDto {
|
||||
private Long id;
|
||||
private String fontName;
|
||||
private String originalFileName;
|
||||
private FontFormat format;
|
||||
private Long fileSize;
|
||||
private LocalDateTime uploadedAt;
|
||||
}
|
||||
+1
@@ -14,4 +14,5 @@ public class EpubViewerPreferences {
|
||||
private Integer fontSize;
|
||||
private Float letterSpacing;
|
||||
private Float lineHeight;
|
||||
private Long customFontId;
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "custom_font")
|
||||
public class CustomFontEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@Column(name = "font_name", nullable = false)
|
||||
private String fontName;
|
||||
|
||||
@Column(name = "file_name", nullable = false, unique = true)
|
||||
private String fileName;
|
||||
|
||||
@Column(name = "original_file_name", nullable = false)
|
||||
private String originalFileName;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "format", nullable = false)
|
||||
private FontFormat format;
|
||||
|
||||
@Column(name = "file_size", nullable = false)
|
||||
private Long fileSize;
|
||||
|
||||
@Column(name = "uploaded_at", nullable = false)
|
||||
private LocalDateTime uploadedAt;
|
||||
}
|
||||
+3
@@ -44,4 +44,7 @@ public class EpubViewerPreferencesEntity {
|
||||
|
||||
@Column(name = "spread")
|
||||
private String spread;
|
||||
|
||||
@Column(name = "custom_font_id")
|
||||
private Long customFontId;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public enum FontFormat {
|
||||
TTF("font/ttf", ".ttf"),
|
||||
OTF("font/otf", ".otf"),
|
||||
WOFF("font/woff", ".woff"),
|
||||
WOFF2("font/woff2", ".woff2");
|
||||
|
||||
private final String mimeType;
|
||||
private final String extension;
|
||||
|
||||
FontFormat(String mimeType, String extension) {
|
||||
this.mimeType = mimeType;
|
||||
this.extension = extension;
|
||||
}
|
||||
|
||||
public static FontFormat fromExtension(String extension) {
|
||||
String normalizedExt = extension.toLowerCase();
|
||||
if (!normalizedExt.startsWith(".")) {
|
||||
normalizedExt = "." + normalizedExt;
|
||||
}
|
||||
for (FontFormat format : values()) {
|
||||
if (format.extension.equals(normalizedExt)) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported font format: " + extension);
|
||||
}
|
||||
|
||||
public static FontFormat fromMimeType(String mimeType) {
|
||||
for (FontFormat format : values()) {
|
||||
if (format.mimeType.equals(mimeType)) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported MIME type: " + mimeType);
|
||||
}
|
||||
|
||||
public static boolean isSupportedExtension(String extension) {
|
||||
String normalizedExt = extension.toLowerCase();
|
||||
if (!normalizedExt.startsWith(".")) {
|
||||
normalizedExt = "." + normalizedExt;
|
||||
}
|
||||
for (FontFormat format : values()) {
|
||||
if (format.extension.equals(normalizedExt)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface CustomFontRepository extends JpaRepository<CustomFontEntity, Long> {
|
||||
|
||||
List<CustomFontEntity> findByUserId(Long userId);
|
||||
|
||||
int countByUserId(Long userId);
|
||||
|
||||
Optional<CustomFontEntity> findByIdAndUserId(Long id, Long userId);
|
||||
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package com.adityachandel.booklore.service.customfont;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.mapper.CustomFontMapper;
|
||||
import com.adityachandel.booklore.model.dto.CustomFontDto;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CustomFontEntity;
|
||||
import com.adityachandel.booklore.model.enums.FontFormat;
|
||||
import com.adityachandel.booklore.repository.CustomFontRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CustomFontService {
|
||||
|
||||
private final CustomFontRepository customFontRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final CustomFontMapper customFontMapper;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
private static final int MAX_FONTS_PER_USER = 10;
|
||||
private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024;
|
||||
private static final String CUSTOM_FONTS_DIR = "custom-fonts";
|
||||
private static final int MAX_FONT_NAME_LENGTH = 100;
|
||||
|
||||
@Transactional
|
||||
public CustomFontDto uploadFont(MultipartFile file, String fontName, Long userId) {
|
||||
Path fontPath = null;
|
||||
CustomFontEntity savedEntity = null;
|
||||
|
||||
try {
|
||||
validateFontUpload(file, userId);
|
||||
|
||||
BookLoreUserEntity user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
if (originalFilename == null || originalFilename.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid file name");
|
||||
}
|
||||
|
||||
String extension = getFileExtension(originalFilename);
|
||||
FontFormat format = FontFormat.fromExtension(extension);
|
||||
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
String fileName = String.format("user_%d_font_%s%s", userId, uuid, format.getExtension());
|
||||
|
||||
Path fontDir = getFontDirectory(userId);
|
||||
Files.createDirectories(fontDir);
|
||||
fontPath = fontDir.resolve(fileName);
|
||||
|
||||
validatePath(fontPath, fontDir);
|
||||
|
||||
file.transferTo(fontPath.toFile());
|
||||
|
||||
validateFontMagicBytes(fontPath, format);
|
||||
|
||||
String sanitizedFontName = sanitizeFontName(fontName, originalFilename);
|
||||
|
||||
CustomFontEntity entity = CustomFontEntity.builder()
|
||||
.user(user)
|
||||
.fontName(sanitizedFontName)
|
||||
.fileName(fileName)
|
||||
.originalFileName(originalFilename)
|
||||
.format(format)
|
||||
.fileSize(file.getSize())
|
||||
.uploadedAt(LocalDateTime.now())
|
||||
.build();
|
||||
|
||||
savedEntity = customFontRepository.save(entity);
|
||||
log.info("Font uploaded successfully for user {}: {} ({})", userId, sanitizedFontName, fileName);
|
||||
|
||||
return customFontMapper.toDto(savedEntity);
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to upload font for user {}: {}", userId, e.getMessage(), e);
|
||||
throw new APIException("Failed to upload font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
} finally {
|
||||
if (fontPath != null && savedEntity == null) {
|
||||
try {
|
||||
Files.deleteIfExists(fontPath);
|
||||
log.debug("Cleaned up orphaned font file after upload failure: {}", fontPath);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to cleanup orphaned font file: {}", fontPath, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<CustomFontDto> getUserFonts(Long userId) {
|
||||
List<CustomFontEntity> fonts = customFontRepository.findByUserId(userId);
|
||||
return fonts.stream()
|
||||
.map(customFontMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteFont(Long fontId, Long userId) {
|
||||
CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Font not found or access denied"));
|
||||
|
||||
IOException fileDeleteException = null;
|
||||
|
||||
try {
|
||||
Path fontDir = getFontDirectory(userId);
|
||||
Path fontPath = fontDir.resolve(font.getFileName());
|
||||
|
||||
validatePath(fontPath, fontDir);
|
||||
|
||||
Files.deleteIfExists(fontPath);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete font file for user {}: {}", userId, e.getMessage(), e);
|
||||
fileDeleteException = e;
|
||||
}
|
||||
|
||||
try {
|
||||
customFontRepository.delete(font);
|
||||
log.info("Font deleted successfully for user {}: {} ({})", userId, font.getFontName(), font.getFileName());
|
||||
} catch (Exception dbException) {
|
||||
log.error("Failed to delete font from database for user {}: {}", userId, dbException.getMessage(), dbException);
|
||||
|
||||
if (fileDeleteException != null) {
|
||||
log.error("Additionally, file deletion also failed for font: {}", font.getFileName(), fileDeleteException);
|
||||
}
|
||||
|
||||
throw new APIException("Failed to delete font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
if (fileDeleteException != null) {
|
||||
log.warn("Font deleted from database but failed to delete file for user {}: {}", userId, font.getFileName(), fileDeleteException);
|
||||
}
|
||||
}
|
||||
|
||||
public Resource getFontFile(Long fontId, Long userId) {
|
||||
CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Font not found or access denied"));
|
||||
|
||||
Path fontDir = getFontDirectory(userId);
|
||||
Path fontPath = fontDir.resolve(font.getFileName());
|
||||
|
||||
try {
|
||||
validatePath(fontPath, fontDir);
|
||||
} catch (IOException e) {
|
||||
log.error("Invalid font path for user {}: {}", userId, fontPath, e);
|
||||
throw new IllegalArgumentException("Invalid font file path");
|
||||
}
|
||||
|
||||
File fontFile = fontPath.toFile();
|
||||
|
||||
if (!fontFile.exists()) {
|
||||
throw new IllegalArgumentException("Font file not found on disk");
|
||||
}
|
||||
|
||||
return new FileSystemResource(fontFile);
|
||||
}
|
||||
|
||||
public FontFormat getFontFormat(Long fontId, Long userId) {
|
||||
CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Font not found or access denied"));
|
||||
return font.getFormat();
|
||||
}
|
||||
|
||||
private void validateFontUpload(MultipartFile file, Long userId) {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("File is empty");
|
||||
}
|
||||
|
||||
if (file.getSize() > MAX_FILE_SIZE_BYTES) {
|
||||
throw new IllegalArgumentException("File size exceeds maximum limit of 5MB");
|
||||
}
|
||||
|
||||
int currentFontCount = customFontRepository.countByUserId(userId);
|
||||
if (currentFontCount >= MAX_FONTS_PER_USER) {
|
||||
throw new IllegalArgumentException(String.format("Font limit exceeded. Maximum %d fonts per user allowed", MAX_FONTS_PER_USER));
|
||||
}
|
||||
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
if (originalFilename == null || originalFilename.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid file name");
|
||||
}
|
||||
|
||||
String extension = getFileExtension(originalFilename);
|
||||
if (!FontFormat.isSupportedExtension(extension)) {
|
||||
throw new IllegalArgumentException("Unsupported font format. Allowed formats: .ttf, .otf, .woff, .woff2");
|
||||
}
|
||||
|
||||
String contentType = file.getContentType();
|
||||
if (contentType != null && !isSupportedMimeType(contentType)) {
|
||||
log.warn("Potentially invalid MIME type for font: {}", contentType);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSupportedMimeType(String mimeType) {
|
||||
return mimeType.equals("font/ttf") ||
|
||||
mimeType.equals("font/otf") ||
|
||||
mimeType.equals("font/woff") ||
|
||||
mimeType.equals("font/woff2") ||
|
||||
mimeType.equals("application/x-font-ttf") ||
|
||||
mimeType.equals("application/x-font-opentype") ||
|
||||
mimeType.equals("application/font-woff") ||
|
||||
mimeType.equals("application/font-woff2") ||
|
||||
mimeType.equals("application/octet-stream");
|
||||
}
|
||||
|
||||
private String getFileExtension(String filename) {
|
||||
int lastDotIndex = filename.lastIndexOf('.');
|
||||
if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
|
||||
throw new IllegalArgumentException("File has no extension");
|
||||
}
|
||||
return filename.substring(lastDotIndex);
|
||||
}
|
||||
|
||||
private Path getFontDirectory(Long userId) {
|
||||
return Paths.get(appProperties.getPathConfig(), CUSTOM_FONTS_DIR, String.valueOf(userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that the resolved path stays within the expected parent directory
|
||||
* to prevent directory traversal attacks.
|
||||
*/
|
||||
private void validatePath(Path resolvedPath, Path expectedParent) throws IOException {
|
||||
Path normalizedPath = resolvedPath.toAbsolutePath().normalize();
|
||||
Path normalizedParent = expectedParent.toAbsolutePath().normalize();
|
||||
|
||||
if (!normalizedPath.startsWith(normalizedParent)) {
|
||||
log.error("Path traversal attempt detected: {} does not start with {}", normalizedPath, normalizedParent);
|
||||
throw new IOException("Invalid file path: path traversal detected");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates font file format by checking magic bytes.
|
||||
* Prevents malicious files from being uploaded with font extensions.
|
||||
*/
|
||||
private void validateFontMagicBytes(Path fontPath, FontFormat expectedFormat) throws IOException {
|
||||
byte[] header = new byte[4];
|
||||
|
||||
try (var inputStream = Files.newInputStream(fontPath)) {
|
||||
int bytesRead = inputStream.read(header);
|
||||
|
||||
if (bytesRead < 4) {
|
||||
throw new IllegalArgumentException("Invalid font file: file too small");
|
||||
}
|
||||
}
|
||||
|
||||
boolean isValid = false;
|
||||
String detectedFormat = "Unknown";
|
||||
|
||||
// Check TTF signature: 0x00 0x01 0x00 0x00 or "true" (0x74 0x72 0x75 0x65)
|
||||
if ((header[0] == 0x00 && header[1] == 0x01 && header[2] == 0x00 && header[3] == 0x00) ||
|
||||
(header[0] == 0x74 && header[1] == 0x72 && header[2] == 0x75 && header[3] == 0x65)) {
|
||||
isValid = (expectedFormat == FontFormat.TTF);
|
||||
detectedFormat = "TTF";
|
||||
}
|
||||
// Check OTF signature: "OTTO" (0x4F 0x54 0x54 0x4F)
|
||||
else if (header[0] == 0x4F && header[1] == 0x54 && header[2] == 0x54 && header[3] == 0x4F) {
|
||||
isValid = (expectedFormat == FontFormat.OTF);
|
||||
detectedFormat = "OTF";
|
||||
}
|
||||
// Check WOFF signature: "wOFF" (0x77 0x4F 0x46 0x46)
|
||||
else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x46) {
|
||||
isValid = (expectedFormat == FontFormat.WOFF);
|
||||
detectedFormat = "WOFF";
|
||||
}
|
||||
// Check WOFF2 signature: "wOF2" (0x77 0x4F 0x46 0x32)
|
||||
else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x32) {
|
||||
isValid = (expectedFormat == FontFormat.WOFF2);
|
||||
detectedFormat = "WOFF2";
|
||||
}
|
||||
|
||||
if (!isValid) {
|
||||
log.error("Font file magic bytes validation failed. Expected: {}, Detected: {}", expectedFormat, detectedFormat);
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Invalid font file format. File appears to be %s but extension indicates %s",
|
||||
detectedFormat, expectedFormat)
|
||||
);
|
||||
}
|
||||
|
||||
log.debug("Font file magic bytes validated successfully: {}", detectedFormat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes font name to prevent XSS and ensure data integrity.
|
||||
*/
|
||||
private String sanitizeFontName(String fontName, String fallbackName) {
|
||||
if (fontName == null || fontName.trim().isEmpty()) {
|
||||
fontName = fallbackName;
|
||||
}
|
||||
|
||||
String sanitized = fontName.trim();
|
||||
|
||||
sanitized = sanitized.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
|
||||
|
||||
sanitized = sanitized.replaceAll("<[^>]*>", "");
|
||||
sanitized = sanitized.replaceAll("[<>\"'`]", "");
|
||||
|
||||
sanitized = sanitized.replaceAll("\\s+", " ");
|
||||
|
||||
sanitized = sanitized.trim();
|
||||
|
||||
if (sanitized.isEmpty()) {
|
||||
sanitized = fallbackName;
|
||||
}
|
||||
|
||||
if (sanitized.length() > MAX_FONT_NAME_LENGTH) {
|
||||
sanitized = sanitized.substring(0, MAX_FONT_NAME_LENGTH).trim();
|
||||
}
|
||||
|
||||
return sanitized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE IF NOT EXISTS custom_font (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
font_name VARCHAR(255) NOT NULL,
|
||||
file_name VARCHAR(255) NOT NULL UNIQUE,
|
||||
original_file_name VARCHAR(255) NOT NULL,
|
||||
format VARCHAR(10) NOT NULL,
|
||||
file_size BIGINT NOT NULL,
|
||||
uploaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
INDEX idx_user_id (user_id)
|
||||
);
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE epub_viewer_preference ADD COLUMN IF NOT EXISTS custom_font_id BIGINT NULL;
|
||||
ALTER TABLE epub_viewer_preference ADD FOREIGN KEY (custom_font_id) REFERENCES custom_font(id) ON DELETE SET NULL;
|
||||
Reference in New Issue
Block a user