Search in sources :

Example 1 with NotAuthorisedException

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;
    }
}
Also used : Comment(com.aidanwhiteley.books.domain.Comment) User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) NotAuthorisedException(com.aidanwhiteley.books.controller.exceptions.NotAuthorisedException) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping)

Aggregations

NotAuthorisedException (com.aidanwhiteley.books.controller.exceptions.NotAuthorisedException)1 Book (com.aidanwhiteley.books.domain.Book)1 Comment (com.aidanwhiteley.books.domain.Comment)1 User (com.aidanwhiteley.books.domain.User)1 DeleteMapping (org.springframework.web.bind.annotation.DeleteMapping)1