Skip to content

Commit

Permalink
Merge pull request #18 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 8ddd100 + 5f0ffa3 commit 2441b42
Show file tree
Hide file tree
Showing 12 changed files with 108 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ public class HeaderCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 예시로 "X-Custom-Header"라는 헤더를 확인
String headerValue = request.getHeader("access-token");
//String headerValue = request.getHeader("access-token");

String authorizationHeader = request.getHeader(HEADER_AUTHORIZATION);

// 가져온 값에서 접두사 제거
String token = getAccesToken(authorizationHeader);

//System.out.println(token);
// 가져온 토큰이 유효한지 확인하고, 유효한 때는 인증정보 설정한다.
System.out.println("토큰 유효성 검사"+tokenProvider.validToken(token));


// 헤더가 올바르면 요청을 진행
return true;
Expand Down
51 changes: 35 additions & 16 deletions src/main/java/com/example/ai_jeju/controller/MyPageController.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package com.example.ai_jeju.controller;

import com.example.ai_jeju.domain.User;
import com.example.ai_jeju.dto.MyPageResponse;
import com.example.ai_jeju.jwt.TokenProvider;
import com.example.ai_jeju.service.MyPageService;
import com.example.ai_jeju.service.S3Service;
import com.example.ai_jeju.service.UserService;
import com.example.ai_jeju.util.ResponseDto;
import com.example.ai_jeju.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

