diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java index d6b21af75..9caad0d26 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityUtil.java @@ -129,4 +129,14 @@ public class SecurityUtil { var user = getCurrentUser(); return user != null && user.getPermissions().isCanAccessTaskManager(); } + + public boolean canReadShelf(Long shelfId) { + var user = getCurrentUser(); + if (user != null) { + return shelfRepository.findById(shelfId) + .map(shelf -> shelf.isPublic() || shelf.getUser().getId().equals(user.getId())) + .orElse(false); + } + return false; + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/ShelfController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/ShelfController.java index 283cd8008..2531b2928 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/ShelfController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/ShelfController.java @@ -39,7 +39,7 @@ public class ShelfController { @ApiResponse(responseCode = "403", description = "Forbidden") }) @GetMapping("/{shelfId}") - @PreAuthorize("@securityUtil.isShelfOwner(#shelfId)") + @PreAuthorize("@securityUtil.canReadShelf(#shelfId)") public ResponseEntity getShelf( @Parameter(description = "ID of the shelf") @PathVariable Long shelfId) { return ResponseEntity.ok(shelfService.getShelf(shelfId)); @@ -76,7 +76,7 @@ public class ShelfController { @Operation(summary = "Get books on a shelf", description = "Retrieve all books assigned to a specific shelf.") @ApiResponse(responseCode = "200", description = "Books returned successfully") @GetMapping("/{shelfId}/books") - @PreAuthorize("@securityUtil.isShelfOwner(#shelfId)") + @PreAuthorize("@securityUtil.canReadShelf(#shelfId)") public ResponseEntity> getShelfBooks( @Parameter(description = "ID of the shelf") @PathVariable Long shelfId) { return ResponseEntity.ok(shelfService.getShelfBooks(shelfId)); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/ShelfMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/ShelfMapper.java index 75cbef0ba..a6243ffbd 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/ShelfMapper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/ShelfMapper.java @@ -9,5 +9,7 @@ import org.mapstruct.Mapping; public interface ShelfMapper { @Mapping(source = "user.id", target = "userId") + @Mapping(source = "public", target = "publicShelf") + @Mapping(target = "bookCount", expression = "java(shelfEntity.getBookEntities() != null ? shelfEntity.getBookEntities().size() : 0)") Shelf toShelf(ShelfEntity shelfEntity); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Shelf.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Shelf.java index 33d18c633..c8869d186 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Shelf.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Shelf.java @@ -15,4 +15,6 @@ public class Shelf { private IconType iconType; private Sort sort; private Long userId; + private boolean publicShelf; + private int bookCount; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ShelfCreateRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ShelfCreateRequest.java index b31c2943c..e59790e03 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ShelfCreateRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ShelfCreateRequest.java @@ -21,4 +21,6 @@ public class ShelfCreateRequest { @NotNull(message = "Shelf icon type must not be null.") private IconType iconType; + + private boolean publicShelf; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ShelfEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ShelfEntity.java index 118d9fce0..5872ef177 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ShelfEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/ShelfEntity.java @@ -40,6 +40,10 @@ public class ShelfEntity { @Builder.Default private IconType iconType = IconType.PRIME_NG; + @Column(name = "is_public", nullable = false) + @Builder.Default + private boolean isPublic = false; + @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "book_shelf_mapping", diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/ShelfRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/ShelfRepository.java index d62916ff3..df1759658 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/ShelfRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/ShelfRepository.java @@ -16,5 +16,8 @@ public interface ShelfRepository extends JpaRepository { Optional findByUserIdAndName(Long id, String name); + @org.springframework.data.jpa.repository.Query("SELECT s FROM ShelfEntity s WHERE s.user.id = :userId OR s.isPublic = true") + List findByUserIdOrPublicShelfTrue(@org.springframework.data.repository.query.Param("userId") Long userId); + List findByUserIdInAndName(List userIds, String name); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java index 416620ca1..0ab9e3ae7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java @@ -37,10 +37,14 @@ public class ShelfService { if (shelfRepository.existsByUserIdAndName(userId, request.getName())) { throw ApiError.SHELF_ALREADY_EXISTS.createException(request.getName()); } + if (request.isPublicShelf() && !authenticationService.getAuthenticatedUser().getPermissions().isAdmin()) { + throw new org.springframework.security.access.AccessDeniedException("Only admins can create public shelves"); + } ShelfEntity shelfEntity = ShelfEntity.builder() .icon(request.getIcon()) .name(request.getName()) .iconType(request.getIconType()) + .isPublic(request.isPublicShelf()) .user(fetchUserEntityById(userId)) .build(); return shelfMapper.toShelf(shelfRepository.save(shelfEntity)); @@ -48,15 +52,19 @@ public class ShelfService { public Shelf updateShelf(Long id, ShelfCreateRequest request) { ShelfEntity shelfEntity = findShelfByIdOrThrow(id); + if (request.isPublicShelf() && !authenticationService.getAuthenticatedUser().getPermissions().isAdmin()) { + throw new org.springframework.security.access.AccessDeniedException("Only admins can create public shelves"); + } shelfEntity.setName(request.getName()); shelfEntity.setIcon(request.getIcon()); shelfEntity.setIconType(request.getIconType()); + shelfEntity.setPublic(request.isPublicShelf()); return shelfMapper.toShelf(shelfRepository.save(shelfEntity)); } public List getShelves() { Long userId = getAuthenticatedUserId(); - return shelfRepository.findByUserId(userId).stream() + return shelfRepository.findByUserIdOrPublicShelfTrue(userId).stream() .map(shelfMapper::toShelf) .toList(); } diff --git a/booklore-api/src/main/resources/db/migration/V80__Add_is_public_to_shelf.sql b/booklore-api/src/main/resources/db/migration/V80__Add_is_public_to_shelf.sql new file mode 100644 index 000000000..6426d894d --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V80__Add_is_public_to_shelf.sql @@ -0,0 +1 @@ +ALTER TABLE shelf ADD COLUMN is_public BOOLEAN NOT NULL DEFAULT FALSE; diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index 2dc90b743..b2e96adf4 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -800,8 +800,16 @@ export class BookBrowserComponent implements OnInit, AfterViewInit { case EntityType.LIBRARY: return this.fetchBooks(book => book.libraryId === entityId); case EntityType.SHELF: - return this.fetchBooks(book => - book.shelves?.some(shelf => shelf.id === entityId) ?? false + return this.shelfService.getBooksOnShelf(entityId).pipe( + map(books => { + const sortedBooks = this.sortService.applySort(books, this.bookSorter.selectedSort!); + return { + books: sortedBooks, + loaded: true, + error: null + }; + }), + switchMap(bookState => this.applyBookFilters(bookState)) ); case EntityType.MAGIC_SHELF: return this.fetchBooksMagicShelfBooks(entityId); diff --git a/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts b/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts index 1f7feb18b..c1f8da99e 100644 --- a/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts +++ b/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts @@ -3,7 +3,7 @@ import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; import {Book} from '../../model/book.model'; import {MessageService} from 'primeng/api'; import {ShelfService} from '../../service/shelf.service'; -import {finalize, Observable} from 'rxjs'; +import {combineLatest, finalize, Observable} from 'rxjs'; import {BookService} from '../../service/book.service'; import {map, tap} from 'rxjs/operators'; import {Shelf} from '../../model/shelf.model'; @@ -14,6 +14,7 @@ import {Checkbox} from 'primeng/checkbox'; import {FormsModule} from '@angular/forms'; import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service'; import {LoadingService} from '../../../../core/services/loading.service'; +import {UserService} from '../../../settings/user-management/user.service'; import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component'; import {IconSelection} from '../../../../shared/service/icon-picker.service'; @@ -39,8 +40,18 @@ export class ShelfAssignerComponent implements OnInit { private bookService = inject(BookService); private bookDialogHelper = inject(BookDialogHelperService); private loadingService = inject(LoadingService); + private userService = inject(UserService); + + shelfState$: Observable = combineLatest([ + this.shelfService.shelfState$, + this.userService.userState$ + ]).pipe( + map(([state, userState]) => ({ + ...state, + shelves: state.shelves?.filter(s => s.userId === userState.user?.id) || [] + })) + ); - shelfState$: Observable = this.shelfService.shelfState$; book: Book = this.dynamicDialogConfig.data.book; selectedShelves: Shelf[] = []; bookIds: Set = this.dynamicDialogConfig.data.bookIds; diff --git a/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html b/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html index 88509d0ab..84a49d080 100644 --- a/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html +++ b/booklore-ui/src/app/features/book/components/shelf-creator/shelf-creator.component.html @@ -88,6 +88,21 @@ } + + @if (isAdmin) { +
+ +
+ +
+ + +
+
+ } + + @if (isAdmin) { +
+ +
+ + +
+
+ } diff --git a/booklore-ui/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.ts b/booklore-ui/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.ts index f11fe2a40..74004f797 100644 --- a/booklore-ui/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.ts +++ b/booklore-ui/src/app/features/book/components/shelf-edit-dialog/shelf-edit-dialog.component.ts @@ -9,6 +9,8 @@ import {Shelf} from '../../model/shelf.model'; import {MessageService} from 'primeng/api'; import {IconPickerService, IconSelection} from '../../../../shared/service/icon-picker.service'; import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component'; +import {CheckboxModule} from 'primeng/checkbox'; +import {UserService} from '../../../settings/user-management/user.service'; @Component({ selector: 'app-shelf-edit-dialog', @@ -17,7 +19,8 @@ import {IconDisplayComponent} from '../../../../shared/components/icon-display/i InputText, ReactiveFormsModule, FormsModule, - IconDisplayComponent + IconDisplayComponent, + CheckboxModule ], templateUrl: './shelf-edit-dialog.component.html', standalone: true, @@ -30,16 +33,20 @@ export class ShelfEditDialogComponent implements OnInit { private dynamicDialogRef = inject(DynamicDialogRef); private messageService = inject(MessageService); private iconPickerService = inject(IconPickerService); + private userService = inject(UserService); shelfName: string = ''; selectedIcon: IconSelection | null = null; shelf!: Shelf | undefined; + isPublic: boolean = false; + isAdmin: boolean = this.userService.getCurrentUser()?.permissions.admin ?? false; ngOnInit(): void { const shelfId = this.dynamicDialogConfig?.data.shelfId; this.shelf = this.shelfService.getShelfById(shelfId); if (this.shelf) { this.shelfName = this.shelf.name; + this.isPublic = this.shelf.publicShelf ?? false; if (this.shelf.iconType === 'PRIME_NG') { this.selectedIcon = {type: 'PRIME_NG', value: `pi pi-${this.shelf.icon}`}; } else { @@ -67,7 +74,8 @@ export class ShelfEditDialogComponent implements OnInit { const shelf: Shelf = { name: this.shelfName, icon: iconValue, - iconType: iconType + iconType: iconType, + publicShelf: this.isPublic }; this.shelfService.updateShelf(shelf, this.shelf?.id).subscribe({ diff --git a/booklore-ui/src/app/features/book/model/shelf.model.ts b/booklore-ui/src/app/features/book/model/shelf.model.ts index 0942e6f96..ff1391709 100644 --- a/booklore-ui/src/app/features/book/model/shelf.model.ts +++ b/booklore-ui/src/app/features/book/model/shelf.model.ts @@ -6,4 +6,7 @@ export interface Shelf { icon: string; iconType?: 'PRIME_NG' | 'CUSTOM_SVG'; sort?: SortOption; + publicShelf?: boolean; + userId?: number; + bookCount?: number; } diff --git a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts index 7c8759ede..77baca8d2 100644 --- a/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.ts @@ -135,14 +135,20 @@ export class LibraryShelfMenuService { ]; } - initializeShelfMenuItems(entity: Shelf | null): MenuItem[] { + initializeShelfMenuItems(entity: any): MenuItem[] { + const user = this.userService.getCurrentUser(); + const isOwner = entity?.userId === user?.id; + const isPublicShelf = entity?.publicShelf ?? false; + const disableOptions = !isOwner; + return [ { - label: 'Options', + label: (isPublicShelf ? 'Public Shelf - ' : '') + (disableOptions ? 'Read only' : 'Options'), items: [ { label: 'Edit Shelf', icon: 'pi pi-pen-to-square', + disabled: disableOptions, command: () => { this.dialogLauncherService.openShelfEditDialog((entity?.id as number)); } @@ -153,6 +159,7 @@ export class LibraryShelfMenuService { { label: 'Delete Shelf', icon: 'pi pi-trash', + disabled: disableOptions, command: () => { this.confirmationService.confirm({ message: `Are you sure you want to delete shelf: ${entity?.name}?`, diff --git a/booklore-ui/src/app/features/book/service/shelf.service.ts b/booklore-ui/src/app/features/book/service/shelf.service.ts index 6e6713dba..a89d1f0a2 100644 --- a/booklore-ui/src/app/features/book/service/shelf.service.ts +++ b/booklore-ui/src/app/features/book/service/shelf.service.ts @@ -1,18 +1,21 @@ import {inject, Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; -import {BehaviorSubject, Observable, of} from 'rxjs'; +import {BehaviorSubject, combineLatest, Observable, of} from 'rxjs'; import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators'; import {Shelf} from '../model/shelf.model'; import {ShelfState} from '../model/state/shelf-state.model'; import {BookService} from './book.service'; import {API_CONFIG} from '../../../core/config/api-config'; +import {Book} from '../model/book.model'; +import {UserService} from '../../settings/user-management/user.service'; @Injectable({providedIn: 'root'}) export class ShelfService { private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`; private http = inject(HttpClient); private bookService = inject(BookService); + private userService = inject(UserService); private shelfStateSubject = new BehaviorSubject({ shelves: null, @@ -101,13 +104,30 @@ export class ShelfService { } getBookCount(shelfId: number): Observable { - return this.bookService.bookState$.pipe( - map(state => - (state.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length - ) + return combineLatest([ + this.shelfState$, + this.userService.userState$, + this.bookService.bookState$ + ]).pipe( + map(([shelfState, userState, bookState]) => { + const shelf = shelfState.shelves?.find(s => s.id === shelfId); + if (!shelf) return 0; + + const isOwner = userState.user?.id === shelf.userId; + + if (isOwner) { + return (bookState.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length; + } else { + return shelf.bookCount || 0; + } + }) ); } + getBooksOnShelf(shelfId: number): Observable { + return this.http.get(`${this.url}/${shelfId}/books`); + } + getUnshelvedBookCount(): Observable { return this.bookService.bookState$.pipe( map(state =>