use of com.aidanwhiteley.books.controller.exceptions.NotAuthorisedException in project books by aidanwhiteley.
the class BookSecureController method removeCommentFromBook.
@DeleteMapping(value = "/books/{id}/comments/{commentId}")
public Book removeCommentFromBook(@PathVariable("id") String id, @PathVariable("commentId") String commentId, Principal principal) {
Optional<User> user = authUtils.extractUserFromPrincipal(principal, false);
if (user.isPresent()) {
Book currentBook = bookRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Unable to find book to delete comment from"));
Comment comment = currentBook.getComments().stream().filter(c -> c.getId().equals(commentId)).findFirst().orElse(null);
if (comment == null) {
throw new IllegalArgumentException("Unknown commentId supplied");
}
if (comment.isOwner(user.get()) || user.get().getRoles().contains(User.Role.ROLE_ADMIN)) {
return bookRepository.removeCommentFromBook(id, commentId, user.get().getFullName());
} else {
throw new NotAuthorisedException("Not owner of comment or admin");
}
} else {
return null;
}
}
Aggregations