Search in sources :

Example 31 with User

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

the class JwtUtilsTest method testExpiredToken.

@Test(expected = ExpiredJwtException.class)
public void testExpiredToken() {
    JwtUtils jwt = new JwtUtils();
    jwt.setIssuer("A test issuer");
    jwt.setExpiryInMilliSeconds(-1);
    jwt.setSecretKey("A test secret key");
    User testUser = BookControllerTestUtils.getTestUser();
    String token = jwt.createTokenForUser(testUser);
    jwt.getUserFromToken(token);
}
Also used : User(com.aidanwhiteley.books.domain.User) Test(org.junit.Test)

Example 32 with User

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

the class UserServiceTest method testUpdateFacebookBasedUser.

@Test
public void testUpdateFacebookBasedUser() {
    User user = testUserCreate(facebookClientClientId, NEW_USER_2, User.AuthenticationProvider.FACEBOOK);
    configureOauth(facebookClientClientId, UPDATED_USER_2);
    UserService userService = configureUserService();
    User updatedUser = userService.createOrUpdateUser(oauthToken);
    assertEquals(UPDATED_USER_2, updatedUser.getFullName());
    // Check that the user was updated and not created again
    assertEquals(user.getId(), updatedUser.getId());
}
Also used : User(com.aidanwhiteley.books.domain.User) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) Test(org.junit.Test) IntegrationTest(com.aidanwhiteley.books.util.IntegrationTest)

Example 33 with User

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

Example 34 with User

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

the class BookSecureController method createBook.

@RequestMapping(value = "/books", method = POST)
public ResponseEntity<Book> createBook(@Valid @RequestBody Book book, Principal principal, HttpServletRequest request) throws MalformedURLException, URISyntaxException {
    Optional<User> user = authUtils.extractUserFromPrincipal(principal, false);
    if (user.isPresent()) {
        book.setCreatedBy(new Owner(user.get()));
        // implementation.
        if (book.getGoogleBookId() != null && book.getGoogleBookId().length() > 0) {
            book.setGoogleBookDetails(googleBooksDaoSync.searchGoogleBooksByGoogleBookId(book.getGoogleBookId()));
        }
        Book insertedBook = bookRepository.insert(book);
        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().replaceAll("/secure", ""));
        return ResponseEntity.created(location).build();
    } else {
        LOGGER.error("Couldnt create a book as user to own book not found! Principal: {}", principal);
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }
}
Also used : Owner(com.aidanwhiteley.books.domain.Owner) User(com.aidanwhiteley.books.domain.User) Book(com.aidanwhiteley.books.domain.Book) URI(java.net.URI)

Example 35 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.valueOf(s)));
    }
    return user;
}
Also used : Claims(io.jsonwebtoken.Claims) User(com.aidanwhiteley.books.domain.User)

Aggregations

User (com.aidanwhiteley.books.domain.User)36 Test (org.junit.Test)19 IntegrationTest (com.aidanwhiteley.books.util.IntegrationTest)16 Book (com.aidanwhiteley.books.domain.Book)15 BookRepositoryTest (com.aidanwhiteley.books.repository.BookRepositoryTest)9 URI (java.net.URI)3 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)3 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)3 Principal (java.security.Principal)2 Around (org.aspectj.lang.annotation.Around)2 HttpHeaders (org.springframework.http.HttpHeaders)2 ClientRoles (com.aidanwhiteley.books.controller.dtos.ClientRoles)1 AccessForbiddenException (com.aidanwhiteley.books.controller.exceptions.AccessForbiddenException)1 Comment (com.aidanwhiteley.books.domain.Comment)1 Owner (com.aidanwhiteley.books.domain.Owner)1 Claims (io.jsonwebtoken.Claims)1 ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)1 LocalDateTime (java.time.LocalDateTime)1 List (java.util.List)1 Cookie (javax.servlet.http.Cookie)1