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));
}
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();
}
}
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();
}
}
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;
}
}
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;
}
Aggregations