Fix: restrict book query to assigned library IDs for non-admin users

This commit is contained in:
aditya.chandel
2025-06-13 09:55:53 -06:00
committed by Aditya Chandel
parent 1f3e77f775
commit 852373711e
6 changed files with 38 additions and 10 deletions
@@ -36,6 +36,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b")
List<BookEntity> findAllWithMetadata();
@EntityGraph(attributePaths = {"metadata", "shelves"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds")
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
@EntityGraph(attributePaths = {"metadata", "shelves"})
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds")
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
@@ -31,6 +31,19 @@ public class BookQueryService {
.collect(Collectors.toList());
}
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription) {
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
return books.stream()
.map(book -> {
Book dto = bookMapperV2.toDTO(book);
if (!includeDescription && dto.getMetadata() != null) {
dto.getMetadata().setDescription(null);
}
return dto;
})
.collect(Collectors.toList());
}
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
return bookRepository.findAllWithMetadataByIds(bookIds);
}
@@ -53,7 +53,16 @@ public class BookService {
public List<Book> getBookDTOs(boolean includeDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> books = bookQueryService.getAllBooks(includeDescription);
boolean isAdmin = user.getPermissions().isAdmin();
List<Book> books;
if(isAdmin) {
books = bookQueryService.getAllBooks(includeDescription);
} else{
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
books = bookQueryService.getAllBooksByLibraryIds(libraryIds, includeDescription);
}
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(user.getId(), books.stream().map(Book::getId).collect(Collectors.toSet()));
books.forEach(book -> {
UserBookProgressEntity progress = progressMap.get(book.getId());