Skip to content

Commit

Permalink
chore: clean codes
Browse files Browse the repository at this point in the history
  • Loading branch information
hantsy committed Dec 7, 2023
1 parent 7307f98 commit ab82fa1
Show file tree
Hide file tree
Showing 17 changed files with 109 additions and 227 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,8 @@ public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
if (StringUtils.hasText(token) && this.tokenProvider.validateToken(token)) {
return Mono.fromCallable(() -> this.tokenProvider.getAuthentication(token))
.subscribeOn(Schedulers.boundedElastic())
.flatMap(authentication -> {
return chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
});
.flatMap(authentication -> chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)));
}
return chain.filter(exchange);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.util.Date;
import javax.crypto.SecretKey;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.joining;

@Component
Expand All @@ -45,9 +44,8 @@ public void init() {
public String createToken(Authentication authentication) {

String username = authentication.getName();
Collection<? extends GrantedAuthority> authorities = authentication
.getAuthorities();
var claimsBuilder = Jwts.claims().subject(username);
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
var claimsBuilder = Jwts.claims().subject(username);
if (!authorities.isEmpty()) {
claimsBuilder.add(AUTHORITIES_KEY, authorities.stream()
.map(GrantedAuthority::getAuthority).collect(joining(",")));
Expand All @@ -71,8 +69,7 @@ public Authentication getAuthentication(String token) {

Collection<? extends GrantedAuthority> authorities = authoritiesClaim == null
? AuthorityUtils.NO_AUTHORITIES
: AuthorityUtils
.commaSeparatedStringToAuthorityList(authoritiesClaim.toString());
: AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesClaim.toString());

User principal = new User(claims.getSubject(), "", authorities);

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/example/demo/web/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public Mono<ResponseEntity> login(
return authRequest
.flatMap(login -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(
login.getUsername(), login.getPassword()))
login.username(), login.password()))
.map(this.tokenProvider::createToken))
.map(jwt -> {
HttpHeaders httpHeaders = new HttpHeaders();
Expand Down
24 changes: 4 additions & 20 deletions src/main/java/com/example/demo/web/AuthenticationRequest.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,9 @@
package com.example.demo.web;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import jakarta.validation.constraints.NotBlank;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AuthenticationRequest implements Serializable {

private static final long serialVersionUID = -6986746375915710855L;

@NotBlank
private String username;

@NotBlank
private String password;

public record AuthenticationRequest(
@NotBlank String username,
@NotBlank String password
) {
}
17 changes: 4 additions & 13 deletions src/main/java/com/example/demo/web/CommentForm.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
package com.example.demo.web;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import jakarta.validation.constraints.NotBlank;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CommentForm {

@NotBlank
private String content;
public record CommentForm(
@NotBlank
String content

) {
}
9 changes: 9 additions & 0 deletions src/main/java/com/example/demo/web/CreatePostCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.example.demo.web;

import jakarta.validation.constraints.NotBlank;

public record CreatePostCommand(
@NotBlank String title,
@NotBlank String content
) {
}
6 changes: 6 additions & 0 deletions src/main/java/com/example/demo/web/PaginatedResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.demo.web;

import java.util.List;

public record PaginatedResult<T>(List<T> data, Long count) {
}
82 changes: 40 additions & 42 deletions src/main/java/com/example/demo/web/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@
import com.example.demo.domain.PostNotFoundException;
import com.example.demo.repository.CommentRepository;
import com.example.demo.repository.PostRepository;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import jakarta.validation.Valid;

import static org.springframework.http.HttpStatus.NO_CONTENT;
import static org.springframework.http.ResponseEntity.created;
Expand All @@ -33,38 +32,29 @@ public class PostController {
private final CommentRepository comments;

@GetMapping("")
public Flux<Post> all(@RequestParam(value = "q", required = false) String q,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size) {
public Mono<PaginatedResult> all(@RequestParam(value = "q", required = false, defaultValue = "") String q,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size) {
Sort sort = Sort.by(Sort.Direction.DESC, "createdDate");

if (StringUtils.hasText(q)) {
return this.posts.findByTitleContains(q, PageRequest.of(page, size, sort));
}
else {
return this.posts.findAll(sort).skip(page).take(size);
}
}

@GetMapping(value = "/count")
public Mono<CountValue> count(@RequestParam(value = "q", required = false) String q) {
if (StringUtils.hasText(q)) {
return this.posts.countByTitleContains(q).map(CountValue::new);
}
else {
return this.posts.count().map(CountValue::new);
}
return this.posts.findByTitleContains(q, PageRequest.of(page, size, sort))
.collectList()
.zipWith(this.posts.countByTitleContains(q),
PaginatedResult::new
);
}

@PostMapping("")
public Mono<ResponseEntity<Void>> create(
@RequestBody @Valid Mono<PostForm> formData) {

return formData
.map(data -> Post.builder().title(data.getTitle())
.content(data.getContent()).build())
.flatMap(this.posts::save)
.map(saved -> created(URI.create("/posts/" + saved.getId())).build());
@RequestBody @Valid CreatePostCommand data) {
Post post = Post.builder()
.title(data.title())
.content(data.content())
.build();
return this.posts.save(post)
.map(saved -> created(URI.create("/posts/" + saved.getId()))
.build()
);
}

@GetMapping("/{id}")
Expand All @@ -76,27 +66,32 @@ public Mono<Post> get(@PathVariable("id") String id) {
@PutMapping("/{id}")
@ResponseStatus(NO_CONTENT)
public Mono<Void> update(@PathVariable("id") String id,
@RequestBody @Valid PostForm post) {
@RequestBody @Valid UpdatePostCommand post) {
return this.posts.findById(id)
.switchIfEmpty(Mono.error(new PostNotFoundException(id))).map(p -> {
p.setTitle(post.getTitle());
p.setContent(post.getContent());
.switchIfEmpty(Mono.error(new PostNotFoundException(id)))
.map(p -> {
p.setTitle(post.title());
p.setContent(post.content());

return p;
}).flatMap(this.posts::save).flatMap(data -> Mono.empty());
})
.flatMap(this.posts::save)
.then();
}

@PutMapping("/{id}/status")
@ResponseStatus(NO_CONTENT)
public Mono<Void> updateStatus(@PathVariable("id") String id,
@RequestBody @Valid UpdateStatusRequest status) {
@RequestBody @Valid UpdateStatusRequest status) {
return this.posts.findById(id)
.switchIfEmpty(Mono.error(new PostNotFoundException(id))).map(p -> {
.switchIfEmpty(Mono.error(new PostNotFoundException(id)))
.map(p -> {
// TODO: check if the current user is author it has ADMIN role.
p.setStatus(Post.Status.valueOf(status.getStatus()));

p.setStatus(Post.Status.valueOf(status.status()));
return p;
}).flatMap(this.posts::save).flatMap(data -> Mono.empty());
})
.flatMap(this.posts::save)
.then();
}

@DeleteMapping("/{id}")
Expand All @@ -119,14 +114,17 @@ public Mono<CountValue> getCommentsCountOf(@PathVariable("id") String id) {

@PostMapping("/{id}/comments")
public Mono<ResponseEntity<Void>> createCommentsOf(@PathVariable("id") String id,
@RequestBody @Valid CommentForm form) {
Comment comment = Comment.builder().post(new PostId(id))
.content(form.getContent()).build();
@RequestBody @Valid CommentForm form) {
Comment comment = Comment.builder()
.post(new PostId(id))
.content(form.content())
.build();

return this.comments.save(comment)
.map(saved -> created(
URI.create("/posts/" + id + "/comments/" + saved.getId()))
.build());
.build()
);
}

}
23 changes: 0 additions & 23 deletions src/main/java/com/example/demo/web/PostForm.java

This file was deleted.

2 changes: 2 additions & 0 deletions src/main/java/com/example/demo/web/RestExceptionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.springframework.web.reactive.result.method.annotation.ResponseEntityExceptionHandler;

import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -28,6 +29,7 @@ public class RestExceptionHandler extends ResponseEntityExceptionHandler {
public ProblemDetail handlePostNotFoundException(PostNotFoundException ex) {
ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problemDetail.setTitle("Post Not Found");
problemDetail.setType(URI.create("http://example.com/api/errors/not_found"));
return problemDetail;
}

Expand Down
9 changes: 9 additions & 0 deletions src/main/java/com/example/demo/web/UpdatePostCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.example.demo.web;

import jakarta.validation.constraints.NotBlank;

public record UpdatePostCommand(
@NotBlank String title,
@NotBlank String content
) {
}
16 changes: 3 additions & 13 deletions src/main/java/com/example/demo/web/UpdateStatusRequest.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
package com.example.demo.web;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import jakarta.validation.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpdateStatusRequest implements Serializable {

@NotBlank
private String status;

public record UpdateStatusRequest(
@NotBlank String status
) {
}
5 changes: 3 additions & 2 deletions src/test/java/com/example/demo/AuthControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
@WebFluxTest(
controllers = AuthController.class,
excludeAutoConfiguration = {
ReactiveUserDetailsServiceAutoConfiguration.class, ReactiveSecurityAutoConfiguration.class
ReactiveUserDetailsServiceAutoConfiguration.class,
ReactiveSecurityAutoConfiguration.class
}
)
@Slf4j
Expand Down Expand Up @@ -56,7 +57,7 @@ void testFindByUsername() {
.thenReturn(Mono.just(usernamePasswordAuthenticationToken));
when(this.tokenProvider.createToken(any(Authentication.class))).thenReturn("atesttoken");

var req = AuthenticationRequest.builder().username("test").password("password").build();
var req = new AuthenticationRequest("test", "password");

this.client.post()
.uri("/auth/login")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ void testFilterWithInvalidToken() {
when(this.exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION))
.thenReturn("Bearer atesttoken");
when(this.tokenProvider.validateToken(anyString())).thenReturn(false);
when(
this.chain
.filter(this.exchange)
).thenReturn(Mono.empty());
when(this.chain.filter(this.exchange)).thenReturn(Mono.empty());

filter.filter(this.exchange, this.chain);

Expand Down
Loading

0 comments on commit ab82fa1

Please sign in to comment.