Skip to content

Commit

Permalink
Merge pull request #67 from BOOK-TALK/#63-user-info-api
Browse files Browse the repository at this point in the history
#63 user info api
  • Loading branch information
chanwoo7 authored Aug 19, 2024
2 parents bbdaf72 + 4796891 commit 06afe33
Show file tree
Hide file tree
Showing 7 changed files with 170 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class SignupDto {
@Past(message = "현재 날짜보다 이전 날짜여야 합니다.")
private LocalDate birthDate;

// FIXME: 아래 필드는 삭제 예정
@Email(message = "유효한 이메일 주소여야 합니다.")
private String email;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.book.backend.domain.auth.dto.SignupDto;
import com.book.backend.domain.user.entity.Gender;
import com.book.backend.domain.user.entity.User;
import com.book.backend.domain.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -13,20 +14,14 @@
public class AuthMapper {

private final ModelMapper mapper;
private final UserMapper userMapper;
private final PasswordEncoder passwordEncoder;

public User convertToUser(SignupDto signupDto) {
User user = mapper.map(signupDto, User.class);
user.setGender(convertStringToGender(signupDto.getGender()));
user.setGender(userMapper.convertStringToGender(signupDto.getGender()));
user.setPassword(passwordEncoder.encode(signupDto.getPassword()));
return user;
}

private Gender convertStringToGender(String gender) {
return switch (gender) {
case "MAN" -> Gender.G1;
case "WOMAN" -> Gender.G2;
default -> Gender.G0;
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.book.backend.domain.user.controller;

import com.book.backend.domain.user.dto.UserDto;
import com.book.backend.domain.user.dto.UserInfoDto;
import com.book.backend.domain.user.entity.User;
import com.book.backend.domain.user.mapper.UserMapper;
import com.book.backend.domain.user.service.UserService;
import com.book.backend.global.ResponseTemplate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {
private final UserService userService;
private final ResponseTemplate responseTemplate;
private final UserMapper userMapper;

@Operation(summary = "유저 정보 불러오기", description = "유저 정보를 불러옵니다.",
responses = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UserDto.class)),
description = UserDto.description)})
@GetMapping("/info")
public ResponseEntity<?> getUserInfo() {
log.trace("UserController > getUserInfo()");

User user = userService.loadLoggedinUser();
UserDto userDto = userMapper.convertToUserDto(user);

return responseTemplate.success(userDto, HttpStatus.OK);
}

@Operation(summary = "유저 정보 수정", description = "유저의 변경 가능한 정보를 수정합니다.",
responses = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = UserInfoDto.class)),
description = UserInfoDto.description)})
@PutMapping("/info/edit")
public ResponseEntity<?> editUserInfo(@Valid @RequestBody UserInfoDto requestDto) {
log.trace("UserController > editUserInfo()");

User user = userService.loadLoggedinUser();
User updatedUser = userService.updateUserInfo(user, requestDto);

UserInfoDto userInfoDto = userMapper.convertToUserInfoDto(updatedUser);

return responseTemplate.success(userInfoDto, HttpStatus.OK);
}

}
14 changes: 4 additions & 10 deletions src/main/java/com/book/backend/domain/user/dto/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,22 @@
@AllArgsConstructor
public class UserDto {
private Long userId;

private String loginId;
private String kakaoId;

private LocalDateTime regDate;

private String loginId;

private String nickname;
private String password;

private String gender;

private LocalDate birthDate;

private String email;

private String phone;

public static final String description =
"userId : 유저 아이디 | " +
"loginId : 유저 로그인 아이디 (일반 로그인 시 생성) | " +
"kakaoId : 유저 카카오 아이디 (카카오 로그인 시 생성) | " +
"regDate : 가입 시각 | " +
"loginId : 유저 로그인 아이디 (일반 로그인 시 생성) | " +
"nickname : 닉네임 | " +
"password : 암호화된 비밀번호 (일반 로그인 시 생성) | " +
"gender : 성별 | " +
"birthDate : 생일 | " +
Expand Down
30 changes: 30 additions & 0 deletions src/main/java/com/book/backend/domain/user/dto/UserInfoDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.book.backend.domain.user.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Past;
import jakarta.validation.constraints.Pattern;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDate;

@Getter
@Setter
@NoArgsConstructor
public class UserInfoDto {
@NotBlank(message = "닉네임은 필수 입력값입니다.")
private String nickname;

@NotBlank(message = "성별은 필수 입력값입니다.")
@Pattern(regexp = "NOT_SELECTED|MAN|WOMAN", message = "성별은 NOT_SELECTED, MAN, WOMAN 중 하나여야 합니다.")
private String gender;

@Past(message = "현재 날짜보다 이전 날짜여야 합니다.")
private LocalDate birthDate;

public static final String description =
"nickname : 닉네임 | " +
"gender : 성별 | " +
"birthDate : 생일";
}
30 changes: 28 additions & 2 deletions src/main/java/com/book/backend/domain/user/mapper/UserMapper.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.book.backend.domain.user.mapper;

import com.book.backend.domain.user.dto.UserDto;
import com.book.backend.domain.user.dto.UserInfoDto;
import com.book.backend.domain.user.entity.Gender;
import com.book.backend.domain.user.entity.User;
import com.book.backend.domain.user.repository.UserRepository;
import com.book.backend.exception.CustomException;
import com.book.backend.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
Expand All @@ -11,7 +14,6 @@
@Component
@RequiredArgsConstructor
public class UserMapper {

private final ModelMapper mapper;

public UserDto convertToUserDto(User user) {
Expand All @@ -20,8 +22,32 @@ public UserDto convertToUserDto(User user) {
}

UserDto userDto = mapper.map(user, UserDto.class);
userDto.setGender(user.getGender().name());
if (userDto.getGender() == null) {
userDto.setGender(user.getGender().name());
}

return userDto;
}

public UserInfoDto convertToUserInfoDto(User user) {
if (user == null) {
throw new CustomException(ErrorCode.USER_NOT_FOUND);
}

UserInfoDto userInfoDto = mapper.map(user, UserInfoDto.class);
userInfoDto.setGender(user.getGender().name());
if (userInfoDto.getGender() == null) {
userInfoDto.setGender(user.getGender().name());
}

return userInfoDto;
}

public Gender convertStringToGender(String gender) {
return switch (gender) {
case "MAN" -> Gender.G1;
case "WOMAN" -> Gender.G2;
default -> Gender.G0;
};
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,60 @@
package com.book.backend.domain.user.service;

import com.book.backend.domain.user.dto.UserInfoDto;
import com.book.backend.domain.user.entity.User;
import com.book.backend.domain.user.mapper.UserMapper;
import com.book.backend.domain.user.repository.UserRepository;
import com.book.backend.exception.CustomException;
import com.book.backend.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional
@Transactional(readOnly = true)
public class UserService {
private final UserRepository userRepository;
private final UserMapper userMapper;

// TODO: 기능에 따른 회원 서비스 메서드 추가 예정
public User loadLoggedinUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();

return findByUsername(username);
}

public User findByUsername(String username) {
try {
return findByLoginId(username);
} catch (IllegalArgumentException e) {
return findByKakaoId(username);
}
}

public User findByLoginId(String loginId) {
return userRepository.findByLoginId(loginId)
.orElseThrow(IllegalArgumentException::new);
}

public User findByKakaoId(String kakaoId) {
return userRepository.findByKakaoId(kakaoId)
.orElseThrow(IllegalArgumentException::new);
}

@Transactional
public User updateUserInfo(User user, UserInfoDto requestDto) {
if (user == null) {
throw new CustomException(ErrorCode.USER_NOT_FOUND);
}

user.setNickname(requestDto.getNickname());
user.setGender(userMapper.convertStringToGender(requestDto.getGender()));
user.setBirthDate(requestDto.getBirthDate());
userRepository.save(user);

return user;
}
}

0 comments on commit 06afe33

Please sign in to comment.