Skip to content

Commit

Permalink
Merge pull request #20 from KAKAO-TOUR-API-CONTEST/develop
Browse files Browse the repository at this point in the history
[FIX] 닉네임 중복 가입 불가설정, 마이페이지 필드 선택적 수정
  • Loading branch information
femmefatalehaein authored Sep 1, 2024
2 parents 908c872 + a980c34 commit bd15aa3
Show file tree
Hide file tree
Showing 12 changed files with 144 additions and 54 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-websocket'

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.openapitools:jackson-databind-nullable:0.2.4'


}
Expand Down
17 changes: 17 additions & 0 deletions src/main/java/com/example/ai_jeju/config/JacksonConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.example.ai_jeju.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.openapitools.jackson.nullable.JsonNullableModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JsonNullableModule());
return mapper;
}
}
67 changes: 35 additions & 32 deletions src/main/java/com/example/ai_jeju/controller/MyPageController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.example.ai_jeju.controller;

import com.example.ai_jeju.dto.ModifyMyPageRequest;
import com.example.ai_jeju.dto.MyPageResponse;
import com.example.ai_jeju.exception.UserNotFoundException;
import com.example.ai_jeju.jwt.TokenProvider;
import com.example.ai_jeju.service.MyPageService;
import com.example.ai_jeju.service.S3Service;
Expand Down Expand Up @@ -32,24 +34,12 @@ public MyPageController(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}

//마이페이지 회원 1명씩 조회

// @GetMapping("/mypage")
// public ResponseEntity<User> getUserById(@RequestParam Long userId) {
// Optional<User> user = myPageService.getUserById(userId);
// if (user.isPresent()) {
// return ResponseEntity.ok(user.get());
// } else {
// return ResponseEntity.notFound().build();
// }
// }


