Skip to content

Commit

Permalink
refactor(AuthArgumentResolver): null 대신 Optional API를 활용하여 코드 개선
Browse files Browse the repository at this point in the history
  • Loading branch information
seokmyungham committed Aug 1, 2024
1 parent 58b9ab0 commit 0df9663
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import kr.momo.exception.MomoException;
import kr.momo.exception.code.AuthErrorCode;
import java.util.Optional;
import kr.momo.service.auth.JwtManager;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -38,24 +37,19 @@ public Long resolveArgument(
) {
HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
Cookie[] cookies = request.getCookies();
String token = getCookieValue(cookies);

if (token == null) {
throw new MomoException(AuthErrorCode.NOT_FOUND_TOKEN);
}
String token = getCookieValue(cookies).orElse("");

return jwtManager.extract(token);
}

private String getCookieValue(Cookie[] cookies) {
private Optional<String> getCookieValue(Cookie[] cookies) {
if (cookies == null) {
return null;
return Optional.empty();
}

return Arrays.stream(cookies)
.filter(cookie -> ACCESS_TOKEN.equals(cookie.getName()))
.map(Cookie::getValue)
.findFirst()
.orElse(null);
.findFirst();
}
}
13 changes: 8 additions & 5 deletions backend/src/test/java/kr/momo/service/auth/JwtManagerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
import kr.momo.fixture.MeetingFixture;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;

class JwtManagerTest {

Expand All @@ -30,11 +33,11 @@ void generate() {
assertThat(attendeeId).isEqualTo(attendee.getId());
}

@DisplayName("토큰이 올바르지 않을 경우 예외를 발생시킨다.")
@Test
void throwExceptionForInvalidToken() {
String token = "invalidToken";

@DisplayName("토큰이 null이거나 올바르지 않을 경우 예외를 발생시킨다.")
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"invalidToken"})
void throwExceptionForInvalidToken(String token) {
assertThatThrownBy(() -> jwtManager.extract(token))
.isInstanceOf(MomoException.class)
.hasMessage(AuthErrorCode.INVALID_TOKEN.message());
Expand Down

0 comments on commit 0df9663

Please sign in to comment.