Expand All @@ -15,6 +18,7 @@
@RequestMapping("/api")
public class MyPageController {

private final TokenProvider tokenProvider;
@Autowired
private MyPageService myPageService;

Expand All @@ -24,6 +28,10 @@ public class MyPageController {
@Autowired
private S3Service s3Service;

public MyPageController(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}

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

// @GetMapping("/mypage")
Expand All @@ -36,9 +44,19 @@ public class MyPageController {
// }
// }


@GetMapping("/mypage")
public MyPageResponse myPage(@RequestParam Long userId){
return userService.getMyPage(userId);
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);

return ResponseUtil.SUCCESS("마이페이지 조회에 성공하였습니다.", userService.getMyPage(userId));
} else {
return ResponseUtil.ERROR("유저 추가 중 문제가 발생하였습니다.", null);
}
}

@PutMapping("/mypage/nickname")
Expand Down Expand Up @@ -71,17 +89,18 @@ public ResponseEntity<String> createPresignedUrl(@RequestBody Map<String, String
}


@PutMapping("/mypage/update")
public ResponseEntity<User> updateMyPage (@RequestBody User newUser) {

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 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();
// }
//
// }
}
3 changes: 1 addition & 2 deletions src/main/java/com/example/ai_jeju/domain/Child.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import jakarta.persistence.*;
import lombok.*;

import java.sql.Date;

@Table(name="child")
@NoArgsConstructor(access= AccessLevel.PROTECTED) //기본생성자
@Getter
Expand All @@ -30,4 +28,5 @@ public class Child {
private String realtion;
@Column
private long childProfile;

}
8 changes: 8 additions & 0 deletions src/main/java/com/example/ai_jeju/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ public class User {
@Column(name ="ifRcmd", nullable = false)
private boolean ifRcmd;

@Column(name ="ag1", nullable = false)
private boolean ag1;

@Column(name ="ag2", nullable = false)
private boolean ag2;

@Column(name ="ag3", nullable = false)
private boolean ag3;

/*
// Builder pattern
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.example.ai_jeju.dto;

public class ModifyMyPageRequest {





}
6 changes: 6 additions & 0 deletions src/main/java/com/example/ai_jeju/dto/SignUpRequest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.ai_jeju.dto;

import com.example.ai_jeju.domain.Child;
import jakarta.persistence.Column;
import lombok.Getter;
import lombok.Setter;

Expand All @@ -17,6 +18,11 @@ public class SignUpRequest {
private String provider;
private String phoneNum;
private Boolean ifRcmd;

private boolean mustCk;
private boolean selectedCk1;
private boolean selectedCk2;

/**
* 함께 보낼 동반 아동에 대한 정보 -> 여러명일 수도 있으므로 배열 형식으로 받는다.
* private List<Child> child;
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/example/ai_jeju/jwt/TokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ public boolean validToken(String token) {
try {
Jwts.parser()
.setSigningKey(key) // 동일한 키와 알고리즘 사용
.parseClaimsJws(token);
.parseClaimsJws(token)
.getBody();

log.info("JWT token is valid");
return true;
} catch (MalformedJwtException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findById(Long userId);




}
53 changes: 9 additions & 44 deletions src/main/java/com/example/ai_jeju/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -106,21 +106,25 @@ public Long registerUser( SignUpRequest signUpRequest, HttpServletRequest reques
.build();
/*-------------------------------------------*/

System.out.println("id"+newUser.getId());
//1. 부모 저장하고
userRepository.save(newUser);
Optional<User> registerdUser = userRepository.findByEmail(newUser.getEmail());

//System.out.println("id"+newUser.getId());
// 동반아동 등록하기
List<ChildRequest> childList = signUpRequest.getChild();
for(int i=0; i<childList.size(); i++){
Child child = Child.builder()
// 유저 아이디의 값 그대로 주기.
.userId(newUser.getId())
.userId(registerdUser.get().getId())
.childName(childList.get(i).getChildName())
.birthDate(childList.get(i).getBirthDate())
.gender(childList.get(i).getGender())
.realtion(childList.get(i).getRelation())
.build();
childRepository.save(child);
}
userRepository.save(newUser);

String refresh_token = tokenProvider.generateToken(newUser, REFRESH_TOKEN_DURATION);
String access_token = tokenProvider.generateToken(newUser, ACCESS_TOKEN_DURATION);
// DB에 refreshToken 저장
Expand Down Expand Up @@ -206,47 +210,6 @@ public String withDraw(WithdrawRequest withDrawRequest){
}
return "result";
}
// public String successHadler(HttpServletRequest request,
// HttpServletResponse response, SignUpRequest signUpRequest) throws IOException {
//
// String nick = signUpRequest.getNickname();
// if(nick==null){
// nick = new NickNameGenerator().getNickname();
// }
// // Save new user using builder pattern
// User newUser = User.builder()
// .name(signUpRequest.getName())
// .nickname(nick)
// .provider(signUpRequest.getProvider())
// .email(signUpRequest.getEmail())
//
// .profileImg(signUpRequest.getProfileImg())
// .provider(signUpRequest.getProvider())
// .build();
//
//
// String accessToken = tokenProvider.generateToken(newUser, REFRESH_TOKEN_DURATION);
// /*-------------------------------------------*/
// //동반아동
// List<ChildRequest> childList = signUpRequest.getChild();
// for(int i=0; i<childList.size(); i++){
// Child child = Child.builder()
// //유저 아이디의 값 그대로 주기.
// .userId(newUser.getId())
// .childName(childList.get(i).getChildName())
// .birthDate(childList.get(i).getBirthDate())
// .gender(childList.get(i).getGender())
// .build();
// childRepository.save(child);
// }
//
// userRepository.save(newUser);
// String refresh_token = tokenProvider.generateToken(newUser, REFRESH_TOKEN_DURATION);
//
// saveRefreshToken(newUser.getId(), refresh_token);
// addAccessTokenToCookie(request,response,refresh_token);
// return accessToken;
// }

//생성된 리프레시 토큰을 전달받아 데이터베이스 저장
private void saveRefreshToken(Long userId, String newRefreshToken) {
Expand All @@ -263,10 +226,12 @@ private void addAccessTokenToCookie(HttpServletRequest request,
CookieUtil.addCookie(response, ACCESS_TOKEN_COOKIE_NAME, refreshToken, cookieMaxAge);
}
public MyPageResponse getMyPage(Long userId){

MyPageResponse myPageRes = new MyPageResponse();
User user = userRepository.findById(userId).get();
List<Child> childs = childRepository.findAllById(userId);
// myPageResponse : 응답 객체 만들기
System.out.println(childs.get(0).getChildName());
myPageRes.setEmail(user.getEmail());
myPageRes.setName(user.getName());
myPageRes.setNickname(user.getNickname());
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/example/ai_jeju/util/ResponseDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.ai_jeju.util;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class ResponseDto<T> {
private final ResponseStatus status;
private final String message;
private final T data;
}
5 changes: 5 additions & 0 deletions src/main/java/com/example/ai_jeju/util/ResponseStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.example.ai_jeju.util;

public enum ResponseStatus {
SUCCESS,FAILURE,ERROR
}
16 changes: 16 additions & 0 deletions src/main/java/com/example/ai_jeju/util/ResponseUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.ai_jeju.util;

public class ResponseUtil {

public static <T>ResponseDto<T> SUCCESS (String message, T data) {
return new ResponseDto(ResponseStatus.SUCCESS, message, data);
}

public static <T>ResponseDto<T> FAILURE (String message, T data) {
return new ResponseDto(ResponseStatus.FAILURE, message, data);
}

public static <T>ResponseDto<T> ERROR (String message, T data) {
return new ResponseDto(ResponseStatus.ERROR, message, data);
}
}

0 comments on commit 2441b42

Please sign in to comment.