WIP: Permissions hardening
This commit is contained in:
+1
-2
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component("securityUtil")
|
||||
public class SecurityUtil {
|
||||
|
||||
private final ShelfRepository shelfRepository;
|
||||
|
||||
public boolean isAdmin() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isAdmin();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean canUpload() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanUpload();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean canManipulateLibrary() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanManipulateLibrary();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean canEditMetadata() {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isCanEditMetadata();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean canViewUserProfile(Long userId) {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return user.getPermissions().isAdmin() || user.getId().equals(userId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isShelfOwner(Long shelfId) {
|
||||
var authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.getPrincipal() instanceof BookLoreUser user) {
|
||||
return shelfRepository.findById(shelfId)
|
||||
.map(shelf -> shelf.getUser().getId().equals(user.getId()))
|
||||
.orElse(false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.service.UserService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -21,6 +22,7 @@ public class AuthController {
|
||||
private final UserService userService;
|
||||
|
||||
@PostMapping("/register")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<Map<String, String>> registerUser(@RequestBody @Valid UserCreateRequest userCreateRequest) {
|
||||
return userService.registerUser(userCreateRequest);
|
||||
}
|
||||
|
||||
+2
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.service.FileUploadService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@@ -17,6 +18,7 @@ public class FileUploadController {
|
||||
|
||||
private final FileUploadService fileUploadService;
|
||||
|
||||
@PreAuthorize("@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) {
|
||||
if (file.isEmpty()) {
|
||||
|
||||
+7
-2
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.service.LibraryService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -28,16 +29,19 @@ public class LibraryController {
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Library> createLibrary(@RequestBody CreateLibraryRequest request) {
|
||||
return ResponseEntity.ok(libraryService.createLibrary(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{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}")
|
||||
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
|
||||
libraryService.deleteLibrary(libraryId);
|
||||
return ResponseEntity.noContent().build();
|
||||
@@ -55,8 +59,9 @@ public class LibraryController {
|
||||
}
|
||||
|
||||
@PutMapping("/{libraryId}/refresh")
|
||||
public ResponseEntity<?> refreshLibrary(@PathVariable long libraryId) {
|
||||
libraryService.refreshLibrary(libraryId);
|
||||
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<?> rescanLibrary(@PathVariable long libraryId) {
|
||||
libraryService.rescanLibrary(libraryId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+6
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.service.BookMetadataUpdater;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@@ -27,11 +28,13 @@ public class MetadataController {
|
||||
private BookMetadataMapper bookMetadataMapper;
|
||||
|
||||
@PostMapping("/{bookId}/metadata/prospective")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
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()")
|
||||
public ResponseEntity<BookMetadata> updateMetadata(
|
||||
@RequestBody BookMetadata setMetadataRequest, @PathVariable long bookId,
|
||||
@RequestParam(defaultValue = "true") boolean mergeCategories) {
|
||||
@@ -41,18 +44,21 @@ public class MetadataController {
|
||||
}
|
||||
|
||||
@PutMapping(path = "/metadata/refresh")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<String> scheduleRefreshV2(@Validated @RequestBody MetadataRefreshRequest request) {
|
||||
jobSchedulerService.scheduleMetadataRefresh(request);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PostMapping("/{bookId}/metadata/cover")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookMetadata> uploadCover(@PathVariable Long bookId, @RequestParam("file") MultipartFile file) {
|
||||
BookMetadata updatedMetadata = bookMetadataService.handleCoverUpload(bookId, file);
|
||||
return ResponseEntity.ok(updatedMetadata);
|
||||
}
|
||||
|
||||
@PutMapping("/{bookId}/metadata/lock")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookMetadata> updateFieldLockState(@RequestBody FieldLockRequest request) {
|
||||
long bookId = request.getBookId();
|
||||
String field = request.getField();
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.PathService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@@ -17,6 +18,7 @@ public class PathController {
|
||||
private PathService pathService;
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()")
|
||||
public List<String> getFolders(@RequestParam String path) {
|
||||
return pathService.getFoldersAtPath(path);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -26,6 +27,7 @@ public class ShelfController {
|
||||
}
|
||||
|
||||
@GetMapping("/{shelfId}")
|
||||
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
|
||||
public ResponseEntity<Shelf> getShelf(@PathVariable Long shelfId) {
|
||||
return ResponseEntity.ok(shelfService.getShelf(shelfId));
|
||||
}
|
||||
@@ -36,17 +38,20 @@ public class ShelfController {
|
||||
}
|
||||
|
||||
@PutMapping("/{shelfId}")
|
||||
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
|
||||
public ResponseEntity<Shelf> updateShelf(@Valid @RequestBody ShelfCreateRequest request, @PathVariable Long shelfId) {
|
||||
return ResponseEntity.ok(shelfService.updateShelf(shelfId, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{shelfId}")
|
||||
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
|
||||
public ResponseEntity<Void> deleteShelf(@PathVariable Long shelfId) {
|
||||
shelfService.deleteShelf(shelfId);
|
||||
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
|
||||
}
|
||||
|
||||
@GetMapping("/{shelfId}/books")
|
||||
@PreAuthorize("@securityUtil.isShelfOwner(#shelfId)")
|
||||
public ResponseEntity<List<Book>> getShelfBooks(@PathVariable Long shelfId) {
|
||||
return ResponseEntity.ok(shelfService.getShelfBooks(shelfId));
|
||||
}
|
||||
|
||||
+4
-3
@@ -23,25 +23,26 @@ public class UserController {
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("@securityUtil.canViewUserProfile(#id)")
|
||||
public ResponseEntity<BookLoreUser> getUser(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(userService.getBookLoreUser(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<List<BookLoreUser>> getAllUsers() {
|
||||
return ResponseEntity.ok(userService.getBookLoreUsers());
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookLoreUser> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest updateRequest) {
|
||||
BookLoreUser updatedUser = userService.updateUser(id, updateRequest);
|
||||
return ResponseEntity.ok(updatedUser);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public void deleteUser(@PathVariable Long id) {
|
||||
userService.deleteUser(id);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.EpubViewerPreferencesMapper;
|
||||
@@ -29,7 +30,6 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
+1
-2
@@ -23,7 +23,6 @@ import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -102,7 +101,7 @@ public class LibraryProcessingService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void refreshLibrary(long libraryId) throws IOException {
|
||||
public void rescanLibrary(long libraryId) throws IOException {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
|
||||
processLibraryFiles(getUnProcessedFiles(libraryEntity));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.LibraryMapper;
|
||||
@@ -174,11 +175,11 @@ public class LibraryService {
|
||||
return libraryMapper.toLibrary(libraryEntity);
|
||||
}
|
||||
|
||||
public void refreshLibrary(long libraryId) {
|
||||
public void rescanLibrary(long libraryId) {
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
Thread.startVirtualThread(() -> {
|
||||
try {
|
||||
libraryProcessingService.refreshLibrary(libraryId);
|
||||
libraryProcessingService.rescanLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.ShelfMapper;
|
||||
@@ -10,7 +11,6 @@ import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.model.dto.Sort;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
@@ -47,11 +47,7 @@ public class ShelfService {
|
||||
}
|
||||
|
||||
public Shelf updateShelf(Long id, ShelfCreateRequest request) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
ShelfEntity shelfEntity = shelfRepository.findById(id).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(id));
|
||||
if (!shelfEntity.getUser().getId().equals(user.getId())) {
|
||||
throw ApiError.UNAUTHORIZED.createException("You are not authorized to access this shelf.");
|
||||
}
|
||||
shelfEntity.setName(request.getName());
|
||||
shelfEntity.setIcon(request.getIcon());
|
||||
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
|
||||
@@ -65,29 +61,17 @@ public class ShelfService {
|
||||
}
|
||||
|
||||
public Shelf getShelf(Long shelfId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
ShelfEntity shelfEntity = shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
if (!shelfEntity.getUser().getId().equals(user.getId())) {
|
||||
throw ApiError.UNAUTHORIZED.createException("You are not authorized to access this shelf.");
|
||||
}
|
||||
return shelfMapper.toShelf(shelfEntity);
|
||||
}
|
||||
|
||||
public void deleteShelf(Long shelfId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
ShelfEntity shelfEntity = shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
if (!shelfEntity.getUser().getId().equals(user.getId())) {
|
||||
throw ApiError.UNAUTHORIZED.createException("You are not authorized to delete this shelf.");
|
||||
}
|
||||
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
shelfRepository.deleteById(shelfId);
|
||||
}
|
||||
|
||||
public List<Book> getShelfBooks(Long shelfId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
ShelfEntity shelfEntity = shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
if (!shelfEntity.getUser().getId().equals(user.getId())) {
|
||||
throw ApiError.UNAUTHORIZED.createException("You are not authorized to view the books in this shelf.");
|
||||
}
|
||||
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
List<BookEntity> bookEntities = bookRepository.findByShelfId(shelfId);
|
||||
return bookEntities.stream()
|
||||
.map(bookMapper::toBook)
|
||||
|
||||
Reference in New Issue
Block a user