Introduce @CheckBookAccess and @CheckLibraryAccess annotations for endpoint-level access control

This commit is contained in:
aditya.chandel
2025-06-17 18:01:09 -06:00
parent f43c71b1f1
commit 8439d31d1a
14 changed files with 196 additions and 5 deletions
@@ -35,6 +35,11 @@ public class SecurityUtil {
return user != null && user.getPermissions().isCanUpload();
}
public boolean canDownload() {
var user = getCurrentUser();
return user != null && user.getPermissions().isCanDownload();
}
public boolean canManipulateLibrary() {
var user = getCurrentUser();
return user != null && user.getPermissions().isCanManipulateLibrary();
@@ -0,0 +1,10 @@
package com.adityachandel.booklore.config.security.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckBookAccess {
String bookIdParam();
}
@@ -0,0 +1,11 @@
package com.adityachandel.booklore.config.security.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckLibraryAccess {
String libraryIdParam();
}
@@ -0,0 +1,70 @@
package com.adityachandel.booklore.config.security.aspect;
import com.adityachandel.booklore.config.security.AuthenticationService;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Objects;
@Aspect
@Component
@RequiredArgsConstructor
public class BookAccessAspect {
private final AuthenticationService authenticationService;
private final BookRepository bookRepository;
@Before("@annotation(com.adityachandel.booklore.config.security.annotation.CheckBookAccess)")
public void checkBookAccess(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
CheckBookAccess annotation = method.getAnnotation(CheckBookAccess.class);
if (annotation == null) {
return;
}
Long bookId = extractBookId(joinPoint.getArgs(), methodSignature.getParameterNames(), annotation.bookIdParam());
if (bookId == null) {
throw ApiError.BAD_REQUEST.createException("Missing or invalid book ID in method parameters.");
}
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookLoreUser user = authenticationService.getAuthenticatedUser();
if (user.getPermissions().isAdmin()) {
return;
}
boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(library -> library.getId().equals(bookEntity.getLibrary().getId()));
if (!hasAccess) {
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
}
}
private Long extractBookId(Object[] args, String[] paramNames, String targetParamName) {
for (int i = 0; i < paramNames.length; i++) {
if (Objects.equals(paramNames[i], targetParamName)) {
Object arg = args[i];
if (arg instanceof Long) {
return (Long) arg;
} else if (arg instanceof String str && str.matches("\\d+")) {
return Long.valueOf(str);
}
}
}
return null;
}
}
@@ -0,0 +1,62 @@
package com.adityachandel.booklore.config.security.aspect;
import com.adityachandel.booklore.config.security.AuthenticationService;
import com.adityachandel.booklore.config.security.annotation.CheckLibraryAccess;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Objects;
@Aspect
@Component
@RequiredArgsConstructor
public class LibraryAccessAspect {
private final AuthenticationService authenticationService;
@Before("@annotation(com.adityachandel.booklore.config.security.annotation.CheckLibraryAccess)")
public void checkLibraryAccess(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
CheckLibraryAccess annotation = method.getAnnotation(CheckLibraryAccess.class);
if (annotation == null) return;
Long libraryId = extractLibraryId(methodSignature.getParameterNames(), joinPoint.getArgs(), annotation.libraryIdParam());
if (libraryId == null) {
throw ApiError.BAD_REQUEST.createException("Library ID not found in method parameters.");
}
BookLoreUser user = authenticationService.getAuthenticatedUser();
if (user.getPermissions().isAdmin()) return;
boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(lib -> lib.getId().equals(libraryId));
if (!hasAccess) {
throw ApiError.FORBIDDEN.createException("You are not authorized to access this library.");
}
}
private Long extractLibraryId(String[] paramNames, Object[] args, String targetParam) {
for (int i = 0; i < paramNames.length; i++) {
if (Objects.equals(paramNames[i], targetParam)) {
Object arg = args[i];
if (arg instanceof Long) {
return (Long) arg;
} else if (arg instanceof String str && str.matches("\\d+")) {
return Long.parseLong(str);
}
}
}
return null;
}
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookRecommendation;
import com.adityachandel.booklore.model.dto.BookViewerSettings;
@@ -15,6 +16,7 @@ import lombok.AllArgsConstructor;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@@ -35,6 +37,7 @@ public class BookController {
}
@GetMapping("/{bookId}")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Book> getBook(@PathVariable long bookId, @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
return ResponseEntity.ok(bookService.getBook(bookId, withDescription));
}
@@ -54,21 +57,26 @@ public class BookController {
}
@GetMapping("/{bookId}/content")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
return bookService.getBookContent(bookId);
}
@GetMapping("/{bookId}/download")
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
return bookService.downloadBook(bookId);
}
@GetMapping("/{bookId}/viewer-setting")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
}
@PutMapping("/{bookId}/viewer-setting")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSettings bookViewerSettings, @PathVariable long bookId) {
bookService.updateBookViewerSetting(bookId, bookViewerSettings);
return ResponseEntity.noContent().build();
@@ -86,6 +94,7 @@ public class BookController {
}
@GetMapping("/{id}/recommendations")
@CheckBookAccess(bookIdParam = "id")
public ResponseEntity<List<BookRecommendation>> getRecommendations(@PathVariable Long id, @RequestParam(defaultValue = "25") @Max(25) @Min(1) int limit) {
return ResponseEntity.ok(bookRecommendationService.getRecommendations(id, limit));
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
@@ -16,11 +17,13 @@ public class CbxReaderController {
private final CbxReaderService cbxReaderService;
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/pages")
public List<Integer> listPages(@PathVariable Long bookId) {
return cbxReaderService.getAvailablePages(bookId);
}
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/pages/{pageNumber}")
public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
@@ -20,7 +20,7 @@ public class FileUploadController {
private final FileUploadService fileUploadService;
@PreAuthorize("@securityUtil.canUpload()")
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
if (file.isEmpty()) {
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckLibraryAccess;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
@@ -24,6 +25,7 @@ public class LibraryController {
}
@GetMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<Library> getLibrary(@PathVariable long libraryId) {
return ResponseEntity.ok(libraryService.getLibrary(libraryId));
}
@@ -35,12 +37,14 @@ public class LibraryController {
}
@PutMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> updateLibrary(@RequestBody CreateLibraryRequest request, @PathVariable Long libraryId) {
return ResponseEntity.ok(libraryService.updateLibrary(request, libraryId));
}
@DeleteMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId);
@@ -48,17 +52,21 @@ public class LibraryController {
}
@GetMapping("/{libraryId}/book/{bookId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<Book> getBook(@PathVariable long libraryId, @PathVariable long bookId) {
return ResponseEntity.ok(libraryService.getBook(libraryId, bookId));
}
@GetMapping("/{libraryId}/book")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<List<Book>> getBooks(@PathVariable long libraryId) {
List<Book> books = libraryService.getBooks(libraryId);
return ResponseEntity.ok(books);
}
@PutMapping("/{libraryId}/refresh")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<?> rescanLibrary(@PathVariable long libraryId) {
libraryService.rescanLibrary(libraryId);
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMetadataMapper;
import com.adityachandel.booklore.model.dto.BookMetadata;
@@ -36,12 +37,14 @@ public class MetadataController {
@PostMapping("/{bookId}/metadata/prospective")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<List<BookMetadata>> getMetadataList(@RequestBody(required = false) FetchMetadataRequest fetchMetadataRequest, @PathVariable Long bookId) {
return ResponseEntity.ok(bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest));
}
@PutMapping("/{bookId}/metadata")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookMetadata> updateMetadata(@RequestBody BookMetadata setMetadataRequest, @PathVariable long bookId, @RequestParam(defaultValue = "true") boolean mergeCategories) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
bookMetadataUpdater.setBookMetadata(bookEntity, setMetadataRequest, true, mergeCategories);
@@ -59,6 +62,7 @@ public class MetadataController {
@PostMapping("/{bookId}/metadata/cover")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookMetadata> uploadCover(@PathVariable Long bookId, @RequestParam("file") MultipartFile file) {
BookMetadata updatedMetadata = bookMetadataService.handleCoverUpload(bookId, file);
return ResponseEntity.ok(updatedMetadata);
@@ -85,6 +89,7 @@ public class MetadataController {
@PostMapping("/{bookId}/regenerate-cover")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public void regenerateCovers(@PathVariable Long bookId) {
bookMetadataService.regenerateCover(bookId);
}
@@ -98,13 +103,15 @@ public class MetadataController {
@GetMapping("/{bookId}/metadata/restore")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<EpubMetadata> getBackedUpMetadata(@PathVariable Long bookId) throws IOException {
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<EpubMetadata> getBackedUpMetadata(@PathVariable Long bookId) {
EpubMetadata restoredMetadata = bookMetadataService.getBackedUpMetadata(bookId);
return ResponseEntity.ok(restoredMetadata);
}
@PostMapping("/{bookId}/metadata/restore")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<BookMetadata> restoreMetadata(@PathVariable Long bookId) throws IOException {
BookMetadata restoredMetadata = bookMetadataService.restoreMetadataFromBackup(bookId);
return ResponseEntity.ok(restoredMetadata);
@@ -39,6 +39,7 @@ public class OpdsUserController {
return ResponseEntity.noContent().build();
}
@PreAuthorize("@securityUtil.isAdmin()")
@PutMapping("/{userId}/reset-password")
public ResponseEntity<Void> resetPassword(@PathVariable("userId") Long userId, @RequestBody PasswordResetRequest resetRequest) {
opdsUserService.resetPassword(userId, resetRequest.getPassword());
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
@@ -20,11 +21,13 @@ public class PdfReaderController {
private final PdfReaderService pdfReaderService;
@GetMapping("/{bookId}/pages")
@CheckBookAccess(bookIdParam = "bookId")
public List<Integer> listPages(@PathVariable Long bookId) throws IOException {
return pdfReaderService.getAvailablePages(bookId);
}
@GetMapping("/{bookId}/pages/{pageNumber}")
@CheckBookAccess(bookIdParam = "bookId")
public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
@@ -35,6 +35,7 @@ public enum ApiError {
USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "User not found: %s"),
CANNOT_DELETE_ADMIN(HttpStatus.FORBIDDEN, "Admin user cannot be deleted"),
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "%s"),
FORBIDDEN(HttpStatus.FORBIDDEN, "%s"),
BAD_REQUEST(HttpStatus.BAD_REQUEST, "%s"),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "%s"),
PASSWORD_INCORRECT(HttpStatus.BAD_REQUEST, "Incorrect current password"),
@@ -55,9 +55,9 @@ public class BookService {
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean isAdmin = user.getPermissions().isAdmin();
List<Book> books;
if(isAdmin) {
if (isAdmin) {
books = bookQueryService.getAllBooks(includeDescription);
} else{
} else {
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
@@ -91,10 +91,10 @@ public class BookService {
}
}
public BookViewerSettings getBookViewerSetting(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookViewerSettings.BookViewerSettingsBuilder settingsBuilder = BookViewerSettings.builder();
if (bookEntity.getBookType() == BookFileType.EPUB) {
epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
@@ -301,6 +301,7 @@ public class BookService {
public ResponseEntity<Resource> downloadBook(Long bookId) {
try {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
Resource resource = new UrlResource(file.toUri());
return ResponseEntity.ok()