Search in sources :

Example 1 with AccessForbiddenException

use of com.aidanwhiteley.books.controller.exceptions.AccessForbiddenException in project books by aidanwhiteley.

the class BookSecureController method removeCommentFromBook.

@RequestMapping(value = "/books/{id}/comments/{commentId}", method = DELETE)
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 AccessForbiddenException("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) AccessForbiddenException(com.aidanwhiteley.books.controller.exceptions.AccessForbiddenException)

Aggregations

AccessForbiddenException (com.aidanwhiteley.books.controller.exceptions.AccessForbiddenException)1 Book (com.aidanwhiteley.books.domain.Book)1 Comment (com.aidanwhiteley.books.domain.Comment)1 User (com.aidanwhiteley.books.domain.User)1