Search in sources :

Example 51 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class JwtUtilsTest method testTamperedWithToken.

@Test
void testTamperedWithToken() {
    JwtUtils jwt = new JwtUtils();
    jwt.setIssuer("A test issuer");
    jwt.setExpiryInMilliSeconds(60 * 1000);
    jwt.setSecretKey("A test secret key");
    User testUser = BookControllerTestUtils.getTestUser();
    String token = jwt.createTokenForUser(testUser);
    StringBuilder tampered = new StringBuilder(token);
    int strlength = token.length();
    char aChar = token.charAt(strlength - 1);
    tampered.setCharAt(strlength - 1, (char) (aChar - 1));
    String tamperedString = tampered.toString();
    Assertions.assertThrows(SignatureException.class, () -> jwt.getUserFromToken(tamperedString));
}
Also used : User(com.aidanwhiteley.books.domain.User) Test(org.junit.jupiter.api.Test)

Example 52 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class BookSecureController method createBook.

@PostMapping(value = "/books")
public ResponseEntity<Book> createBook(@Valid @RequestBody Book book, Principal principal) throws MalformedURLException, URISyntaxException {
    LOGGER.debug("createBook in BookSecureController called");
    Optional<User> user = authUtils.extractUserFromPrincipal(principal, false);
    if (user.isPresent()) {
        Book insertedBook = bookRepository.insert(book);
        // go and get the full details from Google and then update the Mongo document for the book
        if (book.getGoogleBookId() != null && book.getGoogleBookId().length() > 0) {
            googleBooksDaoAsync.updateBookWithGoogleBookDetails(insertedBook, book.getGoogleBookId());
        }
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(insertedBook.getId()).toUri();
        // Basic GET of book details are not on a secure API
        location = new URI(location.toURL().toString().replace("/secure", ""));
        LOGGER.debug("createBook existed. New Book created in store - accessible at {}", location);
        return ResponseEntity.created(location).build();
    } else {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Couldnt create a book as user to own book not found! Principal: {}", logMessageDetaint(principal));
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }
}
Also used : User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) URI(java.net.URI) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 53 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class BookSecureController method updateBook.

@PutMapping(value = "/books")
public ResponseEntity<Book> updateBook(@Valid @RequestBody Book book, Principal principal) {
    Optional<User> user = authUtils.extractUserFromPrincipal(principal, false);
    if (user.isPresent()) {
        Book currentBookState = bookRepository.findById(book.getId()).orElseThrow(() -> new IllegalArgumentException("Didnt find book to update"));
        if (currentBookState.isOwner(user.get()) || user.get().getRoles().contains(User.Role.ROLE_ADMIN)) {
            boolean inputHasGoogleBookId = book.getGoogleBookId() != null && (!book.getGoogleBookId().isEmpty());
            if ((inputHasGoogleBookId && currentBookState.getGoogleBookDetails() == null) || (currentBookState.getGoogleBookId() != null && book.getGoogleBookId() != null && (!currentBookState.getGoogleBookId().equalsIgnoreCase(book.getGoogleBookId())))) {
                // Retrieve and update Google Book details synchronously
                Item item = googleBooksDaoSync.searchGoogleBooksByGoogleBookId(book.getGoogleBookId());
                book.setGoogleBookDetails(item);
            } else if (book.getGoogleBookId() == null || book.getGoogleBookId().isEmpty()) {
                book.setGoogleBookDetails(null);
            }
            bookRepository.save(book);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    } else {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }
}
Also used : Item(com.aidanwhiteley.books.domain.googlebooks.Item) User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) PutMapping(org.springframework.web.bind.annotation.PutMapping)

Example 54 with User

use of com.aidanwhiteley.books.domain.User 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)

Example 55 with User

use of com.aidanwhiteley.books.domain.User in project books by aidanwhiteley.

the class JwtUtils method getUserFromToken.

public User getUserFromToken(String token) {
    Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    String authenticationServiceId = claims.getSubject();
    String extractedIssuer = claims.getIssuer();
    String authProvider = (String) claims.get(AUTH_PROVIDER);
    String fullName = (String) claims.get(FULL_NAME);
    String roles = (String) claims.get(ROLES);
    if (!issuer.equals(extractedIssuer)) {
        String errMsg = "Expected token issuer of " + issuer + " but found " + extractedIssuer;
        LOGGER.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    User user = User.builder().authenticationServiceId(authenticationServiceId).authProvider(User.AuthenticationProvider.valueOf(authProvider)).fullName(fullName).build();
    String[] rolesArray = roles.split(ROLES_DELIMETER);
    for (String s : rolesArray) {
        user.addRole(User.Role.getRole(Integer.parseInt(s)));
    }
    return user;
}
Also used : Claims(io.jsonwebtoken.Claims) User(com.aidanwhiteley.books.domain.User)

Aggregations

User (com.aidanwhiteley.books.domain.User)61 Test (org.junit.jupiter.api.Test)35 Book (com.aidanwhiteley.books.domain.Book)25 IntegrationTest (com.aidanwhiteley.books.util.IntegrationTest)24 BookRepositoryTest (com.aidanwhiteley.books.repository.BookRepositoryTest)13 URI (java.net.URI)5 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)4 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)4 Principal (java.security.Principal)3 HttpHeaders (org.springframework.http.HttpHeaders)3 Comment (com.aidanwhiteley.books.domain.Comment)2 Around (org.aspectj.lang.annotation.Around)2 LoggerContext (ch.qos.logback.classic.LoggerContext)1 ClientRoles (com.aidanwhiteley.books.controller.dtos.ClientRoles)1 NotAuthorisedException (com.aidanwhiteley.books.controller.exceptions.NotAuthorisedException)1 Owner (com.aidanwhiteley.books.domain.Owner)1 Item (com.aidanwhiteley.books.domain.googlebooks.Item)1 Claims (io.jsonwebtoken.Claims)1 ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)1 LocalDateTime (java.time.LocalDateTime)1