Skip to content
This repository has been archived by the owner on Oct 20, 2024. It is now read-only.

Commit

Permalink
Merge pull request #209 from FinFellows/develop
Browse files Browse the repository at this point in the history
[FIX] 로그아웃, 관리자 로그인, 토큰 갱신 롤백
  • Loading branch information
LEEJaeHyeok97 authored Jan 18, 2024
2 parents cc7fd84 + 30626d5 commit ab3de49
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -231,26 +231,11 @@ public AuthRes kakaoLogin(KakaoProfile kakaoProfile) {
}

@Transactional
public Message signOut(HttpServletRequest request, HttpServletResponse response) {
//쿠키에서 리프레시 토큰 추출
String refreshToken = Arrays.stream(request.getCookies())
.filter(cookie -> "refreshToken".equals(cookie.getName()))
.findFirst()
.map(Cookie::getValue)
.orElseThrow(() -> new DefaultAuthenticationException(ErrorCode.INVALID_AUTHENTICATION));

Token token = tokenRepository.findByRefreshToken(refreshToken)
public Message signOut(final RefreshTokenReq tokenRefreshRequest) {
Token token = tokenRepository.findByRefreshToken(tokenRefreshRequest.getRefreshToken())
.orElseThrow(() -> new DefaultAuthenticationException(ErrorCode.INVALID_AUTHENTICATION));
tokenRepository.delete(token);

// 쿠키에서 리프레시 토큰 삭제
Cookie refreshTokenCookie = new Cookie("refreshToken", null);
refreshTokenCookie.setMaxAge(0); // 쿠키 만료 시간을 0으로 설정하여 쿠키를 즉시 만료시킴
refreshTokenCookie.setHttpOnly(true);
refreshTokenCookie.setPath("/");
refreshTokenCookie.setSecure(true);
response.addCookie(refreshTokenCookie);

return Message.builder()
.message("로그아웃 하였습니다.")
.build();
Expand All @@ -275,7 +260,7 @@ public Message deleteAccount(UserPrincipal userPrincipal) {
}

@Transactional
public AuthRes adminSignIn(KakaoProfile kakaoProfile, HttpServletResponse response) {
public AuthRes adminSignIn(KakaoProfile kakaoProfile) {
Optional<User> byEmail = userRepository.findByEmail(kakaoProfile.getKakaoAccount().getEmail());
if (!byEmail.isPresent()) {
User user = User.builder()
Expand Down Expand Up @@ -311,13 +296,6 @@ public AuthRes adminSignIn(KakaoProfile kakaoProfile, HttpServletResponse respon

Token savedToken = tokenRepository.save(token);

Cookie refreshTokenCookie = new Cookie("refreshToken", tokenMapping.getRefreshToken());
refreshTokenCookie.setMaxAge(14 * 24 * 60 * 60); // 유효기간 2주일
refreshTokenCookie.setHttpOnly(true);
refreshTokenCookie.setPath("/");
refreshTokenCookie.setSecure(true);
response.addCookie(refreshTokenCookie);


return AuthRes.builder()
.accessToken(tokenMapping.getAccessToken())
Expand All @@ -326,26 +304,19 @@ public AuthRes adminSignIn(KakaoProfile kakaoProfile, HttpServletResponse respon

}

public ResponseEntity<?> refresh(HttpServletRequest request, HttpServletResponse response) {
//쿠키에서 리프레시 토큰 추출
String refreshToken = Arrays.stream(request.getCookies())
.filter(cookie -> "refreshToken".equals(cookie.getName()))
.findFirst()
.map(Cookie::getValue)
.orElseThrow(() -> new DefaultAuthenticationException(ErrorCode.INVALID_AUTHENTICATION));

public ResponseEntity<?> refresh(RefreshTokenReq refreshTokenReq) {
//1차 검증
boolean checkValid = valid(refreshToken);
boolean checkValid = valid(refreshTokenReq.getRefreshToken());
DefaultAssert.isAuthentication(checkValid);

Optional<Token> token = tokenRepository.findByRefreshToken(refreshToken);
Optional<Token> token = tokenRepository.findByRefreshToken(refreshTokenReq.getRefreshToken());
Authentication authentication = customTokenProviderService.getAuthenticationByEmail(token.get().getEmail());

//4. refresh token 정보 값을 업데이트 한다.
//시간 유효성 확인
TokenMapping tokenMapping;

Long expirationTime = customTokenProviderService.getExpiration(refreshToken);
Long expirationTime = customTokenProviderService.getExpiration(refreshTokenReq.getRefreshToken());
if(expirationTime > 0){
tokenMapping = customTokenProviderService.refreshToken(authentication, token.get().getRefreshToken());
}else{
Expand All @@ -355,21 +326,12 @@ public ResponseEntity<?> refresh(HttpServletRequest request, HttpServletResponse
Token updateToken = token.get().updateRefreshToken(tokenMapping.getRefreshToken());
tokenRepository.save(updateToken);

// 새로운 리프레시 토큰을 쿠키에 설정
Cookie refreshTokenCookie = new Cookie("refreshToken", tokenMapping.getRefreshToken());
refreshTokenCookie.setMaxAge(14 * 24 * 60 * 60); // 유효기간을 2주로 설정
refreshTokenCookie.setHttpOnly(true); // JavaScript를 통한 쿠키 접근 방지
refreshTokenCookie.setPath("/"); // 모든 경로에서 쿠키 사용
refreshTokenCookie.setSecure(true);
response.addCookie(refreshTokenCookie); // 쿠키를 응답에 추가

AuthRes authResponse = AuthRes.builder()
.accessToken(tokenMapping.getAccessToken())
.refreshToken(updateToken.getRefreshToken())
.role(Role.USER)
.build();


return ResponseEntity.ok(authResponse);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,12 @@ public ResponseCustom<?> kakaoCallback(
})
@GetMapping(value = "/admin/sign-in")
public ResponseCustom<?> adminSignIn(
@Parameter(description = "code를 입력해주세요.", required = true) @RequestParam("code") String code,
HttpServletResponse response
@Parameter(description = "code를 입력해주세요.", required = true) @RequestParam("code") String code
) {
String accessToken = kakaoService.getKakaoAccessToken(code);
KakaoProfile kakaoProfile = kakaoService.getKakaoProfile(accessToken);

return ResponseCustom.OK(kakaoService.adminSignIn(kakaoProfile, response));
return ResponseCustom.OK(kakaoService.adminSignIn(kakaoProfile));
}


Expand All @@ -103,10 +102,9 @@ public ResponseCustom<?> adminSignIn(
@PostMapping(value = "sign-out")
public ResponseCustom<?> signOut(
@Parameter(description = "Accesstoken을 입력해주세요.", required = true) @CurrentUser UserPrincipal userPrincipal,
HttpServletRequest request,
HttpServletResponse response
@Parameter(description = "Schemas의 RefreshTokenRequest를 참고해주세요.") @Valid @RequestBody RefreshTokenReq tokenRefreshRequest
) {
return ResponseCustom.OK(kakaoService.signOut(request, response));
return ResponseCustom.OK(kakaoService.signOut(tokenRefreshRequest));
}


Expand All @@ -127,13 +125,12 @@ public ResponseCustom<?> deleteAccount(
@ApiResponse(responseCode = "200", description = "토큰 갱신 성공", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = AuthRes.class) ) } ),
@ApiResponse(responseCode = "400", description = "토큰 갱신 실패", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class) ) } ),
})
@PostMapping("/refresh")
public ResponseEntity<?> refresh(
HttpServletRequest request,
HttpServletResponse response
public ResponseCustom<?> refresh(
@Parameter(description = "Schemas의 RefreshTokenReq를 참고해주세요.", required = true) @Valid @RequestBody RefreshTokenReq refreshTokenReq
) {
return kakaoService.refresh(request, response);
return ResponseCustom.OK(kakaoService.refresh(refreshTokenReq));
}



}

0 comments on commit ab3de49

Please sign in to comment.