토큰을 사용하여 현재 사용자 정보 응답

This commit is contained in:
이진석
2020-01-31 16:40:34 +09:00
parent c8f1c96c02
commit 017bc2edfe
5 changed files with 54 additions and 1 deletions

View File

@@ -11,7 +11,10 @@ import org.springframework.web.bind.annotation.RestController;
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping
public void getAuthenticationUser(@AuthenticationPrincipal User user) {
public UserResponseDto getAuthenticationUser(@AuthenticationPrincipal User user) {
return new UserResponseDto(userService.findById(user.getId()));
}
}

View File

@@ -0,0 +1,16 @@
package com.example.vue.domain.user;
import java.util.function.Supplier;
public class UserException {
public static class NoExist extends RuntimeException {
public NoExist(Long id) {
super("존재하지 않는 사용자입니다. [userId=" + id + "]");
}
}
public static Supplier<NoExist> passNoExistExceptionSupplier(Long id) {
return () -> new NoExist(id);
}
}

View File

@@ -5,6 +5,7 @@ import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
@@ -21,4 +22,8 @@ public class UserRepository {
return em.createNamedQuery("findByEmail", User.class).setParameter("email", email).getResultList();
}
public Optional<User> findById(Long id) {
return Optional.ofNullable(em.find(User.class, id));
}
}

View File

@@ -0,0 +1,21 @@
package com.example.vue.domain.user;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class UserResponseDto {
private Long id;
private String email;
private String name;
private LocalDateTime createdAt;
public UserResponseDto(User user) {
this.id = user.getId();
this.email = user.getEmail();
this.name = user.getName();
this.createdAt = user.getCreatedAt();
}
}

View File

@@ -1,7 +1,15 @@
package com.example.vue.domain.user;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public User findById(Long id) {
return userRepository.findById(id).orElseThrow(UserException.passNoExistExceptionSupplier(id));
}
}