@RestController
@RequestMapping("/dev")
@RequiredArgsConstructor
public class ProfileController {
private final UserService userService;
// 프로필 조회
@GetMapping("/my-page")
public ProfileResponseDto getMyPage(@AuthenticationPrincipal UserDetailsImpl userDetails) {
return userService.getMyPage(userDetails.getUser());
}
// 프로필 수정
@PutMapping("/profile")
public ProfileResponseDto updateProfile(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody ProfileRequestDto profileRequestDto) {
return userService.updateProfile(userDetails.getUser(), profileRequestDto);
}
// 비밀번호 변경
@PutMapping("/profile/password")
public ResponseEntity<ApiResponseDto> updatePassword(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody PasswordRequestDto passwordRequestDto) {
try {
userService.updatePassword(userDetails, passwordRequestDto);
return ResponseEntity.ok().body(new ApiResponseDto("비밀번호 변경 성공", HttpStatus.OK.value()));
} catch (RejectedExecutionException e) {
return ResponseEntity.badRequest().body(new ApiResponseDto("비밀번호가 일치하지 않습니다.", HttpStatus.BAD_REQUEST.value()));
}
}
}
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public void signup(SignupRequestDto requestDto) {
String username = requestDto.getUsername();
String password = passwordEncoder.encode(requestDto.getPassword());
String realname = requestDto.getRealname();
String introduction = requestDto.getIntroduction();
UserRoleEnum role = UserRoleEnum.USER;
// 회원 중복 확인
if (userRepository.findByUsername(username).isPresent()) {
throw new IllegalArgumentException("중복된 사용자가 존재합니다.");
}
// 사용자 등록
User user = new User(username, password, realname, introduction, role);
userRepository.save(user);
}
// 프로필 조회
public ProfileResponseDto getMyPage(User user) {
return new ProfileResponseDto(user);
}
// 프로필 수정
@Transactional
public ProfileResponseDto updateProfile(User user, ProfileRequestDto profileRequestDto) {
user.setRealname(profileRequestDto.getRealname());
user.setIntroduction(profileRequestDto.getIntroduction());
userRepository.save(user);
return new ProfileResponseDto(user);
}
// 비밀번호 변경
@Transactional
public void updatePassword(UserDetailsImpl userDetails, PasswordRequestDto passwordRequestDto) {
User user = userDetails.getUser();
if(!passwordEncoder.matches(passwordRequestDto.getPassword(), userDetails.getPassword())) {
throw new RejectedExecutionException();
}
user.setPassword(passwordRequestDto.getNewpassword());
userRepository.save(user);
}
}
오늘의 삽질
ResponseDto에 @Getter 붙이는 걸 잊지 말자..!
@RequestBody는 여러 개 보낼 수 없다.
레포지토리에 save하는 걸 잊지 말자