Compare commits
3 Commits
feature/fi
...
feature/te
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
994db8afad | ||
|
|
dabee5c844 | ||
|
|
24c8039031 |
@@ -1,7 +1,7 @@
|
||||
plugins {
|
||||
java
|
||||
id("org.springframework.boot") version "2.6.7"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
java
|
||||
id("org.springframework.boot") version "2.6.7"
|
||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||
}
|
||||
|
||||
group = "com.ticketing"
|
||||
@@ -9,60 +9,59 @@ version = "0.0.1-SNAPSHOT"
|
||||
|
||||
val javaVersion = JavaVersion.VERSION_11
|
||||
java {
|
||||
sourceCompatibility = javaVersion
|
||||
targetCompatibility = javaVersion
|
||||
sourceCompatibility = javaVersion
|
||||
targetCompatibility = javaVersion
|
||||
}
|
||||
|
||||
configurations {
|
||||
compileOnly {
|
||||
extendsFrom(configurations.annotationProcessor.get())
|
||||
}
|
||||
compileOnly {
|
||||
extendsFrom(configurations.annotationProcessor.get())
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
||||
implementation("org.springframework.boot:spring-boot-starter-log4j2")
|
||||
implementation("org.projectlombok:lombok:1.18.20")
|
||||
implementation("io.springfox:springfox-boot-starter:3.0.0")
|
||||
implementation("io.springfox:springfox-swagger-ui:3.0.0")
|
||||
implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4")
|
||||
implementation("com.lmax:disruptor:3.4.2")
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.11.2")
|
||||
implementation("com.googlecode.json-simple:json-simple:1.1.1")
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-redis")
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
||||
implementation("org.springframework.boot:spring-boot-starter-log4j2")
|
||||
implementation("org.projectlombok:lombok:1.18.20")
|
||||
implementation("io.springfox:springfox-swagger2:3.0.0")
|
||||
implementation("io.springfox:springfox-swagger-ui:3.0.0")
|
||||
implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4")
|
||||
implementation("com.lmax:disruptor:3.4.2")
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.11.2")
|
||||
implementation("com.googlecode.json-simple:json-simple:1.1.1")
|
||||
|
||||
modules {
|
||||
module("org.springframework.boot:spring-boot-starter-logging") {
|
||||
replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")
|
||||
}
|
||||
}
|
||||
modules {
|
||||
module("org.springframework.boot:spring-boot-starter-logging") {
|
||||
replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")
|
||||
}
|
||||
}
|
||||
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1")
|
||||
|
||||
compileOnly("org.projectlombok:lombok")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.2")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.2")
|
||||
annotationProcessor("org.projectlombok:lombok")
|
||||
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
|
||||
compileOnly("org.projectlombok:lombok")
|
||||
runtimeOnly("mysql:mysql-connector-java")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.2")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.2")
|
||||
annotationProcessor("org.projectlombok:lombok")
|
||||
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
|
||||
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.ticketing.server;
|
||||
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import com.ticketing.server.global.jwt.JwtProperties;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
|
||||
@@ -1,28 +1,14 @@
|
||||
package com.ticketing.server.global.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
|
||||
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
|
||||
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
|
||||
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
|
||||
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
|
||||
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
|
||||
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.web.WebEndpointsSupplier;
|
||||
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
|
||||
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
|
||||
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.util.StringUtils;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.ApiKey;
|
||||
import springfox.documentation.service.AuthorizationScope;
|
||||
import springfox.documentation.service.SecurityReference;
|
||||
@@ -36,29 +22,27 @@ import springfox.documentation.swagger.web.UiConfigurationBuilder;
|
||||
@RequiredArgsConstructor
|
||||
public class SwaggerConfig {
|
||||
|
||||
public static final String SECURITY_SCHEMA_NAME = "Authorization";
|
||||
public static final String AUTHORIZATION_SCOPE_GLOBAL = "global";
|
||||
public static final String AUTHORIZATION_SCOPE_GLOBAL_DESC = "accessEverything";
|
||||
|
||||
@Bean
|
||||
public Docket api() {
|
||||
return new Docket(DocumentationType.OAS_30).useDefaultResponseMessages(false).select()
|
||||
.apis(RequestHandlerSelectors.any()).paths(PathSelectors.ant("/api/**")).build()
|
||||
return new Docket(DocumentationType.OAS_30)
|
||||
.useDefaultResponseMessages(false)
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.any())
|
||||
.paths(PathSelectors.ant("/api/**")).build()
|
||||
.apiInfo(apiInfo())
|
||||
.securityContexts(Arrays.asList(securityContext()))
|
||||
.securitySchemes(Arrays.asList(apiKey()));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
|
||||
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
|
||||
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
|
||||
allEndpoints.addAll(webEndpoints);
|
||||
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
|
||||
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
|
||||
String basePath = webEndpointProperties.getBasePath();
|
||||
EndpointMapping endpointMapping = new EndpointMapping(basePath);
|
||||
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
|
||||
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
|
||||
}
|
||||
|
||||
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
|
||||
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder()
|
||||
.title("Ticketing REST API Document")
|
||||
.version("v1")
|
||||
.description("Ticketing REST API 문서").build();
|
||||
}
|
||||
|
||||
private ApiKey apiKey() {
|
||||
@@ -69,10 +53,6 @@ public class SwaggerConfig {
|
||||
return SecurityContext.builder().securityReferences(defaultAuth()).build();
|
||||
}
|
||||
|
||||
public static final String SECURITY_SCHEMA_NAME = "Authorization";
|
||||
public static final String AUTHORIZATION_SCOPE_GLOBAL = "global";
|
||||
public static final String AUTHORIZATION_SCOPE_GLOBAL_DESC = "accessEverything";
|
||||
|
||||
private List<SecurityReference> defaultAuth() {
|
||||
AuthorizationScope authorizationScope = new AuthorizationScope(AUTHORIZATION_SCOPE_GLOBAL,
|
||||
AUTHORIZATION_SCOPE_GLOBAL_DESC);
|
||||
|
||||
@@ -28,6 +28,4 @@ public abstract class AbstractEntity {
|
||||
@LastModifiedDate
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
private LocalDateTime deletedAt;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.ticketing.server.global.exception;
|
||||
|
||||
public class EmailNotFoundException extends IllegalArgumentException {
|
||||
public class NotFoundEmailException extends IllegalArgumentException {
|
||||
|
||||
private static final String MESSAGE = "존재하지 않는 이메일 입니다.";
|
||||
|
||||
public EmailNotFoundException() {
|
||||
public NotFoundEmailException() {
|
||||
super(MESSAGE);
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.ticketing.server.global.exception.token;
|
||||
|
||||
public class TokenException extends RuntimeException {
|
||||
|
||||
public TokenException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.ticketing.server.global.exception.token;
|
||||
|
||||
public class TokenNotFindException extends TokenException {
|
||||
|
||||
private static final String MESSAGE = "일치하는 토큰을 찾지 못하였습니다.";
|
||||
|
||||
public TokenNotFindException() {
|
||||
super(MESSAGE);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.ticketing.server.global.exception.token;
|
||||
|
||||
public class TokenTypeException extends TokenException {
|
||||
|
||||
private static final String MESSAGE = "토큰 타입이 일치하지 않습니다.";
|
||||
|
||||
public TokenTypeException() {
|
||||
super(MESSAGE);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.ticketing.server.global.exception.token;
|
||||
|
||||
public class UnavailableRefreshTokenException extends TokenException {
|
||||
|
||||
private static final String MESSAGE = "사용할 수 없는 refresh Token 입니다.";
|
||||
|
||||
public UnavailableRefreshTokenException() {
|
||||
super(MESSAGE);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,23 +5,19 @@ import java.util.Properties;
|
||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||
import org.springframework.core.env.PropertiesPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.EncodedResource;
|
||||
import org.springframework.core.io.support.PropertySourceFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class YamlPropertySourceFactory implements PropertySourceFactory {
|
||||
|
||||
@Override
|
||||
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) {
|
||||
Properties yamlProperties = loadYamlProperties(resource);
|
||||
String sourceName = StringUtils.hasText(name) ? name : resource.getResource().getFilename();
|
||||
return new PropertiesPropertySource(Objects.requireNonNull(sourceName), Objects.requireNonNull(yamlProperties));
|
||||
}
|
||||
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
|
||||
Resource resource = encodedResource.getResource();
|
||||
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
|
||||
factoryBean.setResources(resource);
|
||||
|
||||
private Properties loadYamlProperties(EncodedResource resource) {
|
||||
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
|
||||
factory.setResources(resource.getResource());
|
||||
return factory.getObject();
|
||||
Properties properties = factoryBean.getObject();
|
||||
return new PropertiesPropertySource(Objects.requireNonNull(resource.getFilename()), Objects.requireNonNull(properties));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
package com.ticketing.server.global.jwt;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.FilterChain;
|
||||
@@ -17,10 +17,12 @@ import org.springframework.web.filter.OncePerRequestFilter;
|
||||
public class JwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtProvider tokenProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final String accessHeader;
|
||||
private final String tokenPrefix;
|
||||
|
||||
public JwtFilter(JwtProperties jwtProperties, JwtProvider tokenProvider) {
|
||||
this.jwtProperties = jwtProperties;
|
||||
this.accessHeader = jwtProperties.getAccessHeader();
|
||||
this.tokenPrefix = jwtProperties.getPrefix();
|
||||
this.tokenProvider = tokenProvider;
|
||||
}
|
||||
|
||||
@@ -38,10 +40,11 @@ public class JwtFilter extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String bearerToken = request.getHeader(jwtProperties.getAccessHeader());
|
||||
if (StringUtils.hasText(bearerToken) && jwtProperties.hasTokenStartsWith(bearerToken)) {
|
||||
String bearerToken = request.getHeader(accessHeader);
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(tokenPrefix)) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
package com.ticketing.server.global.jwt;
|
||||
|
||||
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||
import lombok.Getter;
|
||||
@@ -10,18 +10,13 @@ import org.springframework.context.annotation.PropertySource;
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
@ConstructorBinding
|
||||
@ConfigurationProperties(value = "jwt")
|
||||
@ConfigurationProperties("jwt")
|
||||
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
|
||||
public class JwtProperties {
|
||||
|
||||
private final String accessHeader;
|
||||
private final String refreshHeader;
|
||||
private final String prefix;
|
||||
private final String secretKey;
|
||||
private final Integer accessTokenValidityInSeconds;
|
||||
private final Integer refreshTokenValidityInSeconds;
|
||||
private final Integer tokenValidityInSeconds;
|
||||
|
||||
public boolean hasTokenStartsWith(String token) {
|
||||
return token.startsWith(prefix);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
package com.ticketing.server.global.jwt;
|
||||
|
||||
import com.ticketing.server.user.application.response.TokenDto;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.MalformedJwtException;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.UnsupportedJwtException;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import io.jsonwebtoken.security.SecurityException;
|
||||
import java.security.Key;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
@@ -28,53 +31,29 @@ public class JwtProvider {
|
||||
private static final String AUTHORITIES_KEY = "auth";
|
||||
private static final String AUTHORITIES_DELIMITER = ",";
|
||||
|
||||
private final long tokenValidityInMilliseconds;
|
||||
private final Key key;
|
||||
private final String prefix;
|
||||
private final long accessTokenValidityInMilliseconds;
|
||||
private final long refreshTokenValidityInMilliseconds;
|
||||
|
||||
public JwtProvider(JwtProperties jwtProperties) {
|
||||
this.tokenValidityInMilliseconds = jwtProperties.getTokenValidityInSeconds();
|
||||
|
||||
byte[] keyBytes = Decoders.BASE64.decode(jwtProperties.getSecretKey());
|
||||
this.key = Keys.hmacShaKeyFor(keyBytes);
|
||||
|
||||
this.prefix = jwtProperties.getPrefix();
|
||||
this.accessTokenValidityInMilliseconds = jwtProperties.getAccessTokenValidityInSeconds() * 1000L;
|
||||
this.refreshTokenValidityInMilliseconds = jwtProperties.getRefreshTokenValidityInSeconds() * 1000L;
|
||||
}
|
||||
|
||||
public TokenDto generateTokenDto(Authentication authentication) {
|
||||
String accessToken = createAccessToken(authentication);
|
||||
String refreshToken = createRefreshToken(authentication);
|
||||
long expiresIn = accessTokenValidityInMilliseconds / 1000L;
|
||||
|
||||
return TokenDto.of(accessToken, refreshToken, prefix, expiresIn);
|
||||
}
|
||||
|
||||
private String createAccessToken(Authentication authentication) {
|
||||
// 만료시간 계산
|
||||
long now = (new Date()).getTime();
|
||||
Date accessTokenExpiresIn = new Date(now + this.accessTokenValidityInMilliseconds);
|
||||
|
||||
return createToken(authentication, accessTokenExpiresIn);
|
||||
}
|
||||
|
||||
private String createRefreshToken(Authentication authentication) {
|
||||
// 만료시간 계산
|
||||
long now = (new Date()).getTime();
|
||||
Date refreshTokenExpiresIn = new Date(now + this.refreshTokenValidityInMilliseconds);
|
||||
|
||||
return createToken(authentication, refreshTokenExpiresIn);
|
||||
}
|
||||
|
||||
private String createToken(Authentication authentication, Date expiration) {
|
||||
public String createToken(Authentication authentication) {
|
||||
// 권한 정보 가져오기
|
||||
String authorities = generateStringToAuthorities(authentication);
|
||||
|
||||
// 만료시간 계산
|
||||
long now = new Date().getTime();
|
||||
Date accessTokenExpiresIn = new Date(now + this.tokenValidityInMilliseconds);
|
||||
|
||||
// JWT 생성
|
||||
return Jwts.builder()
|
||||
.setSubject(authentication.getName()) // email
|
||||
.claim(AUTHORITIES_KEY, authorities) // payload
|
||||
.setExpiration(expiration) // 만료일
|
||||
.setExpiration(accessTokenExpiresIn) // 만료일
|
||||
.signWith(key, SignatureAlgorithm.HS512) // 서명 키 값
|
||||
.compact();
|
||||
}
|
||||
@@ -96,7 +75,6 @@ public class JwtProvider {
|
||||
// 토큰 복호화
|
||||
Claims claims = parseClaims(token);
|
||||
|
||||
// 권한조회
|
||||
List<SimpleGrantedAuthority> authorities =
|
||||
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(AUTHORITIES_DELIMITER))
|
||||
.map(SimpleGrantedAuthority::new)
|
||||
@@ -107,12 +85,25 @@ public class JwtProvider {
|
||||
}
|
||||
|
||||
public boolean validateToken(String token) {
|
||||
parseClaims(token);
|
||||
return true;
|
||||
try {
|
||||
parseClaims(token);
|
||||
return true;
|
||||
} catch (SecurityException | MalformedJwtException exception) {
|
||||
log.info("잘못된 JWT 서명입니다.");
|
||||
} catch (ExpiredJwtException e) {
|
||||
log.info("잘못된 JWT 토큰입니다.");
|
||||
} catch (UnsupportedJwtException e) {
|
||||
log.info("지원되지 않는 JWT 토큰입니다.");
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.info("JWT 토큰이 잘못되었습니다.");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private Claims parseClaims(String token) {
|
||||
return Jwts.parserBuilder()
|
||||
return Jwts
|
||||
.parserBuilder()
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
package com.ticketing.server.global.jwt;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.jwt.handle;
|
||||
package com.ticketing.server.global.jwt.handle;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.jwt.handle;
|
||||
package com.ticketing.server.global.jwt.handle;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
@Configuration
|
||||
@EnableRedisRepositories
|
||||
public class RedisConfig {
|
||||
|
||||
@Value("${spring.redis.host}")
|
||||
private String host;
|
||||
|
||||
@Value("${spring.redis.port}")
|
||||
private int port;
|
||||
|
||||
@Bean
|
||||
public RedisConnectionFactory redisConnectionFactory() {
|
||||
return new LettuceConnectionFactory(host, port);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate() {
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory());
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new StringRedisSerializer());
|
||||
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
return new JpaTransactionManager();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface RefreshRedisRepository extends CrudRepository<RefreshToken, Long> {
|
||||
|
||||
Optional<RefreshToken> findByEmail(String email);
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.data.redis.core.RedisHash;
|
||||
import org.springframework.data.redis.core.index.Indexed;
|
||||
|
||||
@Getter
|
||||
@RedisHash("RefreshToken")
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
public class RefreshToken {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
@Column(name = "refresh_token_id")
|
||||
private Long id;
|
||||
|
||||
@Indexed
|
||||
private String email;
|
||||
private String token;
|
||||
|
||||
public RefreshToken(String email, String token) {
|
||||
this.email = email;
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public void changeToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
package com.ticketing.server.global.security;
|
||||
|
||||
import com.ticketing.server.global.security.jwt.JwtFilter;
|
||||
import com.ticketing.server.global.security.jwt.JwtSecurityConfig;
|
||||
import com.ticketing.server.global.security.jwt.handle.JwtAccessDeniedHandler;
|
||||
import com.ticketing.server.global.security.jwt.handle.JwtAuthenticationEntryPoint;
|
||||
import com.ticketing.server.global.jwt.JwtFilter;
|
||||
import com.ticketing.server.global.jwt.JwtSecurityConfig;
|
||||
import com.ticketing.server.global.jwt.handle.JwtAccessDeniedHandler;
|
||||
import com.ticketing.server.global.jwt.handle.JwtAuthenticationEntryPoint;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
@@ -53,14 +52,12 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers(HttpMethod.POST, "/api/user/login").permitAll()
|
||||
.antMatchers(HttpMethod.POST, "/api/user/refresh").permitAll()
|
||||
.antMatchers(HttpMethod.POST, "/api/user").permitAll()
|
||||
.antMatchers("/api/movies/**").permitAll()
|
||||
.antMatchers(HttpMethod.POST, "/user").permitAll()
|
||||
.antMatchers(HttpMethod.POST, "/user/login").permitAll()
|
||||
.antMatchers("/l7check").permitAll()
|
||||
.antMatchers("/actuator/**").permitAll()
|
||||
.antMatchers("/api/v3/", "/swagger-ui/**", "/swagger/", "/swagger-resources/**", "/v3/api-docs").permitAll()
|
||||
.antMatchers("/actuator/health").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
|
||||
.and()
|
||||
.apply(new JwtSecurityConfig(jwtFilter));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.service;
|
||||
package com.ticketing.server.global.service;
|
||||
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||
@@ -1,30 +1,8 @@
|
||||
package com.ticketing.server.movie.application;
|
||||
|
||||
import com.ticketing.server.movie.application.response.MovieListResponse;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/movies")
|
||||
@Api(value = "Movie API", tags = {"Movie"})
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MovieController {
|
||||
|
||||
private final MovieService movieService;
|
||||
|
||||
@GetMapping()
|
||||
@ApiOperation(value = "영화 목록 조회")
|
||||
public ResponseEntity<MovieListResponse> getMovies() {
|
||||
return ResponseEntity.status(HttpStatus.OK).body(MovieListResponse.from(movieService.getMovies()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.ticketing.server.movie.application.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.ticketing.server.movie.service.dto.MovieDto;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import java.util.List;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class MovieListResponse {
|
||||
|
||||
@ApiModelProperty(value = "영화 제목")
|
||||
@JsonProperty
|
||||
private List<MovieDto> movieDtos;
|
||||
|
||||
public static MovieListResponse from(List<MovieDto> movieDtos) {
|
||||
return new MovieListResponse(movieDtos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.ticketing.server.movie.domain;
|
||||
|
||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||
import com.ticketing.server.movie.service.dto.MovieDto;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.validation.constraints.NotNull;
|
||||
@@ -22,8 +21,4 @@ public class Movie extends AbstractEntity {
|
||||
@NotNull
|
||||
private Integer runningTime;
|
||||
|
||||
public MovieDto toDto() {
|
||||
return new MovieDto(this.title);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.ticketing.server.movie.domain.repository;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@@ -13,9 +10,4 @@ public interface MovieRepository extends JpaRepository<Movie, Long> {
|
||||
|
||||
Optional<Movie> findByTitle(String title);
|
||||
|
||||
@Query(value = "SELECT * "
|
||||
+ "FROM movie "
|
||||
+ "WHERE deleted_at IS NULL", nativeQuery = true)
|
||||
List<Movie> findValidMovies();
|
||||
|
||||
}
|
||||
|
||||
@@ -1,29 +1,9 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.repository.MovieRepository;
|
||||
import com.ticketing.server.movie.service.dto.MovieDto;
|
||||
import com.ticketing.server.movie.service.interfaces.MovieService;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MovieServiceImpl implements MovieService {
|
||||
|
||||
private final MovieRepository movieRepository;
|
||||
|
||||
public List<MovieDto> getMovies() {
|
||||
List<Movie> movies = movieRepository.findValidMovies();
|
||||
|
||||
return movies.stream()
|
||||
.map(movie -> movie.toDto())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.ticketing.server.movie.service.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
@AllArgsConstructor
|
||||
public class MovieDto {
|
||||
|
||||
@JsonProperty
|
||||
private String title;
|
||||
|
||||
}
|
||||
@@ -1,10 +1,5 @@
|
||||
package com.ticketing.server.movie.service.interfaces;
|
||||
|
||||
import com.ticketing.server.movie.service.dto.MovieDto;
|
||||
import java.util.List;
|
||||
|
||||
public interface MovieService {
|
||||
|
||||
List<MovieDto> getMovies();
|
||||
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
package com.ticketing.server.user.application;
|
||||
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import com.ticketing.server.global.jwt.JwtProperties;
|
||||
import com.ticketing.server.user.application.request.LoginRequest;
|
||||
import com.ticketing.server.user.application.request.SignUpRequest;
|
||||
import com.ticketing.server.user.application.request.UserDeleteRequest;
|
||||
import com.ticketing.server.user.application.request.UserModifyPasswordRequest;
|
||||
import com.ticketing.server.user.application.response.LoginResponse;
|
||||
import com.ticketing.server.user.application.response.SignUpResponse;
|
||||
import com.ticketing.server.user.application.response.TokenDto;
|
||||
import com.ticketing.server.user.application.response.UserChangePasswordResponse;
|
||||
import com.ticketing.server.user.application.response.UserDeleteResponse;
|
||||
import com.ticketing.server.user.application.response.UserDetailResponse;
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.service.UserServiceImpl;
|
||||
import com.ticketing.server.user.service.interfaces.AuthenticationService;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -20,50 +18,39 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/user")
|
||||
@Slf4j
|
||||
|
||||
public class UserController {
|
||||
|
||||
private final UserServiceImpl userService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtProperties jwtProperties;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<SignUpResponse> register(@RequestBody @Valid SignUpRequest request) {
|
||||
User user = userService.register(request.toSignUpDto(passwordEncoder));
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(SignUpResponse.from(user));
|
||||
}
|
||||
|
||||
@GetMapping("/info")
|
||||
@Secured("ROLE_GUEST")
|
||||
public ResponseEntity<UserDetailResponse> myInfo(@AuthenticationPrincipal UserDetails userRequest) {
|
||||
User user = userService.findByEmail(userRequest.getUsername());
|
||||
return ResponseEntity.status(HttpStatus.OK).body(UserDetailResponse.from(user));
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(SignUpResponse.of(user));
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
@Secured("ROLE_GUEST")
|
||||
public ResponseEntity<UserDeleteResponse> deleteUser(@RequestBody @Valid UserDeleteRequest request) {
|
||||
User user = userService.delete(request.toDeleteUserDto(passwordEncoder));
|
||||
return ResponseEntity.status(HttpStatus.OK).body(UserDeleteResponse.from(user));
|
||||
return ResponseEntity.status(HttpStatus.OK).body(UserDeleteResponse.of(user));
|
||||
}
|
||||
|
||||
@PutMapping("/password")
|
||||
@PatchMapping("/password")
|
||||
@Secured("ROLE_GUEST")
|
||||
public ResponseEntity<UserChangePasswordResponse> changePassword(@RequestBody @Valid UserModifyPasswordRequest request) {
|
||||
if (request.oldEqualNew()) {
|
||||
@@ -72,25 +59,15 @@ public class UserController {
|
||||
}
|
||||
|
||||
User user = userService.changePassword(request.toChangePasswordDto(passwordEncoder));
|
||||
return ResponseEntity.status(HttpStatus.OK).body(UserChangePasswordResponse.from(user));
|
||||
return ResponseEntity.status(HttpStatus.OK).body(UserChangePasswordResponse.of(user));
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<TokenDto> login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
|
||||
TokenDto tokenDto = authenticationService.login(loginRequest.toAuthentication());
|
||||
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
|
||||
String accessToken = userService.login(loginRequest.toAuthentication());
|
||||
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.setHeader("Pragma", "no-store");
|
||||
return ResponseEntity.status(HttpStatus.OK).body(tokenDto);
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
public ResponseEntity<TokenDto> refreshToken(@RequestParam("refreshToken") String refreshToken, HttpServletResponse response) {
|
||||
TokenDto tokenDto = authenticationService.reissueAccessToken(refreshToken);
|
||||
|
||||
response.setHeader(jwtProperties.getAccessHeader(), tokenDto.getAccessToken());
|
||||
response.setHeader(jwtProperties.getRefreshHeader(), tokenDto.getRefreshToken());
|
||||
return ResponseEntity.status(HttpStatus.OK).body(tokenDto);
|
||||
response.setHeader(jwtProperties.getAccessHeader(), accessToken);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(LoginResponse.of(accessToken));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.ticketing.server.user.application.response;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class LoginResponse {
|
||||
|
||||
private String accessToken;
|
||||
|
||||
public static LoginResponse of(String accessToken) {
|
||||
return new LoginResponse(accessToken);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,7 +13,7 @@ public class SignUpResponse {
|
||||
|
||||
private String email;
|
||||
|
||||
public static SignUpResponse from(User user) {
|
||||
public static SignUpResponse of(User user) {
|
||||
return new SignUpResponse(user.getName(), user.getEmail());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.ticketing.server.user.application.response;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class TokenDto {
|
||||
|
||||
private final String accessToken;
|
||||
private final String refreshToken;
|
||||
private final String tokenType;
|
||||
private final long expiresIn;
|
||||
|
||||
public static TokenDto of(String accessToken, String refreshToken, String tokenType, long expiresIn) {
|
||||
return new TokenDto(accessToken, refreshToken, tokenType, expiresIn);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,7 +13,7 @@ public class UserChangePasswordResponse {
|
||||
|
||||
private String email;
|
||||
|
||||
public static UserChangePasswordResponse from(User user) {
|
||||
public static UserChangePasswordResponse of(User user) {
|
||||
return new UserChangePasswordResponse(user.getName(), user.getEmail());
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ public class UserDeleteResponse {
|
||||
|
||||
private String email;
|
||||
|
||||
public static UserDeleteResponse from(User user) {
|
||||
public static UserDeleteResponse of(User user) {
|
||||
return new UserDeleteResponse(user.getName(), user.getEmail());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.ticketing.server.user.application.response;
|
||||
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class UserDetailResponse {
|
||||
|
||||
private String name;
|
||||
private String email;
|
||||
private UserGrade grade;
|
||||
private String phone;
|
||||
|
||||
public static UserDetailResponse from(User user) {
|
||||
return new UserDetailResponse(user.getName(), user.getEmail(), user.getGrade(), user.getPhone());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package com.ticketing.server.user.service;
|
||||
|
||||
import com.ticketing.server.global.exception.token.TokenNotFindException;
|
||||
import com.ticketing.server.global.exception.token.TokenTypeException;
|
||||
import com.ticketing.server.global.exception.token.UnavailableRefreshTokenException;
|
||||
import com.ticketing.server.global.redis.RefreshRedisRepository;
|
||||
import com.ticketing.server.global.redis.RefreshToken;
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import com.ticketing.server.global.security.jwt.JwtProvider;
|
||||
import com.ticketing.server.user.application.response.TokenDto;
|
||||
import com.ticketing.server.user.service.interfaces.AuthenticationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthenticationServiceImpl implements AuthenticationService {
|
||||
|
||||
private final RefreshRedisRepository refreshRedisRepository;
|
||||
|
||||
private final JwtProvider jwtProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final AuthenticationManagerBuilder authenticationManagerBuilder;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public TokenDto login(UsernamePasswordAuthenticationToken authenticationToken) {
|
||||
// 회원인증
|
||||
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
|
||||
|
||||
String email = authenticationToken.getName();
|
||||
|
||||
// 토큰 발급
|
||||
TokenDto tokenDto = jwtProvider.generateTokenDto(authentication);
|
||||
|
||||
// refresh 토큰이 있으면 수정, 없으면 생성
|
||||
refreshRedisRepository.findByEmail(email)
|
||||
.ifPresentOrElse(
|
||||
tokenEntity -> tokenEntity.changeToken(tokenDto.getRefreshToken()),
|
||||
() -> refreshRedisRepository.save(new RefreshToken(email, tokenDto.getRefreshToken()))
|
||||
);
|
||||
|
||||
return tokenDto;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public TokenDto reissueAccessToken(String bearerRefreshToken) {
|
||||
String refreshToken = resolveToken(bearerRefreshToken);
|
||||
|
||||
// 토큰 검증
|
||||
jwtProvider.validateToken(refreshToken);
|
||||
|
||||
Authentication authentication = jwtProvider.getAuthentication(refreshToken);
|
||||
|
||||
// Redis 에 토큰이 있는지 검증
|
||||
RefreshToken findTokenEntity = refreshRedisRepository.findByEmail(authentication.getName())
|
||||
.orElseThrow(TokenNotFindException::new);
|
||||
|
||||
// redis 토큰과 input 토큰이 일치한지 확인
|
||||
if (!refreshToken.equals(findTokenEntity.getToken())) {
|
||||
throw new UnavailableRefreshTokenException();
|
||||
}
|
||||
|
||||
// 토큰 발급
|
||||
TokenDto tokenDto = jwtProvider.generateTokenDto(authentication);
|
||||
|
||||
// 토큰 최신화
|
||||
findTokenEntity.changeToken(tokenDto.getRefreshToken());
|
||||
refreshRedisRepository.save(findTokenEntity);
|
||||
|
||||
return tokenDto;
|
||||
}
|
||||
|
||||
private String resolveToken(String bearerToken) {
|
||||
if (StringUtils.hasText(bearerToken) && jwtProperties.hasTokenStartsWith(bearerToken)) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
throw new TokenTypeException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.ticketing.server.user.service;
|
||||
|
||||
import com.ticketing.server.global.exception.EmailNotFoundException;
|
||||
import com.ticketing.server.global.exception.NotFoundEmailException;
|
||||
import com.ticketing.server.global.jwt.JwtProvider;
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||
import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
||||
@@ -11,6 +12,9 @@ import java.util.Optional;
|
||||
import javax.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
@@ -23,6 +27,14 @@ import org.springframework.validation.annotation.Validated;
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final AuthenticationManagerBuilder authenticationManagerBuilder;
|
||||
private final JwtProvider jwtProvider;
|
||||
|
||||
@Override
|
||||
public String login(UsernamePasswordAuthenticationToken authenticationToken) {
|
||||
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
|
||||
return jwtProvider.createToken(authentication);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@@ -39,7 +51,13 @@ public class UserServiceImpl implements UserService {
|
||||
@Override
|
||||
@Transactional
|
||||
public User delete(@Valid DeleteUserDTO deleteUserDto) {
|
||||
User user = findByEmail(deleteUserDto.getEmail());
|
||||
User user = userRepository.findByEmail(deleteUserDto.getEmail())
|
||||
.orElseThrow(() -> {
|
||||
log.error("존재하지 않는 이메일 입니다. :: {}", deleteUserDto.getEmail());
|
||||
throw new NotFoundEmailException();
|
||||
}
|
||||
);
|
||||
|
||||
return user.delete(deleteUserDto);
|
||||
}
|
||||
|
||||
@@ -50,21 +68,11 @@ public class UserServiceImpl implements UserService {
|
||||
return user.changePassword(changePasswordDto);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User findByEmail(String email) {
|
||||
return userRepository.findByEmail(email)
|
||||
.orElseThrow(() -> {
|
||||
log.error("존재하지 않는 이메일 입니다. :: {}", email);
|
||||
throw new EmailNotFoundException();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private User findNotDeletedUserByEmail(String email) {
|
||||
return userRepository.findByEmailAndIsDeletedFalse(email)
|
||||
.orElseThrow(() -> {
|
||||
log.error("존재하지 않는 이메일 입니다. :: {}", email);
|
||||
throw new EmailNotFoundException();
|
||||
throw new NotFoundEmailException();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,13 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
public class ChangePasswordDTO implements PasswordMatches {
|
||||
|
||||
public ChangePasswordDTO(String email, String oldPassword, String newPassword, PasswordEncoder passwordEncoder) {
|
||||
this.email = email;
|
||||
this.oldPassword = oldPassword;
|
||||
this.newPassword = newPassword;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@NotEmpty(message = "{validation.not.empty.email}")
|
||||
@Email(message = "{validation.email}")
|
||||
private String email;
|
||||
@@ -18,13 +25,6 @@ public class ChangePasswordDTO implements PasswordMatches {
|
||||
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
public ChangePasswordDTO(String email, String oldPassword, String newPassword, PasswordEncoder passwordEncoder) {
|
||||
this.email = email;
|
||||
this.oldPassword = oldPassword;
|
||||
this.newPassword = newPassword;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,12 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
public class DeleteUserDTO implements PasswordMatches {
|
||||
|
||||
public DeleteUserDTO(String email, String inputPassword, PasswordEncoder passwordEncoder) {
|
||||
this.email = email;
|
||||
this.inputPassword = inputPassword;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@NotEmpty(message = "{validation.not.empty.email}")
|
||||
@Email(message = "{validation.email}")
|
||||
private String email;
|
||||
@@ -15,12 +21,6 @@ public class DeleteUserDTO implements PasswordMatches {
|
||||
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
public DeleteUserDTO(String email, String inputPassword, PasswordEncoder passwordEncoder) {
|
||||
this.email = email;
|
||||
this.inputPassword = inputPassword;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean passwordMatches(String password) {
|
||||
return passwordEncoder.matches(this.inputPassword, password);
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.ticketing.server.user.service.interfaces;
|
||||
|
||||
import com.ticketing.server.user.application.response.TokenDto;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
|
||||
public interface AuthenticationService {
|
||||
|
||||
TokenDto login(UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken);
|
||||
|
||||
TokenDto reissueAccessToken(String bearerRefreshToken);
|
||||
|
||||
}
|
||||
@@ -5,14 +5,17 @@ import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
||||
import com.ticketing.server.user.service.dto.DeleteUserDTO;
|
||||
import com.ticketing.server.user.service.dto.SignUpDTO;
|
||||
import javax.validation.Valid;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
public interface UserService {
|
||||
|
||||
String login(UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken);
|
||||
|
||||
User register(@Valid SignUpDTO signUpDto);
|
||||
|
||||
User delete(@Valid DeleteUserDTO deleteUserDto);
|
||||
|
||||
User changePassword(@Valid ChangePasswordDTO changePasswordDto);
|
||||
|
||||
User findByEmail(String email);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,6 @@ server:
|
||||
spring:
|
||||
profiles:
|
||||
active: local
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
@@ -18,23 +15,12 @@ spring:
|
||||
maximum-pool-size: 10 # default 10
|
||||
max-lifetime: 1800000 # default 30 minutes
|
||||
|
||||
mvc:
|
||||
pathmatch:
|
||||
matching-strategy: ant_path_matcher
|
||||
|
||||
jasypt:
|
||||
encryptor:
|
||||
bean: jasyptStringEncryptor
|
||||
|
||||
jwt:
|
||||
access-header: Authorization
|
||||
refresh-header: REFRESH_TOKEN
|
||||
access-header: ACCESS_TOKEN
|
||||
prefix: Bearer
|
||||
secret-key: Zi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXktZi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXkK
|
||||
access-token-validity-in-seconds: 60 # 1분
|
||||
refresh-token-validity-in-seconds: 259200 # 3일
|
||||
|
||||
springfox:
|
||||
documentation:
|
||||
swagger:
|
||||
use-model-v3: false
|
||||
token-validity-in-seconds: 86400
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
package com.ticketing.server.global.jwt;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
@@ -27,38 +27,10 @@ class JwtPropertiesTest {
|
||||
// when
|
||||
// then
|
||||
assertAll(
|
||||
() -> assertThat(jwtProperties.getAccessHeader()).isEqualTo("Authorization")
|
||||
, () -> assertThat(jwtProperties.getRefreshHeader()).isEqualTo("REFRESH_TOKEN")
|
||||
() -> assertThat(jwtProperties.getAccessHeader()).isEqualTo("ACCESS_TOKEN")
|
||||
, () -> assertThat(jwtProperties.getPrefix()).isEqualTo("Bearer")
|
||||
, () -> assertThat(jwtProperties.getAccessTokenValidityInSeconds()).isEqualTo(60)
|
||||
, () -> assertThat(jwtProperties.getRefreshTokenValidityInSeconds()).isEqualTo(259200)
|
||||
, () -> assertThat(jwtProperties.getTokenValidityInSeconds()).isEqualTo(86400)
|
||||
, () -> assertThat(jwtProperties.getSecretKey()).isNotEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("token prefix 가 일치할 경우")
|
||||
void hasTokenStartsWithTrue() {
|
||||
// given
|
||||
String token = jwtProperties.getPrefix() + " " + "tokenPrefixTest";
|
||||
|
||||
// when
|
||||
boolean result = jwtProperties.hasTokenStartsWith(token);
|
||||
|
||||
// then
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("token prefix 가 일치하지 않을 경우")
|
||||
void hasTokenStartsWithFalse() {
|
||||
// given
|
||||
String token = "tokenPrefixTest";
|
||||
|
||||
// when
|
||||
boolean result = jwtProperties.hasTokenStartsWith(token);
|
||||
|
||||
// then
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
package com.ticketing.server.global.security.jwt;
|
||||
package com.ticketing.server.global.jwt;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||
import com.ticketing.server.user.application.response.TokenDto;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import java.util.Collections;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -26,12 +25,12 @@ class TokenProviderTest {
|
||||
@Autowired
|
||||
private JwtProperties jwtProperties;
|
||||
|
||||
JwtProvider jwtProvider;
|
||||
JwtProvider tokenProvider;
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
jwtProvider = new JwtProvider(jwtProperties);
|
||||
tokenProvider = new JwtProvider(jwtProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -43,10 +42,10 @@ class TokenProviderTest {
|
||||
new UsernamePasswordAuthenticationToken("ticketing@gmail.com", "123456", Collections.singleton(grantedAuthority));
|
||||
|
||||
// when
|
||||
TokenDto tokenDto = jwtProvider.generateTokenDto(authenticationToken);
|
||||
String token = tokenProvider.createToken(authenticationToken);
|
||||
|
||||
// then
|
||||
assertThat(tokenDto).isInstanceOf(TokenDto.class);
|
||||
assertThat(token).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,8 +57,8 @@ class TokenProviderTest {
|
||||
new UsernamePasswordAuthenticationToken("ticketing@gmail.com", "123456", Collections.singleton(grantedAuthority));
|
||||
|
||||
// when
|
||||
TokenDto tokenDto = jwtProvider.generateTokenDto(authenticationToken);
|
||||
Authentication authentication = jwtProvider.getAuthentication(tokenDto.getAccessToken());
|
||||
String token = tokenProvider.createToken(authenticationToken);
|
||||
Authentication authentication = tokenProvider.getAuthentication(token);
|
||||
|
||||
// then
|
||||
assertThat(authentication.getName()).isEqualTo("ticketing@gmail.com");
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.ticketing.server.global.redis;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class RefreshRedisRepositoryTest {
|
||||
|
||||
@Autowired
|
||||
RefreshRedisRepository refreshRedisRepository;
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
refreshRedisRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 등록 및 조회기능")
|
||||
void saveAndFind() {
|
||||
// given
|
||||
RefreshToken refreshToken = new RefreshToken("ticketing@gmail.com", "refreshToken");
|
||||
|
||||
// when
|
||||
refreshRedisRepository.save(refreshToken);
|
||||
|
||||
// then
|
||||
RefreshToken findRefreshToken = refreshRedisRepository.findById(refreshToken.getId()).get();
|
||||
assertAll(
|
||||
() -> assertThat(findRefreshToken.getEmail()).isEqualTo("ticketing@gmail.com")
|
||||
, () -> assertThat(findRefreshToken.getToken()).isEqualTo("refreshToken")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 등록 및 이메일 조회")
|
||||
void saveAndFindByEmail() {
|
||||
// given
|
||||
RefreshToken refreshToken = new RefreshToken("ticketing@gmail.com", "refreshToken");
|
||||
|
||||
// when
|
||||
refreshRedisRepository.save(refreshToken);
|
||||
|
||||
// then
|
||||
RefreshToken findRefreshToken = refreshRedisRepository.findByEmail(refreshToken.getEmail()).get();
|
||||
assertAll(
|
||||
() -> assertThat(findRefreshToken.getEmail()).isEqualTo("ticketing@gmail.com")
|
||||
, () -> assertThat(findRefreshToken.getToken()).isEqualTo("refreshToken")
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 등록 및 수정기능")
|
||||
void saveAndSave() {
|
||||
// given
|
||||
RefreshToken refreshToken = new RefreshToken("ticketing@gmail.com", "refreshToken");
|
||||
refreshRedisRepository.save(refreshToken);
|
||||
Long id = refreshToken.getId();
|
||||
|
||||
// when
|
||||
RefreshToken savedRefreshToken = refreshRedisRepository.findById(id).get();
|
||||
savedRefreshToken.changeToken("refreshToken2");
|
||||
refreshRedisRepository.save(savedRefreshToken);
|
||||
|
||||
// then
|
||||
RefreshToken lastSavedRefreshToken = refreshRedisRepository.findById(id).get();
|
||||
assertThat(lastSavedRefreshToken.getToken()).isEqualTo("refreshToken2");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public class MovieRepositoryTest {
|
||||
@Order(1)
|
||||
@Test
|
||||
@Rollback(value = false)
|
||||
@DisplayName("Movie Repository Test - saving movie")
|
||||
@DisplayName("Movie Repository - test saving movie")
|
||||
void shouldAbleToSaveMovie() {
|
||||
// given
|
||||
Movie movie = new Movie("범죄도시 2", 106);
|
||||
|
||||
@@ -1,66 +1,9 @@
|
||||
package com.ticketing.server.movie.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.ticketing.server.movie.domain.Movie;
|
||||
import com.ticketing.server.movie.domain.repository.MovieRepository;
|
||||
import com.ticketing.server.movie.service.dto.MovieDto;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class MovieServiceImplTest {
|
||||
|
||||
Movie movie;
|
||||
MovieDto movieDto;
|
||||
List<Movie> movies = new ArrayList<>();
|
||||
List<MovieDto> movieDtos = new ArrayList<>();
|
||||
|
||||
@Mock
|
||||
MovieRepository movieRepository;
|
||||
|
||||
@InjectMocks
|
||||
MovieServiceImpl movieService;
|
||||
|
||||
@Test
|
||||
@DisplayName("Movie Service Test - get movies when there is no movie")
|
||||
void shouldGetEmptyList() {
|
||||
// given
|
||||
when(movieRepository.findValidMovies()).thenReturn(Collections.emptyList());
|
||||
|
||||
// when
|
||||
List<MovieDto> movieDtoList = movieService.getMovies();
|
||||
|
||||
// then
|
||||
assertTrue(movieDtoList.isEmpty());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Movie Service Test - get movies")
|
||||
void shouldAbleToGetMovies() {
|
||||
// given
|
||||
movie = new Movie("범죄도시2", 106);
|
||||
movieDto = movie.toDto();
|
||||
movies.add(movie);
|
||||
movieDtos.add(movieDto);
|
||||
|
||||
when(movieRepository.findValidMovies()).thenReturn(movies);
|
||||
|
||||
// when
|
||||
List<MovieDto> movieDtoList = movieService.getMovies();
|
||||
|
||||
// then
|
||||
assertTrue(!movieDtoList.isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,15 +3,14 @@ package com.ticketing.server.user.application;
|
||||
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ticketing.server.global.redis.RefreshRedisRepository;
|
||||
import com.ticketing.server.user.application.request.LoginRequest;
|
||||
import com.ticketing.server.user.application.request.SignUpRequest;
|
||||
import com.ticketing.server.user.service.interfaces.UserService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -41,11 +40,22 @@ class UserControllerTest {
|
||||
@Autowired
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
RefreshRedisRepository refreshRedisRepository;
|
||||
|
||||
MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void init() throws Exception {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
|
||||
SignUpRequest signUpRequest = new SignUpRequest("ticketing", "ticketing@gmail.com", "qwe123", "010-2240-7920");
|
||||
|
||||
mvc.perform(post("/user")
|
||||
.content(asJsonString(signUpRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("로그인 인증 성공")
|
||||
void loginSuccess() throws Exception {
|
||||
@@ -53,13 +63,14 @@ class UserControllerTest {
|
||||
LoginRequest request = new LoginRequest("ticketing@gmail.com", "qwe123");
|
||||
|
||||
// when
|
||||
ResultActions actions = mvc.perform(post("/api/user/login")
|
||||
ResultActions actions = mvc.perform(post("/user/login")
|
||||
.content(asJsonString(request))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
// then
|
||||
actions.andDo(print())
|
||||
.andExpect(status().isOk());
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("ACCESS_TOKEN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,7 +80,7 @@ class UserControllerTest {
|
||||
LoginRequest request = new LoginRequest("ticketing@gmail.com", "qwe1234");
|
||||
|
||||
// when
|
||||
ResultActions actions = mvc.perform(post("/api/user/login")
|
||||
ResultActions actions = mvc.perform(post("/user/login")
|
||||
.content(asJsonString(request))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
|
||||
@@ -82,23 +93,4 @@ class UserControllerTest {
|
||||
return objectMapper.writeValueAsString(object);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void init() throws Exception {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
|
||||
SignUpRequest signUpRequest = new SignUpRequest("ticketing", "ticketing@gmail.com", "qwe123", "010-2240-7920");
|
||||
|
||||
mvc.perform(post("/api/user")
|
||||
.content(asJsonString(signUpRequest))
|
||||
.contentType(MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
refreshRedisRepository.deleteAll();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
package com.ticketing.server.user.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||
import com.ticketing.server.global.redis.RefreshRedisRepository;
|
||||
import com.ticketing.server.global.redis.RefreshToken;
|
||||
import com.ticketing.server.global.security.jwt.JwtProperties;
|
||||
import com.ticketing.server.global.security.jwt.JwtProvider;
|
||||
import com.ticketing.server.user.application.response.TokenDto;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@EnableConfigurationProperties(value = JwtProperties.class)
|
||||
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
|
||||
class AuthenticationServiceImplTest {
|
||||
|
||||
@Autowired
|
||||
private JwtProperties useJwtProperties;
|
||||
private JwtProvider useJwtProvider;
|
||||
|
||||
@Mock
|
||||
JwtProperties jwtProperties;
|
||||
|
||||
@Mock
|
||||
JwtProvider jwtProvider;
|
||||
|
||||
@Mock
|
||||
RefreshRedisRepository redisRepository;
|
||||
|
||||
@InjectMocks
|
||||
AuthenticationServiceImpl authenticationService;
|
||||
|
||||
UsernamePasswordAuthenticationToken authenticationToken;
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
useJwtProvider = new JwtProvider(useJwtProperties);
|
||||
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(UserGrade.GUEST.name());
|
||||
authenticationToken =
|
||||
new UsernamePasswordAuthenticationToken("ticketing@gmail.com", "123456", Collections.singleton(grantedAuthority));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("토큰 재발급 성공")
|
||||
void reissueAccessToken() {
|
||||
// given
|
||||
String refreshToken = "Bearer eyJhbGciOiJIUzUxMiJ9";
|
||||
when(jwtProvider.validateToken(any())).thenReturn(true);
|
||||
when(jwtProvider.getAuthentication(any())).thenReturn(authenticationToken);
|
||||
when(jwtProvider.generateTokenDto(any())).thenReturn(useJwtProvider.generateTokenDto(authenticationToken));
|
||||
when(redisRepository.findByEmail("ticketing@gmail.com")).thenReturn(Optional.of(new RefreshToken("ticketing@gmail.com", "eyJhbGciOiJIUzUxMiJ9")));
|
||||
when(jwtProperties.hasTokenStartsWith(refreshToken)).thenReturn(true);
|
||||
|
||||
// when
|
||||
TokenDto tokenDto = authenticationService.reissueAccessToken(refreshToken);
|
||||
|
||||
// then
|
||||
assertAll(
|
||||
() -> assertThat(tokenDto.getAccessToken()).isNotEmpty()
|
||||
, () -> assertThat(tokenDto.getRefreshToken()).isNotEmpty()
|
||||
, () -> assertThat(tokenDto.getTokenType()).isEqualTo("Bearer")
|
||||
, () -> assertThat(tokenDto.getExpiresIn()).isEqualTo(60)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,11 +2,10 @@ package com.ticketing.server.user.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.ticketing.server.global.exception.EmailNotFoundException;
|
||||
import com.ticketing.server.global.exception.NotFoundEmailException;
|
||||
import com.ticketing.server.user.domain.User;
|
||||
import com.ticketing.server.user.domain.UserGrade;
|
||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||
@@ -80,7 +79,7 @@ class UserServiceImplTest {
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> userService.delete(deleteUserDto))
|
||||
.isInstanceOf(EmailNotFoundException.class);
|
||||
.isInstanceOf(NotFoundEmailException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -93,10 +92,7 @@ class UserServiceImplTest {
|
||||
User user = userService.delete(deleteUserDto);
|
||||
|
||||
// then
|
||||
assertAll(
|
||||
() -> assertThat(user.isDeleted()).isTrue(),
|
||||
() -> assertThat(user.getDeletedAt()).isNotNull()
|
||||
);
|
||||
assertThat(user).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,7 +104,7 @@ class UserServiceImplTest {
|
||||
// when
|
||||
// then
|
||||
assertThatThrownBy(() -> userService.changePassword(changePasswordDto))
|
||||
.isInstanceOf(EmailNotFoundException.class);
|
||||
.isInstanceOf(NotFoundEmailException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -4,9 +4,6 @@ spring:
|
||||
username: ENC(LowN1n4w0Ep/DqLD8+q5Bq6AXM4b8e3V)
|
||||
password: ENC(OMvGcpZLpggFTiGNkqNe66Zq/SmJXF6o)
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
|
||||
jpa:
|
||||
properties:
|
||||
@@ -16,22 +13,17 @@ spring:
|
||||
hibernate:
|
||||
ddl-auto: create
|
||||
|
||||
mvc:
|
||||
pathmatch:
|
||||
matching-strategy: ant_path_matcher
|
||||
|
||||
jasypt:
|
||||
encryptor:
|
||||
bean: jasyptStringEncryptor
|
||||
|
||||
jwt:
|
||||
access-header: Authorization
|
||||
refresh-header: REFRESH_TOKEN
|
||||
access-header: ACCESS_TOKEN
|
||||
prefix: Bearer
|
||||
secret-key: Zi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXktZi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXkK
|
||||
access-token-validity-in-seconds: 60
|
||||
refresh-token-validity-in-seconds: 259200
|
||||
token-validity-in-seconds: 86400
|
||||
|
||||
tmdb:
|
||||
api-key: 0d1503b6dcbfe1c514299b5564c649b8
|
||||
read-access-token: eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwZDE1MDNiNmRjYmZlMWM1MTQyOTliNTU2NGM2NDliOCIsInN1YiI6IjYyOWYwODRlNzI2ZmIxMTA2NDA4MjI2NCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.rs8KZea8QLyashILiggWFx2s46lgUtzo-xSWoDgE58A
|
||||
|
||||
|
||||
Reference in New Issue
Block a user