Skip to content

Commit

Permalink
[merge] Auth 도메인 리팩토링 및 테스트 보강
Browse files Browse the repository at this point in the history
  • Loading branch information
jinkonu authored Jul 15, 2024
2 parents 93a7e71 + c923d56 commit ad5b908
Show file tree
Hide file tree
Showing 19 changed files with 87 additions and 120 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public class AuthPlatform {
public enum Type {

APPLE,
KAKAO,
;
KAKAO
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package org.recordy.server.auth.repository;

import java.util.Optional;
import javax.swing.text.html.Option;
import org.recordy.server.auth.domain.Auth;
import org.recordy.server.auth.domain.AuthPlatform;

import java.util.Optional;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.recordy.server.auth.repository.impl;

import java.util.Optional;
import org.recordy.server.auth.domain.AuthEntity;
import org.springframework.data.repository.CrudRepository;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
package org.recordy.server.auth.repository.impl;

import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.recordy.server.auth.domain.Auth;
import org.recordy.server.auth.domain.AuthEntity;
import org.recordy.server.auth.domain.AuthPlatform;
import org.recordy.server.auth.exception.AuthException;
import org.recordy.server.common.message.ErrorMessage;
import org.recordy.server.auth.repository.AuthRepository;
import org.springframework.stereotype.Repository;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package org.recordy.server.auth.security;
package org.recordy.server.auth.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.recordy.server.auth.exception.AuthException;
import org.recordy.server.auth.security.UserAuthentication;
import org.recordy.server.auth.security.handler.AuthFilterExceptionHandler;
import org.recordy.server.auth.service.AuthTokenService;
import org.recordy.server.auth.service.dto.AuthTokenValidationResult;
Expand All @@ -20,8 +21,6 @@
import java.util.Arrays;
import java.util.stream.Stream;

import static org.recordy.server.auth.service.dto.AuthTokenValidationResult.VALID_JWT;

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

Expand All @@ -45,11 +44,10 @@ public TokenAuthenticationFilter(

@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
AntPathMatcher uriMatcher = new AntPathMatcher();
String uri = request.getRequestURI();

return Stream.concat(Arrays.stream(authFreeApis), Arrays.stream(authDevApis))
.anyMatch(api -> uriMatcher.match(api, uri));
.anyMatch(api -> new AntPathMatcher().match(api, uri));
}

@Override
Expand All @@ -65,16 +63,17 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
filterChain.doFilter(request, response);
}

private void validateToken(String token) {

private void validateToken(String token) throws AuthException {
AuthTokenValidationResult validationResult = authTokenService.validateToken(token);

if (validationResult == VALID_JWT)
return;
if (validationResult == AuthTokenValidationResult.EXPIRED_TOKEN)
throw new AuthException(ErrorMessage.EXPIRED_TOKEN);

throw new AuthException(ErrorMessage.INVALID_TOKEN_VALUE);
switch (validationResult) {
case VALID_TOKEN:
return;
case EXPIRED_TOKEN:
throw new AuthException(ErrorMessage.EXPIRED_TOKEN);
default:
throw new AuthException(ErrorMessage.INVALID_TOKEN_VALUE);
}
}

private void setUserIntoContext(String token, HttpServletRequest request) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.recordy.server.auth.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
Expand All @@ -24,7 +23,7 @@ public class UndefinedAccessHandler implements AccessDeniedHandler {
private final ObjectMapper objectMapper;

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType(APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.NOT_FOUND.value());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.recordy.server.auth.security;
package org.recordy.server.auth.security.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -20,7 +20,7 @@ public boolean supportsParameter(MethodParameter parameter) {
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
return SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.recordy.server.auth.security;
package org.recordy.server.auth.security.resolver;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.recordy.server.auth.service.dto;

public enum AuthTokenValidationResult {
VALID_JWT, // 유효한 토큰
VALID_TOKEN, // 유효한 토큰
INVALID_SIGNATURE, // 유효하지 않은 서명
INVALID_TOKEN, // 유효하지 않은 토큰
EXPIRED_TOKEN, // 만료된 토큰
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public class AuthKakaoPlatformServiceImpl implements AuthPlatformService {
@Value("${auth.token.prefix}")
private String TOKEN_TYPE;

//인증 플랫폼 서비스 식별
@Override
public AuthPlatform getPlatform(UserSignIn userSignIn) {
String platformId = getKakaoPlatformId(userSignIn.platformToken());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import org.recordy.server.auth.domain.AuthToken;
import org.recordy.server.auth.exception.AuthException;
import org.recordy.server.auth.repository.AuthRepository;
import org.recordy.server.auth.security.UserAuthentication;
import org.recordy.server.auth.service.AuthTokenService;
import org.recordy.server.auth.service.dto.AuthTokenValidationResult;
import org.recordy.server.common.message.ErrorMessage;
Expand Down Expand Up @@ -76,7 +75,7 @@ public AuthTokenValidationResult validateToken(String token) {
try {
tokenParser.getBody(token);

return VALID_JWT;
return VALID_TOKEN;
} catch (MalformedJwtException ex) {
return INVALID_TOKEN;
} catch (ExpiredJwtException ex) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.recordy.server.common.config;

import lombok.RequiredArgsConstructor;
import org.recordy.server.auth.security.TokenAuthenticationFilter;
import org.recordy.server.auth.security.filter.TokenAuthenticationFilter;
import org.recordy.server.auth.security.handler.UndefinedAccessHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
Expand All @@ -14,7 +14,6 @@
import org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;

Expand Down Expand Up @@ -42,7 +41,7 @@ public SecurityFilterChain localHttpSecurity(HttpSecurity http) throws Exception

@Bean
@Profile("dev")
public SecurityFilterChain stageHttpSecurity(HttpSecurity http) throws Exception {
public SecurityFilterChain devHttpSecurity(HttpSecurity http) throws Exception {
permitDevelopApis(http);
setHttp(http);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.recordy.server.common.config;

import lombok.RequiredArgsConstructor;
import org.recordy.server.auth.security.AccessTokenArgumentResolver;
import org.recordy.server.auth.security.resolver.AccessTokenArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.junit.jupiter.api.Test;
import org.recordy.server.auth.domain.Auth;
import org.recordy.server.auth.domain.AuthPlatform;
import org.recordy.server.auth.repository.impl.AuthRedisRepository;
import org.recordy.server.util.DomainFixture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -13,58 +14,75 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@SpringBootTest
public class AuthRepositoryIntegrationTest {

@Autowired
private AuthRepository authRepository;
@Autowired
private AuthRedisRepository authRedisRepository;

@BeforeEach
void tearDown() {
authRedisRepository.deleteAll();
System.out.println("shibal");
authRedisRepository.findAll().forEach(System.out::println);
}

@Test
void save_통해_인증_데이터를_저장할__있다() {
void save_통해_Auth_객체를_저장할__있다() {
// given
String id = "abc";
boolean isSignedUp = true;

Auth auth = new Auth(
new AuthPlatform(id, AuthPlatform.Type.KAKAO),
DomainFixture.createAuthToken(),
isSignedUp
);

// when
Auth result = authRepository.save(auth);
Auth result = authRepository.save(DomainFixture.createAuth(isSignedUp));

// then
assertAll(
() -> assertThat(result.getPlatform().getId()).isEqualTo(id),
() -> assertThat(result.getPlatform().getId()).isEqualTo(DomainFixture.PLATFORM_ID),
() -> assertThat(result.getPlatform().getType()).isEqualTo(AuthPlatform.Type.KAKAO),
() -> assertThat(result.getToken().getAccessToken()).isEqualTo(DomainFixture.ACCESS_TOKEN),
() -> assertThat(result.getToken().getRefreshToken()).isEqualTo(DomainFixture.REFRESH_TOKEN),
() -> assertThat(result.isSignedUp()).isEqualTo(isSignedUp)
);
}

@Test
void delete_통해_Auth_객체를_삭제할__있다() {
// given
Auth auth = authRepository.save(DomainFixture.createAuth(false));

// when
authRepository.delete(auth);

// then
assertThat(authRepository.findByPlatformId(auth.getPlatform().getId())).isEmpty();
}

@Test
void delete_통해_존재하지_않는_Auth_객체를_삭제하더라도_에러가_발생하지_않는다() {
// given
Auth auth = DomainFixture.createAuth(false);

// when, then
assertThatCode(() -> authRepository.delete(auth))
.doesNotThrowAnyException();
}

@Test
void findByPlatformId_통해_플랫폼_ID_인증_데이터를_조회할__있다() {
// given
String id = "abc";
boolean isSignedUp = true;

Auth auth = new Auth(
new AuthPlatform(id, AuthPlatform.Type.KAKAO),
DomainFixture.createAuthToken(),
isSignedUp
);
authRepository.save(auth);
authRepository.save(DomainFixture.createAuth(isSignedUp));

// when
Auth result = authRepository.findByPlatformId(id).orElse(null);
Auth result = authRepository.findByPlatformId(DomainFixture.PLATFORM_ID)
.orElse(null);

// then
assertAll(
() -> assertThat(result.getPlatform().getId()).isEqualTo(id),
() -> assertThat(result.getPlatform().getId()).isEqualTo(DomainFixture.PLATFORM_ID),
() -> assertThat(result.getPlatform().getType()).isEqualTo(AuthPlatform.Type.KAKAO),
() -> assertThat(result.getToken().getAccessToken()).isEqualTo(DomainFixture.ACCESS_TOKEN),
() -> assertThat(result.getToken().getRefreshToken()).isEqualTo(DomainFixture.REFRESH_TOKEN),
Expand All @@ -82,28 +100,21 @@ public class AuthRepositoryIntegrationTest {
}

@Test
void ffindByRefreshToken_통해_refresh_token으로_인증_데이터를_조회할__있다() {
void findByRefreshToken_통해_refresh_token으로_인증_데이터를_조회할__있다() {
// given
String id = "abc";
boolean isSignedUp = true;

Auth auth = new Auth(
new AuthPlatform(id, AuthPlatform.Type.KAKAO),
DomainFixture.createAuthToken(),
isSignedUp
);
authRepository.save(auth);
Auth auth = authRepository.save(DomainFixture.createAuth(true));

// when
Auth result = authRepository.findByRefreshToken(DomainFixture.REFRESH_TOKEN).orElse(null);
Auth result = authRepository.findByRefreshToken(auth.getToken().getRefreshToken())
.orElse(null);

// then
assertAll(
() -> assertThat(result.getPlatform().getId()).isEqualTo(id),
() -> assertThat(result.getPlatform().getId()).isEqualTo(auth.getPlatform().getId()),
() -> assertThat(result.getPlatform().getType()).isEqualTo(AuthPlatform.Type.KAKAO),
() -> assertThat(result.getToken().getAccessToken()).isEqualTo(DomainFixture.ACCESS_TOKEN),
() -> assertThat(result.getToken().getRefreshToken()).isEqualTo(DomainFixture.REFRESH_TOKEN),
() -> assertThat(result.isSignedUp()).isEqualTo(isSignedUp)
() -> assertThat(result.isSignedUp()).isEqualTo(auth.isSignedUp())
);
}

Expand All @@ -115,42 +126,4 @@ public class AuthRepositoryIntegrationTest {
//then
assertThat(result).isEmpty();
}


@Test
void delete_통해_Auth_객체를_삭제할__있다() {
// given
String id = "abc";
boolean isSignedUp = true;

Auth auth = new Auth(
new AuthPlatform(id, AuthPlatform.Type.KAKAO),
DomainFixture.createAuthToken(),
isSignedUp
);
authRepository.save(auth);

// when
authRepository.delete(auth);

// then
assertThat(authRepository.findByPlatformId(id)).isEmpty();
}

@Test
void delete_통해_존재하지_않는_Auth_객체를_삭제하더라도_에러가_발생하지_않는다() {
// given
String id = "abc";
boolean isSignedUp = true;

Auth auth = new Auth(
new AuthPlatform(id, AuthPlatform.Type.KAKAO),
DomainFixture.createAuthToken(),
isSignedUp
);

// when, then
assertThatCode(() -> authRepository.delete(auth))
.doesNotThrowAnyException();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.recordy.server.auth.security;
package org.recordy.server.auth.security.filter;

import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
Expand Down
Loading

0 comments on commit ad5b908

Please sign in to comment.