Skip to content

Commit 407f168

Browse files
authored
Merge pull request FITIFITBANnerit#24 from FITIFITBANnerit/feat/login
Feat/login
2 parents a28a621 + b75b8e9 commit 407f168

File tree

10 files changed

+114
-94
lines changed

10 files changed

+114
-94
lines changed

src/main/java/com/BANnerIt/server/api/Auth/controller/OAuthController.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,25 @@
1616
@RestController
1717
@RequestMapping("/oauth")
1818
public class OAuthController {
19+
1920
private final OAuthService oAuthService;
2021

2122
public OAuthController(OAuthService oAuthService) {
2223
this.oAuthService = oAuthService;
2324
}
2425

2526
@PostMapping("/validate")
26-
public ResponseEntity<ApiResponse<?>> validateIdToken(@RequestBody Map<String, String> request) {
27+
public ResponseEntity<ApiResponse<UserData>> validateIdToken(@RequestBody Map<String, String> request) {
2728
String idToken = request.get("id_token");
28-
try {
29-
Map<String, Object> userDetails = oAuthService.authenticateUser(idToken);
3029

31-
String jwtToken = (String) userDetails.get("accessToken");
32-
UserData userData = (UserData) userDetails.get("userData");
30+
try {
31+
AutoLoginResponse loginResponse = oAuthService.authenticateUser(idToken);
3332

34-
if (jwtToken == null || userData == null) {
35-
throw new CustomException(ErrorCode.INTERNAL_SERVER_ERROR, "OAuth 인증 후 필요한 정보를 가져오지 못했습니다.");
36-
}
33+
return ResponseEntity
34+
.ok()
35+
.header("Authorization", "Bearer " + loginResponse.jwt())
36+
.body(ApiResponse.success(loginResponse.userData()));
3737

38-
return ResponseEntity.ok(ApiResponse.success(jwtToken, userData));
3938
} catch (IllegalArgumentException e) {
4039
throw new CustomException(ErrorCode.UNAUTHORIZED, "승인되지 않은 접근입니다.");
4140
} catch (Exception e) {
@@ -48,8 +47,9 @@ public ResponseEntity<ApiResponse<UserData>> refreshAccessToken(HttpServletReque
4847
final String accessToken = oAuthService.extractAccessTokenFromHeader(request);
4948
final AutoLoginResponse result = oAuthService.autoLogin(accessToken);
5049

51-
return ResponseEntity.ok(ApiResponse.success(result.jwt(), result.userData()));
50+
return ResponseEntity
51+
.ok()
52+
.header("Authorization", "Bearer " + result.jwt())
53+
.body(ApiResponse.success(result.userData()));
5254
}
53-
54-
55-
}
55+
}

src/main/java/com/BANnerIt/server/api/Auth/service/OAuthService.java

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public OAuthService(JwtTokenUtil jwtTokenUtil, MemberRepository memberRepository
3737
this.idTokenVerify=idTokenVerify;
3838
}
3939

40-
public Map<String, Object> authenticateUser(String idToken) throws GeneralSecurityException, IOException {
40+
public AutoLoginResponse authenticateUser(String idToken) throws GeneralSecurityException, IOException {
4141
GoogleIdToken.Payload payload = idTokenVerify.verifyIdToken(idToken);
4242
if (payload == null) {
4343
throw new CustomException(ErrorCode.UNAUTHORIZED, "유효하지 않은 ID 토큰입니다.");
@@ -55,14 +55,15 @@ public Map<String, Object> authenticateUser(String idToken) throws GeneralSecuri
5555

5656
refreshTokenRepository.save(new RefreshToken(member.getUserId(), refreshToken));
5757

58-
UserData userData = new UserData(name, email, pictureUrl);
58+
UserData userData = new UserData(
59+
member.getUserId(),
60+
member.getRole(),
61+
member.getName(),
62+
member.getEmail(),
63+
member.getUserProfile()
64+
);
5965

60-
Map<String, Object> response = new HashMap<>();
61-
response.put("accessToken", accessToken);
62-
response.put("refreshToken", refreshToken);
63-
response.put("userData", userData);
64-
65-
return response;
66+
return new AutoLoginResponse(accessToken, userData);
6667
}
6768

6869
public AutoLoginResponse autoLogin(String accessToken) {
@@ -95,17 +96,31 @@ public AutoLoginResponse refreshAccessToken(Long userId) {
9596
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_MEMBER, "사용자를 찾을 수 없습니다."));
9697

9798
String newAccessToken = jwtTokenUtil.generateAccessToken(userId);
98-
return new AutoLoginResponse(newAccessToken,
99-
new UserData(member.getName(), member.getEmail(), member.getUserProfile()));
10099

100+
UserData userData = new UserData(
101+
member.getUserId(),
102+
member.getRole(),
103+
member.getName(),
104+
member.getEmail(),
105+
member.getUserProfile()
106+
);
107+
108+
return new AutoLoginResponse(newAccessToken, userData);
101109
}
102110

111+
103112
private AutoLoginResponse getUserDataFromToken(String token) {
104113
Long userId = jwtTokenUtil.extractUserId(token);
105114
Member member = memberRepository.findById(userId)
106115
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_MEMBER, "사용자를 찾을 수 없습니다."));
107116

108-
UserData userData = new UserData(member.getName(), member.getEmail(), member.getUserProfile());
117+
UserData userData = new UserData(
118+
member.getUserId(),
119+
member.getRole(),
120+
member.getName(),
121+
member.getEmail(),
122+
member.getUserProfile()
123+
);
109124

110125
return new AutoLoginResponse(token, userData);
111126
}

src/main/java/com/BANnerIt/server/api/user/controller/MemberController.java

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,67 +20,79 @@ public class MemberController {
2020
private final JwtTokenUtil jwtTokenUtil;
2121

2222
@GetMapping("/userdetail")
23-
public ResponseEntity<ApiResponse<MemberResponse>> getUserDetails(@RequestHeader("Authorization") String authorizationHeader) {
24-
Long userId = memberService.extractUserId(authorizationHeader);
23+
public ResponseEntity<ApiResponse<MemberResponse>> getUserDetails(
24+
@RequestHeader("Authorization") final String authorizationHeader) {
25+
26+
final Long userId = memberService.extractUserId(authorizationHeader);
2527

2628
if (userId == null) {
2729
return ResponseEntity.badRequest().body(ApiResponse.fail(ErrorCode.INVALID_TOKEN));
2830
}
2931

30-
MemberResponse userResponse = memberService.getUserDetails(userId);
32+
final MemberResponse response = memberService.getUserDetails(userId);
3133

32-
if (userResponse == null) {
34+
if (response == null) {
3335
return ResponseEntity.status(ErrorCode.NOT_FOUND_MEMBER.getHttpStatus())
3436
.body(ApiResponse.fail(ErrorCode.NOT_FOUND_MEMBER));
3537
}
3638

37-
return ResponseEntity.ok(ApiResponse.success(null, userResponse));
39+
return ResponseEntity.ok()
40+
.header("Authorization", authorizationHeader)
41+
.body(ApiResponse.success(response));
3842
}
3943

4044
@PatchMapping("/update")
41-
public ResponseEntity<ApiResponse<String>> updateUser(@Valid @RequestBody MemberUpdateRequest request,
42-
@RequestHeader("Authorization") String authorizationHeader) {
43-
Long userId = memberService.extractUserId(authorizationHeader);
45+
public ResponseEntity<ApiResponse<String>> updateUser(
46+
@Valid @RequestBody MemberUpdateRequest request,
47+
@RequestHeader("Authorization") String authorizationHeader) {
48+
49+
final Long userId = memberService.extractUserId(authorizationHeader);
4450

4551
if (userId == null) {
4652
return ResponseEntity.badRequest().body(ApiResponse.fail(ErrorCode.INVALID_TOKEN));
4753
}
4854

49-
boolean isUpdated = memberService.updateUser(userId, request);
55+
final boolean isUpdated = memberService.updateUser(userId, request);
5056

5157
if (!isUpdated) {
5258
return ResponseEntity.status(ErrorCode.NOT_FOUND_MEMBER.getHttpStatus())
5359
.body(ApiResponse.fail(ErrorCode.NOT_FOUND_MEMBER));
5460
}
5561

56-
return ResponseEntity.ok(ApiResponse.success(null, "회원정보가 수정되었습니다."));
62+
return ResponseEntity.ok()
63+
.header("Authorization", authorizationHeader)
64+
.body(ApiResponse.success("회원정보가 수정되었습니다."));
5765
}
5866

5967
@PostMapping("/logout")
60-
public ResponseEntity<ApiResponse<String>> logout(@RequestHeader("Authorization") String authorizationHeader) {
61-
String token = authorizationHeader.replace("Bearer ", "");
68+
public ResponseEntity<ApiResponse<String>> logout(
69+
@RequestHeader("Authorization") String authorizationHeader) {
6270

63-
boolean isLoggedOut = memberService.logout(token);
71+
final String token = authorizationHeader.replace("Bearer ", "");
72+
73+
final boolean isLoggedOut = memberService.logout(token);
6474

6575
if (!isLoggedOut) {
6676
return ResponseEntity.status(ErrorCode.NOT_FOUND_MEMBER.getHttpStatus())
6777
.body(ApiResponse.fail(ErrorCode.NOT_FOUND_MEMBER));
6878
}
6979

70-
return ResponseEntity.ok(ApiResponse.success(null, "로그아웃 완료되었습니다."));
80+
return ResponseEntity.ok(ApiResponse.success("로그아웃 완료되었습니다."));
7181
}
7282

7383
@DeleteMapping("/delete")
74-
public ResponseEntity<ApiResponse<String>> deleteUser(@RequestHeader("Authorization") String authorizationHeader) {
84+
public ResponseEntity<ApiResponse<String>> deleteUser(
85+
@RequestHeader("Authorization") String authorizationHeader) {
86+
7587
final String token = authorizationHeader.replace("Bearer ", "");
7688

77-
boolean isDeleted = memberService.deleteMember(token);
89+
final boolean isDeleted = memberService.deleteMember(token);
7890

7991
if (!isDeleted) {
8092
return ResponseEntity.status(ErrorCode.NOT_FOUND_MEMBER.getHttpStatus())
8193
.body(ApiResponse.fail(ErrorCode.NOT_FOUND_MEMBER));
8294
}
8395

84-
return ResponseEntity.ok(ApiResponse.success(null, "회원탈퇴가 완료되었습니다."));
96+
return ResponseEntity.ok(ApiResponse.success("회원탈퇴가 완료되었습니다."));
8597
}
86-
}
98+
}
Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
package com.BANnerIt.server.api.user.dto;
22

3+
import com.fasterxml.jackson.annotation.JsonProperty;
4+
35
public record MemberResponse(
4-
Long userId,
6+
Long id,
7+
String role,
58
String email,
69
String name,
7-
String role,
8-
String userProfileUrl
9-
) {
10-
}
10+
@JsonProperty("user_profile_url") String userProfileUrl
11+
) { }

src/main/java/com/BANnerIt/server/api/user/dto/UserData.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44

55
public record UserData(
66

7+
@JsonProperty("user_id")
8+
Long userId,
9+
10+
@JsonProperty("role")
11+
String role,
12+
713
@JsonProperty("name")
814
String name,
915

@@ -12,4 +18,4 @@ public record UserData(
1218

1319
@JsonProperty("profile_image_url")
1420
String userProfileUrl
15-
) { }
21+
) { }

src/main/java/com/BANnerIt/server/global/exception/ApiResponse.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,24 @@
44
import org.springframework.http.HttpStatus;
55

66
public record ApiResponse<T>(
7-
@Nullable String jwt,
8-
@Nullable T user_data,
7+
@Nullable T data,
98
@Nullable ExceptionDto error
109
) {
11-
public static <T> ApiResponse<T> ok(@Nullable final T user_data) {
12-
return new ApiResponse<>(null, user_data, null);
10+
public static <T> ApiResponse<T> success(@Nullable final T data) {
11+
return new ApiResponse<>(data, null);
1312
}
14-
15-
public static <T> ApiResponse<T> success(@Nullable final String jwt, @Nullable final T user_data) {
16-
return new ApiResponse<>(jwt, user_data, null);
13+
public static <T> ApiResponse<T> ok(@Nullable final T user_data) {
14+
return new ApiResponse<>(user_data, null);
1715
}
18-
1916
public static <T> ApiResponse<T> fail(final CustomException e) {
2017
return fail(e.getErrorCode());
2118
}
2219

2320
public static <T> ApiResponse<T> fail(final ErrorCode errorCode) {
24-
return new ApiResponse<>(null, null, ExceptionDto.of(errorCode));
21+
return new ApiResponse<>(null, ExceptionDto.of(errorCode));
2522
}
2623

2724
public static <T> ApiResponse<T> fail(final String message, final HttpStatus status) {
28-
return new ApiResponse<>(null, null, new ExceptionDto(status.value(), message));
25+
return new ApiResponse<>(null, new ExceptionDto(status.value(), message));
2926
}
30-
}
27+
}

src/main/java/com/BANnerIt/server/global/exception/ExceptionDto.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.BANnerIt.server.global.exception;
22

3-
import com.BANnerIt.server.global.exception.ErrorCode;
4-
53
public class ExceptionDto {
64
private final int code;
75
private final String message;

src/main/java/com/BANnerIt/server/global/exception/GlobalExceptionHandler.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@ public class GlobalExceptionHandler {
2020

2121
@ExceptionHandler(CustomException.class)
2222
public ResponseEntity<ApiResponse<?>> handleCustomException(CustomException ex) {
23-
ExceptionDto exceptionDto = new ExceptionDto(ex.getErrorCode().getHttpStatus().value(), ex.getMessage());
24-
ApiResponse<?> response = new ApiResponse<>(null, null, exceptionDto);
25-
HttpStatus status = HttpStatus.valueOf(ex.getErrorCode().getHttpStatus().value());
26-
return new ResponseEntity<>(response, status);
23+
return ResponseEntity
24+
.status(ex.getErrorCode().getHttpStatus())
25+
.body(ApiResponse.fail(ex));
2726
}
2827

2928
@ExceptionHandler(ExpiredJwtException.class)

src/test/java/com/BANnerIt/server/userTest/MemberControllerTest.java

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ void setUp() {
6262
.contentType(MediaType.APPLICATION_JSON)
6363
.content(new ObjectMapper().writeValueAsString(request)))
6464
.andExpect(status().isOk())
65-
.andExpect(jsonPath("$.user_data").value("회원정보가 수정되었습니다."));
65+
.andExpect(jsonPath("$.data").value("회원정보가 수정되었습니다."))
66+
.andExpect(jsonPath("$.error").value(nullValue()));
6667
}
6768

6869
@Test
@@ -75,8 +76,7 @@ void setUp() {
7576
mockMvc.perform(delete("/users/delete")
7677
.header("Authorization", "Bearer " + token))
7778
.andExpect(status().isOk())
78-
.andExpect(jsonPath("$.jwt").value(nullValue()))
79-
.andExpect(jsonPath("$.user_data").value("회원탈퇴가 완료되었습니다."))
79+
.andExpect(jsonPath("$.data").value("회원탈퇴가 완료되었습니다."))
8080
.andExpect(jsonPath("$.error").value(nullValue()));
8181
}
8282

@@ -90,8 +90,7 @@ void setUp() {
9090
mockMvc.perform(post("/users/logout")
9191
.header("Authorization", "Bearer " + token))
9292
.andExpect(status().isOk())
93-
.andExpect(jsonPath("$.jwt").value(nullValue()))
94-
.andExpect(jsonPath("$.user_data").value("로그아웃 완료되었습니다."))
93+
.andExpect(jsonPath("$.data").value("로그아웃 완료되었습니다."))
9594
.andExpect(jsonPath("$.error").value(nullValue()));
9695
}
9796

@@ -103,7 +102,7 @@ void setUp() {
103102
final Long userId = 1L;
104103

105104
final MemberResponse response = new MemberResponse(
106-
1L, "[email protected]", "테스트 유저", "USER", "프로필 이미지"
105+
1L, "USER","[email protected]", "테스트 유저", "프로필 이미지"
107106
);
108107

109108
given(memberService.extractUserId(authHeader)).willReturn(userId);
@@ -113,9 +112,9 @@ void setUp() {
113112
mockMvc.perform(get("/users/userdetail")
114113
.header("Authorization", authHeader))
115114
.andExpect(status().isOk())
116-
.andExpect(jsonPath("$.user_data.email").value("[email protected]"))
117-
.andExpect(jsonPath("$.user_data.name").value("테스트 유저"))
118-
.andExpect(jsonPath("$.user_data.userProfileUrl").value("프로필 이미지"))
115+
.andExpect(jsonPath("$.data.email").value("[email protected]"))
116+
.andExpect(jsonPath("$.data.name").value("테스트 유저"))
117+
.andExpect(jsonPath("$.data.user_profile_url").value("프로필 이미지"))
119118
.andExpect(jsonPath("$.error").value(nullValue()));
120119
}
121-
}
120+
}

0 commit comments

Comments
 (0)