Skip to content

Commit

Permalink
#5 [feat] token refresh 기능 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
SeorinY committed Sep 18, 2023
1 parent a02c048 commit 1233826
Show file tree
Hide file tree
Showing 9 changed files with 35 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import com.qdang.application.user.domain.User;
import com.qdang.global.http.WebAdapter;
import com.qdang.global.pathmatch.V1;
import com.qdang.global.argument.LoginUser;
import com.qdang.global.argument.AuthUser;
import com.qdang.global.response.HttpResponse;
import com.qdang.global.response.SuccessType;
import com.qdang.adapter.match.request.StartMatchRequest;
Expand Down Expand Up @@ -93,7 +93,7 @@ public ResponseEntity<Void> recordMatchProcess(
description = "경기 종료 성공")
@PostMapping("/quit")
public ResponseEntity<Void> quitMatch(
@LoginUser User user,
@AuthUser User user,
@Valid @RequestBody QuitMatchRequest request
) {
quitGameUseCase.quitGame(request.toQuitMatchCommand(user.getId()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.qdang.application.user.domain.User;
import com.qdang.application.user.port.in.LogoutUseCase;
import com.qdang.application.user.port.in.RefreshTokenUseCase;
import com.qdang.global.argument.LoginUser;
import com.qdang.global.argument.AuthUser;
import com.qdang.global.http.HeaderTokenExtractor;
import com.qdang.global.http.WebAdapter;
import com.qdang.global.pathmatch.V1;
Expand All @@ -15,6 +15,7 @@
import com.qdang.application.user.port.in.LoginUseCase;
import com.qdang.application.user.port.in.SignUpUseCase;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.servlet.http.HttpServletRequest;
Expand All @@ -23,6 +24,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

@V1
Expand Down Expand Up @@ -67,18 +69,19 @@ public ResponseEntity<TokenResponse> login(@Valid @RequestBody LoginRequest requ
response);
}

@Operation(summary = "토큰 갱신", description = "Access Token 갱신 (Refresh Token 필요)")
@Operation(summary = "토큰 갱신", description = "Access Token 갱신")
@ApiResponse(
responseCode = "200",
description = "토큰 갱신 성공")
@PostMapping("/refresh")
public ResponseEntity<TokenResponse> refresh(
@Parameter(description = "bearer token in header")
@RequestHeader(value = "Refresh-Token") String refreshToken,
HttpServletRequest request
) {
TokenResponse response =
TokenResponse.from(
refreshTokenUseCase.refreshToken(
headerTokenExtractor.extractAccessToken(request),
headerTokenExtractor.extractRefreshToken(request)));
return HttpResponse.success(
SuccessType.REFRESH_TOKEN_SUCCESS,
Expand All @@ -91,7 +94,7 @@ public ResponseEntity<TokenResponse> refresh(
description = "로그아웃 성공")
@PostMapping("/logout")
public ResponseEntity<Void> logout(
@LoginUser User user
@AuthUser User user
) {
logoutUseCase.logout(user.getId());
return HttpResponse.success(SuccessType.LOGOUT_SUCCESS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import com.qdang.application.user.port.in.SearchUserByUsernameUseCase;
import com.qdang.global.http.WebAdapter;
import com.qdang.global.pathmatch.V1;
import com.qdang.global.argument.LoginUser;
import com.qdang.global.argument.AuthUser;
import com.qdang.global.response.HttpResponse;
import com.qdang.global.response.SuccessType;
import com.qdang.adapter.user.request.UpdateUserProfileRequest;
Expand Down Expand Up @@ -49,7 +49,7 @@ public class UserController {
description = "내 프로필 조회 성공")
@GetMapping("/profiles")
public ResponseEntity<GetUserProfileResponse> getMyProfile(
@LoginUser User user
@AuthUser User user
) {
GetUserProfileResponse response =
GetUserProfileResponse.from(
Expand Down Expand Up @@ -98,7 +98,7 @@ public ResponseEntity<UserValidationResponse> checkValidationUsername(
description = "프로필 수정 성공")
@PatchMapping("/profile")
public ResponseEntity<Void> updateUserProfile(
@LoginUser User user,
@AuthUser User user,
@Valid @RequestBody UpdateUserProfileRequest request
) {
updateUserProfileUseCase.updateUserProfile(request.toUpdateUserProfileCommand(user.getId()));
Expand All @@ -111,7 +111,7 @@ public ResponseEntity<Void> updateUserProfile(
description = "내 경기 전적 조회 성공")
@GetMapping("/matches")
public ResponseEntity<GetUserMatchHistoryResponse> getUserMatchHistory(
@LoginUser User user
@AuthUser User user
) {
GetUserMatchHistoryResponse response =
GetUserMatchHistoryResponse.from(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal(expression = "user")
public @interface LoginUser {
public @interface AuthUser {
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ public WebSecurityCustomizer webSecurityCustomizer() {
new AntPathRequestMatcher(
"/v1/auth/signup",
HttpMethod.POST.name()),
new AntPathRequestMatcher(
"/v1/auth/refresh",
HttpMethod.POST.name()),
new AntPathRequestMatcher(
"/v1/matches/{matchId}",
HttpMethod.GET.name()),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.qdang.global.config;

import com.qdang.global.argument.LoginUser;
import com.qdang.global.argument.AuthUser;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
Expand Down Expand Up @@ -40,6 +40,6 @@ public OpenAPI openAPI() {
}

static {
SpringDocUtils.getConfig().addAnnotationsToIgnore(LoginUser.class);
SpringDocUtils.getConfig().addAnnotationsToIgnore(AuthUser.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@

public interface RefreshTokenUseCase {

TokenCollection refreshToken(String accessToken, String refreshToken);
TokenCollection refreshToken(String refreshToken);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.qdang.global.usecase.UseCase;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@UseCase
Expand All @@ -24,10 +25,10 @@ class RefreshTokenService implements RefreshTokenUseCase {
private final JwtProvider jwtProvider;

@Override
public TokenCollection refreshToken(String accessToken, String refreshToken) {
jwtResolver.validateAccessToken(accessToken);
@Transactional
public TokenCollection refreshToken(String refreshToken) {
jwtResolver.validateRefreshToken(refreshToken);
Long userId = jwtResolver.getUserIdFromAccessToken(accessToken);
Long userId = jwtResolver.getUserIdFromRefreshToken(refreshToken);
User user = loadUserPort.loadById(userId);
if (user.isNotLoggedIn()) {
throw new InvalidException("로그인이 안 된 유저입니다.");
Expand Down
11 changes: 11 additions & 0 deletions application/src/main/java/com/qdang/global/jwt/JwtResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ public Long getUserIdFromAccessToken(String accessToken) {
}
}

public Long getUserIdFromRefreshToken(String refreshToken) {
try {
Claims claims = getRefreshTokenBody(refreshToken);
return Long.parseLong(claims.get("userId").toString());
} catch (ExpiredJwtException e) {
throw new UnauthorizedException(ErrorType.EXPIRED_REFRESH_TOKEN_EXCEPTION);
} catch (Exception e) {
throw new UnauthorizedException();
}
}

public boolean validateAccessToken(String accessToken) {
try {
return !getAccessTokenBody(accessToken)
Expand Down

0 comments on commit 1233826

Please sign in to comment.