WIP: Assign shelf broken

This commit is contained in:
aditya.chandel
2025-02-17 04:34:09 -07:00
parent 0a906ab4f8
commit 5b90f787ce
13 changed files with 218 additions and 73 deletions
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.config.security;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
import com.adityachandel.booklore.repository.UserRepository;
@@ -8,6 +9,7 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.hibernate.Hibernate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
@@ -34,18 +36,16 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = getJwtFromRequest(request);
if (token != null && jwtUtils.validateToken(token)) {
String username = jwtUtils.extractUsername(token);
BookLoreUserEntity bookLoreUserEntity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found"));
Long userId = jwtUtils.extractUserId(token);
BookLoreUserEntity bookLoreUserEntity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found"));
BookLoreUser bookLoreUser = mapToDTO(bookLoreUserEntity);
List<GrantedAuthority> authorities = getAuthorities(bookLoreUserEntity.getPermissions());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(bookLoreUser, null, authorities);
authentication.setDetails(new UserAuthenticationDetails(request, bookLoreUser.getId()));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(request, response);
}
@@ -76,4 +76,22 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
}
return authorities;
}
private BookLoreUser mapToDTO(BookLoreUserEntity userEntity) {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(userEntity.getPermissions().isPermissionAdmin());
permissions.setCanUpload(userEntity.getPermissions().isPermissionUpload());
permissions.setCanDownload(userEntity.getPermissions().isPermissionDownload());
permissions.setCanEditMetadata(userEntity.getPermissions().isPermissionEditMetadata());
permissions.setCanManipulateLibrary(userEntity.getPermissions().isPermissionManipulateLibrary());
BookLoreUser bookLoreUser = new BookLoreUser();
bookLoreUser.setId(userEntity.getId());
bookLoreUser.setUsername(userEntity.getUsername());
bookLoreUser.setName(userEntity.getName());
bookLoreUser.setEmail(userEntity.getEmail());
bookLoreUser.setPermissions(permissions);
return bookLoreUser;
}
}
@@ -53,6 +53,16 @@ public class JwtUtils {
return extractClaims(token).getSubject();
}
public Long extractUserId(String token) {
Object userIdClaim = extractClaims(token).get("userId");
if (userIdClaim instanceof Integer) {
return ((Integer) userIdClaim).longValue();
} else if (userIdClaim instanceof Long) {
return (Long) userIdClaim;
}
throw new IllegalArgumentException("userId claim is not of type Long or Integer");
}
private boolean isTokenExpired(String token) {
return extractClaims(token).getExpiration().before(new Date());
}
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.config.security;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
@Getter
public class UserAuthenticationDetails extends WebAuthenticationDetails {
private final Long userId;
public UserAuthenticationDetails(HttpServletRequest request, Long userId) {
super(request);
this.userId = userId;
}
}
@@ -30,7 +30,7 @@ public enum ApiError {
USERNAME_ALREADY_TAKEN(HttpStatus.BAD_REQUEST, "Username already taken: %s"),
USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "User not found: %s"),
CANNOT_DELETE_ADMIN(HttpStatus.FORBIDDEN, "Admin user cannot be deleted"),
UNAUTHORIZED(HttpStatus.FORBIDDEN, "You do not have permission to perform this action"),
UNAUTHORIZED(HttpStatus.FORBIDDEN, "%s"),
INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Invalid credentials");
private final HttpStatus status;
@@ -4,6 +4,8 @@ import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
@@ -39,6 +41,9 @@ public class BookLoreUserEntity {
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private UserPermissionsEntity permissions;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<ShelfEntity> shelves = new HashSet<>();
@PrePersist
public void prePersist() {
LocalDateTime now = LocalDateTime.now();
@@ -14,21 +14,33 @@ import java.util.Set;
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "shelf")
@Table(
name = "shelf",
uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "name"})
)
public class ShelfEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false, unique = true)
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private BookLoreUserEntity user;
@Column(name = "name", nullable = false)
private String name;
@Convert(converter = SortConverter.class)
private Sort sort;
@ManyToMany(mappedBy = "shelves", fetch = FetchType.LAZY)
private Set<BookEntity> bookEntities = new HashSet<>();
private String icon;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "book_shelf_mapping",
joinColumns = {@JoinColumn(name = "shelf_id")},
inverseJoinColumns = {@JoinColumn(name = "book_id")}
)
private Set<BookEntity> bookEntities = new HashSet<>();
}
@@ -1,14 +1,17 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import jakarta.validation.constraints.NotBlank;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
@Repository
public interface ShelfRepository extends JpaRepository<ShelfEntity, Long> {
List<ShelfEntity> findShelfByName(String name);
boolean existsByName(String name);
boolean existsByUserIdAndName(Long id, String name);
List<ShelfEntity> findByUserId(Long id);
}
@@ -11,5 +11,5 @@ public interface UserRepository extends JpaRepository<BookLoreUserEntity, Long>
Optional<BookLoreUserEntity> findByUsername(String username);
Optional<BookLoreUserEntity> findByEmail(String email);
Optional<BookLoreUserEntity> findById(Long id);
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.service;
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;
import org.springframework.stereotype.Service;
@AllArgsConstructor
@Service
public class AuthenticationService {
public BookLoreUser getAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (BookLoreUser) authentication.getPrincipal();
}
}
@@ -6,15 +6,9 @@ import com.adityachandel.booklore.mapper.EpubViewerPreferencesMapper;
import com.adityachandel.booklore.mapper.PdfViewerPreferencesMapper;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.EpubViewerPreferencesRepository;
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
@@ -34,6 +28,7 @@ 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;
@@ -48,6 +43,8 @@ public class BooksService {
private final ShelfRepository shelfRepository;
private final FileService fileService;
private final BookMapper bookMapper;
private final UserRepository userRepository;
private final AuthenticationService authenticationService;
private final PdfViewerPreferencesMapper pdfViewerPreferencesMapper;
private final EpubViewerPreferencesMapper epubViewerPreferencesMapper;
@@ -100,27 +97,70 @@ public class BooksService {
@Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Optional<BookLoreUserEntity> bookLoreUserEntity = userRepository.findById(user.getId());
if (bookLoreUserEntity.isEmpty()) {
throw ApiError.USER_NOT_FOUND.createException(user.getId());
}
// Fetch books by their IDs
List<BookEntity> bookEntities = bookRepository.findAllById(bookIds);
// Fetch shelves to assign and unassign
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
List<ShelfEntity> shelvesToUnassign = shelfRepository.findAllById(shelfIdsToUnassign);
// Validate that the shelves belong to the authenticated user
validateShelfOwnership(shelvesToAssign, user);
validateShelfOwnership(shelvesToUnassign, user);
// Explicitly set user on the shelves
shelvesToAssign.forEach(shelf -> {
if (shelf.getUser() == null) {
shelf.setUser(bookLoreUserEntity.get());
}
});
shelvesToUnassign.forEach(shelf -> {
if (shelf.getUser() == null) {
shelf.setUser(bookLoreUserEntity.get());
}
});
// Ensure user_id is correctly set on book_shelf_mapping table by setting user_id explicitly when managing many-to-many relationships
for (BookEntity bookEntity : bookEntities) {
// Unassign shelves
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
shelvesToUnassign.forEach(shelf -> shelf.getBookEntities().remove(bookEntity));
// Assign new shelves and add user_id
shelvesToAssign.forEach(shelf -> {
if (!bookEntity.getShelves().contains(shelf)) {
bookEntity.getShelves().add(shelf);
}
// Do remove contains, it's necessary
if (!shelf.getBookEntities().contains(bookEntity)) {
shelf.getBookEntities().add(bookEntity);
}
// Ensure the user_id is set correctly in the relationship table
bookRepository.save(bookEntity);
shelfRepository.save(shelf); // Explicit save after associating user
});
bookRepository.save(bookEntity);
shelfRepository.saveAll(shelvesToAssign);
}
// Return the updated books
return bookEntities.stream().map(bookMapper::toBook).collect(Collectors.toList());
}
@Transactional
protected void validateShelfOwnership(List<ShelfEntity> shelves, BookLoreUser user) {
for (ShelfEntity shelf : shelves) {
if (!shelf.getUser().getId().equals(user.getId())) {
throw ApiError.UNAUTHORIZED.createException("You are not authorized to modify the shelf: " + shelf.getName());
}
}
}
public Resource getBookCover(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
return fileService.getBookCover(bookEntity.getMetadata().getThumbnail());
@@ -4,14 +4,18 @@ import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.mapper.ShelfMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.Shelf;
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;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -24,51 +28,69 @@ public class ShelfService {
private final BookRepository bookRepository;
private final ShelfMapper shelfMapper;
private final BookMapper bookMapper;
private final AuthenticationService authenticationService;
private final UserRepository userRepository;
public Shelf createShelf(ShelfCreateRequest request) {
boolean exists = shelfRepository.existsByName(request.getName());
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
boolean exists = shelfRepository.existsByUserIdAndName(user.getId(), request.getName());
if (exists) {
throw ApiError.SHELF_ALREADY_EXISTS.createException(request.getName());
}
ShelfEntity shelfEntity = ShelfEntity.builder().icon(request.getIcon()).name(request.getName()).build();
return shelfMapper.toShelf((shelfRepository.save(shelfEntity)));
ShelfEntity shelfEntity = ShelfEntity.builder()
.icon(request.getIcon())
.name(request.getName())
.user(userEntity)
.build();
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
}
public Shelf updateShelf(Long id, ShelfCreateRequest request) {
ShelfEntity shelfEntity = shelfRepository.findById(id)
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(id));
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));
}
public List<Shelf> getShelves() {
return shelfRepository.findAll().stream()
BookLoreUser user = authenticationService.getAuthenticatedUser();
return shelfRepository.findByUserId(user.getId()).stream()
.map(shelfMapper::toShelf)
.toList();
}
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) {
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(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.deleteById(shelfId);
}
public List<Book> getShelfBooks(Long shelfId) {
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(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.");
}
List<BookEntity> bookEntities = bookRepository.findByShelfId(shelfId);
return bookEntities.stream()
.map(bookMapper::toBook)
.toList();
}
public Shelf updateSort(long shelfId, Sort sort) {
ShelfEntity shelfEntity = shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
shelfEntity.setSort(sort);
return shelfMapper.toShelf(shelfRepository.save(shelfEntity));
}
}
@@ -142,32 +142,6 @@ CREATE TABLE IF NOT EXISTS book_metadata_author_mapping
CREATE INDEX IF NOT EXISTS idx_book_metadata_id ON book_metadata_author_mapping (book_id);
CREATE INDEX IF NOT EXISTS idx_author_id ON book_metadata_author_mapping (author_id);
CREATE TABLE IF NOT EXISTS shelf
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE,
sort VARCHAR(255) NULL,
icon VARCHAR(64) NOT NULL
);
CREATE TABLE IF NOT EXISTS book_shelf_mapping
(
book_id BIGINT NOT NULL,
shelf_id BIGINT NOT NULL,
PRIMARY KEY (book_id, shelf_id),
CONSTRAINT fk_book_shelf_mapping_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE,
CONSTRAINT fk_book_shelf_mapping_shelf FOREIGN KEY (shelf_id) REFERENCES shelf (id) ON DELETE CASCADE
);
CREATE TABLE app_settings
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
category VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
val TEXT NOT NULL,
UNIQUE (category, name)
);
CREATE TABLE IF NOT EXISTS users
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
@@ -191,4 +165,35 @@ CREATE TABLE IF NOT EXISTS user_permissions
CONSTRAINT fk_user_permissions_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE INDEX idx_user_permissions_user ON user_permissions (user_id);
CREATE INDEX idx_user_permissions_user ON user_permissions (user_id);
CREATE TABLE IF NOT EXISTS shelf
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
sort VARCHAR(255) NULL,
icon VARCHAR(64) NOT NULL,
UNIQUE (user_id, name),
CONSTRAINT fk_shelf_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS book_shelf_mapping
(
book_id BIGINT NOT NULL,
shelf_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
PRIMARY KEY (book_id, shelf_id, user_id),
CONSTRAINT fk_book_shelf_mapping_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE,
CONSTRAINT fk_book_shelf_mapping_shelf FOREIGN KEY (shelf_id) REFERENCES shelf (id) ON DELETE CASCADE,
CONSTRAINT fk_book_shelf_mapping_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE TABLE app_settings
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
category VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
val TEXT NOT NULL,
UNIQUE (category, name)
);
@@ -1,7 +1,3 @@
INSERT INTO shelf (name, icon)
VALUES
('Favorites', 'heart');
INSERT INTO app_settings (category, name, val)
VALUES
('epub', 'theme', 'white'),