spring-boot-realworld-examp.../src/main/java/io/spring/api/CurrentUserApi.java
2021-03-16 17:17:06 +08:00

64 lines
2.3 KiB
Java

package io.spring.api;
import io.spring.application.UserQueryService;
import io.spring.application.data.UserData;
import io.spring.application.data.UserWithToken;
import io.spring.application.user.UpdateUserCommand;
import io.spring.application.user.UpdateUserParam;
import io.spring.application.user.UserService;
import io.spring.core.user.User;
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/user")
public class CurrentUserApi {
private UserQueryService userQueryService;
private UserService userService;
@Autowired
public CurrentUserApi(UserQueryService userQueryService, UserService userService) {
this.userQueryService = userQueryService;
this.userService = userService;
}
@GetMapping
public ResponseEntity currentUser(
@AuthenticationPrincipal User currentUser,
@RequestHeader(value = "Authorization") String authorization) {
UserData userData = userQueryService.findById(currentUser.getId()).get();
return ResponseEntity.ok(
userResponse(new UserWithToken(userData, authorization.split(" ")[1])));
}
@PutMapping
public ResponseEntity updateProfile(
@AuthenticationPrincipal User currentUser,
@RequestHeader("Authorization") String token,
@Valid @RequestBody UpdateUserParam updateUserParam) {
userService.updateUser(new UpdateUserCommand(currentUser, updateUserParam));
UserData userData = userQueryService.findById(currentUser.getId()).get();
return ResponseEntity.ok(userResponse(new UserWithToken(userData, token.split(" ")[1])));
}
private Map<String, Object> userResponse(UserWithToken userWithToken) {
return new HashMap<String, Object>() {
{
put("user", userWithToken);
}
};
}
}