@GetMapping("/mypage")
public ResponseDto myPage(@RequestHeader("Authorization") String token){
// Bearer 토큰 형식에서 "Bearer " 부분 제거
String accessToken = token.replace("Bearer ", "");
System.out.println(accessToken);

if (tokenProvider.validToken(accessToken)) {
Long userId = tokenProvider.getUserId(accessToken);

Expand All @@ -59,12 +49,12 @@ public ResponseDto myPage(@RequestHeader("Authorization") String token){
}
}

@PutMapping("/mypage/nickname")
public ResponseEntity<String> updateNickname(@RequestParam Long userId, @RequestBody Map<String, String> request) {
String nickname = request.get("nickname");
myPageService.updateNickname(userId, nickname);
return ResponseEntity.ok("Nickname changed");
}
// @PutMapping("/mypage/nickname")
// public ResponseEntity<String> updateNickname(@RequestParam Long userId, @RequestBody Map<String, String> request) {
// String nickname = request.get("nickname");
// myPageService.updateNickname(userId, nickname);
// return ResponseEntity.ok("Nickname changed");
// }


//프로필 이미지 변경
Expand All @@ -90,17 +80,30 @@ public ResponseEntity<String> createPresignedUrl(@RequestBody Map<String, String


//바꿔야함.
// @PutMapping("/mypage/update")
// public ResponseEntity<User> updateMyPage (@RequestBody ModifyMyPageRequest request) {
//
// Long userId = newUser.getId();
//
// try {
// User updatedUser = myPageService.updateUser(userId, newUser);
// return ResponseEntity.ok(updatedUser);
// } catch (RuntimeException e) {
// return ResponseEntity.notFound().build();
// }
//
// }
@PutMapping("/mypage/update")
public ResponseDto updateMyPage (@RequestHeader("Authorization") String token, @RequestBody ModifyMyPageRequest modifyMyPageRequest) {

String accessToken = token.replace("Bearer ", "");

if (tokenProvider.validToken(accessToken)) {
Long userId = tokenProvider.getUserId(accessToken);

try {
myPageService.updateUser(userId, modifyMyPageRequest);
return ResponseUtil.SUCCESS("마이페이지 수정에 성공하였습니다.", null);
} catch (UserNotFoundException e) {
return ResponseUtil.FAILURE(e.getMessage(), null);

} catch (Exception e) {
return ResponseUtil.FAILURE(e.getMessage(), null);
}

}else{
return ResponseUtil.FAILURE("고객 정보를 찾지 못하였습니다.", null);
}


}


}
7 changes: 6 additions & 1 deletion src/main/java/com/example/ai_jeju/domain/Album.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@
public class Album {

@Id
@GeneratedValue
@Column(name = "album_id")
private Long albumId;

@OneToOne
@JoinColumn(name = "album_id") // FK를 설정
@MapsId
@JoinColumn(name = "album_id", referencedColumnName = "child_id")
private Child child;

}
3 changes: 3 additions & 0 deletions src/main/java/com/example/ai_jeju/domain/Child.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,7 @@ public class Child {
@Column
private long childProfile;

@OneToOne(mappedBy = "child", cascade = CascadeType.ALL)
private Album album;

}
3 changes: 2 additions & 1 deletion src/main/java/com/example/ai_jeju/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class User {
@Column(name = "name",nullable = false)
private String name;

@Column(name = "nickname",nullable = false)
@Column(name = "nickname",nullable = false,unique = true)
private String nickname;

@Column(name = "provider", nullable = false)
Expand All @@ -56,6 +56,7 @@ public class User {
@Column(name ="ag3", nullable = false)
private boolean ag3;


/*
// Builder pattern
private User(Builder builder) {
Expand Down
20 changes: 19 additions & 1 deletion src/main/java/com/example/ai_jeju/dto/ModifyMyPageRequest.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,27 @@
package com.example.ai_jeju.dto;

public class ModifyMyPageRequest {
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.openapitools.jackson.nullable.JsonNullable;

@Getter
@Setter
@AllArgsConstructor
public class ModifyMyPageRequest {

private JsonNullable<String> nickname;
private JsonNullable<String> phoneNum; // 선택적 필드, null일 수 있음
// 닉네임 수정해야해 ? 기본키인데?
// private JsonNullable<String> email;
// 기본 생성자와 setter 추가


//이 기본생성자 꼭 ㅠㅠㅠㅠㅠ 생성해야해
public ModifyMyPageRequest() {
this.nickname = JsonNullable.undefined();
this.phoneNum = JsonNullable.undefined();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.ai_jeju.exception;

public class UserNotFoundException extends RuntimeException {

public UserNotFoundException(String message) {
super(message);
}

public UserNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ public interface ChildRepository extends JpaRepository<Child, Long> {
@Query("SELECT c FROM Child c WHERE c.userId = :userId")
List<Child> findAllById(@Param("userId") Long userId);


}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findById(Long userId);

Optional<User>findUserByNickname(String nickname);




Expand Down
28 changes: 18 additions & 10 deletions src/main/java/com/example/ai_jeju/service/MyPageService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.example.ai_jeju.service;

import com.example.ai_jeju.domain.User;
import com.example.ai_jeju.dto.ModifyMyPageRequest;
import com.example.ai_jeju.exception.UserNotFoundException;
import com.example.ai_jeju.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -60,15 +62,21 @@ public void deleteProfileImage(Long id) {
}
}

public User updateUser(Long id, User newUserData) {
return userRepository.findById(id)
.map(user -> {
user.setName(newUserData.getName());
user.setNickname(newUserData.getNickname());
user.setProfileImg(newUserData.getProfileImg());
user.setPhoneNum(newUserData.getPhoneNum());
return userRepository.save(user);
})
.orElseThrow(() -> new RuntimeException("User not found"));
public void updateUser(Long userId, ModifyMyPageRequest modifyMyPageRequest) {
//수정당할 애 찾기
User user = userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException("User not found with id: " + userId));

// 닉네임 업데이트
modifyMyPageRequest.getNickname().ifPresent(nickname -> {
user.setNickname(nickname);
});

// 전화번호 업데이트
modifyMyPageRequest.getPhoneNum().ifPresent(phoneNum -> {
user.setPhoneNum(phoneNum);
});
// 변경된 사용자 정보를 저장
userRepository.save(user);
}
}
37 changes: 28 additions & 9 deletions src/main/java/com/example/ai_jeju/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
package com.example.ai_jeju.service;

import com.example.ai_jeju.domain.Child;
import com.example.ai_jeju.domain.RefreshToken;
import com.example.ai_jeju.domain.Store;
import com.example.ai_jeju.domain.User;
import com.example.ai_jeju.domain.*;
import com.example.ai_jeju.dto.ChildRequest;
import com.example.ai_jeju.dto.MyPageResponse;
import com.example.ai_jeju.dto.WithdrawRequest;
import com.example.ai_jeju.dto.SignUpRequest;
import com.example.ai_jeju.generator.NickNameGenerator;
import com.example.ai_jeju.handler.SignUpHandler;
import com.example.ai_jeju.jwt.TokenProvider;
import com.example.ai_jeju.repository.ChildRepository;
import com.example.ai_jeju.repository.RefreshTokenRepository;
import com.example.ai_jeju.repository.StoreRepository;
import com.example.ai_jeju.repository.UserRepository;
import com.example.ai_jeju.repository.*;
import com.example.ai_jeju.util.CookieUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -44,6 +38,8 @@ public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private AlbumRepository albumRepository;
@Autowired
private TokenProvider tokenProvider;
@Autowired
private ChildRepository childRepository;
Expand Down Expand Up @@ -88,7 +84,12 @@ public Long registerUser( SignUpRequest signUpRequest, HttpServletRequest reques
// 닉네임 없을 때 생성
String nick = signUpRequest.getNickname();
if(nick==null){
//일단 닉네임을 생성해보고.
nick = new NickNameGenerator().getNickname();
//만약 중복된 닉네임이 없을 때까지 재생성한다.
while(!userRepository.findUserByNickname(nick).isPresent()){
nick = new NickNameGenerator().getNickname();
}
}
// 가입일자
LocalDate date = LocalDate.now();
Expand All @@ -106,7 +107,7 @@ public Long registerUser( SignUpRequest signUpRequest, HttpServletRequest reques
.build();
/*-------------------------------------------*/

//1. 부모 저장하고
//1. 부모정보 저장하기
userRepository.save(newUser);
Optional<User> registerdUser = userRepository.findByEmail(newUser.getEmail());

Expand All @@ -122,9 +123,27 @@ public Long registerUser( SignUpRequest signUpRequest, HttpServletRequest reques
.gender(childList.get(i).getGender())
.realtion(childList.get(i).getRelation())
.build();

childRepository.save(child);
}

// // userId로 아이들 찾기
// List<Child> savedChilds = childRepository.findAllById(registerdUser.get().getId());
//
//
// for(int i=0; i<savedChilds.size(); i++){
// Album album = Album.builder()
// .albumId(savedChilds.get(i).getChildId())
// .child(savedChilds.get(i))
// .build();
//
// albumRepository.save(album);
// System.out.println(savedChilds.get(i).getUserId());
// }




String refresh_token = tokenProvider.generateToken(newUser, REFRESH_TOKEN_DURATION);
String access_token = tokenProvider.generateToken(newUser, ACCESS_TOKEN_DURATION);
// DB에 refreshToken 저장
Expand Down

0 comments on commit bd15aa3

Please sign in to comment.