Compare commits
6 Commits
feature/de
...
feature/te
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
994db8afad | ||
|
|
dabee5c844 | ||
|
|
24c8039031 | ||
|
|
270edc20b5 | ||
|
|
2b249e3be9 | ||
|
|
0c26555665 |
9
.idea/Ticketing.iml
generated
Normal file
9
.idea/Ticketing.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="JAVA_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||||
|
<exclude-output />
|
||||||
|
<content url="file://$MODULE_DIR$" />
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/Ticketing.iml" filepath="$PROJECT_DIR$/.idea/Ticketing.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
10
.idea/runConfigurations.xml
generated
Normal file
10
.idea/runConfigurations.xml
generated
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RunConfigurationProducerService">
|
||||||
|
<option name="ignoredProducers">
|
||||||
|
<set>
|
||||||
|
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
33
.idea/workspace.xml
generated
Normal file
33
.idea/workspace.xml
generated
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ChangeListManager">
|
||||||
|
<list default="true" id="2a93e153-a90c-44db-b1da-6c4424693422" name="Changes" comment="" />
|
||||||
|
<option name="SHOW_DIALOG" value="false" />
|
||||||
|
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||||
|
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||||
|
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||||
|
</component>
|
||||||
|
<component name="Git.Settings">
|
||||||
|
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectId" id="29uM8tIDp7UqdPYE3auX216NPaN" />
|
||||||
|
<component name="ProjectViewState">
|
||||||
|
<option name="hideEmptyMiddlePackages" value="true" />
|
||||||
|
<option name="showLibraryContents" value="true" />
|
||||||
|
</component>
|
||||||
|
<component name="PropertiesComponent">
|
||||||
|
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
|
||||||
|
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
|
||||||
|
</component>
|
||||||
|
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
||||||
|
<component name="TaskManager">
|
||||||
|
<task active="true" id="Default" summary="Default task">
|
||||||
|
<changelist id="2a93e153-a90c-44db-b1da-6c4424693422" name="Changes" comment="" />
|
||||||
|
<created>1653958362269</created>
|
||||||
|
<option name="number" value="Default" />
|
||||||
|
<option name="presentableId" value="Default" />
|
||||||
|
<updated>1653958362269</updated>
|
||||||
|
</task>
|
||||||
|
<servers />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
plugins {
|
plugins {
|
||||||
java
|
java
|
||||||
id("org.springframework.boot") version "2.6.7"
|
id("org.springframework.boot") version "2.6.7"
|
||||||
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
id("io.spring.dependency-management") version "1.0.11.RELEASE"
|
||||||
}
|
}
|
||||||
|
|
||||||
group = "com.ticketing"
|
group = "com.ticketing"
|
||||||
@@ -9,46 +9,59 @@ version = "0.0.1-SNAPSHOT"
|
|||||||
|
|
||||||
val javaVersion = JavaVersion.VERSION_11
|
val javaVersion = JavaVersion.VERSION_11
|
||||||
java {
|
java {
|
||||||
sourceCompatibility = javaVersion
|
sourceCompatibility = javaVersion
|
||||||
targetCompatibility = javaVersion
|
targetCompatibility = javaVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
configurations {
|
configurations {
|
||||||
compileOnly {
|
compileOnly {
|
||||||
extendsFrom(configurations.annotationProcessor.get())
|
extendsFrom(configurations.annotationProcessor.get())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
implementation("org.springframework.boot:spring-boot-starter-actuator")
|
||||||
implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4")
|
implementation("org.springframework.boot:spring-boot-starter-log4j2")
|
||||||
implementation("org.springframework.boot:spring-boot-starter-log4j2")
|
implementation("org.projectlombok:lombok:1.18.20")
|
||||||
implementation("com.lmax:disruptor:3.4.2")
|
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 {
|
modules {
|
||||||
module("org.springframework.boot:spring-boot-starter-logging") {
|
module("org.springframework.boot:spring-boot-starter-logging") {
|
||||||
replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")
|
replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
compileOnly("org.projectlombok:lombok")
|
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||||
runtimeOnly("mysql:mysql-connector-java")
|
testImplementation("org.springframework.security:spring-security-test")
|
||||||
annotationProcessor("org.projectlombok:lombok")
|
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1")
|
||||||
|
|
||||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
compileOnly("org.projectlombok:lombok")
|
||||||
testImplementation("org.springframework.security:spring-security-test")
|
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")
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.withType<Test> {
|
tasks.withType<Test> {
|
||||||
useJUnitPlatform()
|
useJUnitPlatform()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
package com.ticketing.server;
|
package com.ticketing.server;
|
||||||
|
|
||||||
|
import com.ticketing.server.global.jwt.JwtProperties;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||||
|
|
||||||
@EnableJpaAuditing
|
@EnableJpaAuditing
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
@EnableConfigurationProperties(JwtProperties.class)
|
||||||
public class ServerApplication {
|
public class ServerApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.ticketing.server.global.config;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.time.Duration;
|
||||||
|
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.client.BufferingClientHttpRequestFactory;
|
||||||
|
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||||
|
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class RestTemplateConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
|
||||||
|
return restTemplateBuilder
|
||||||
|
.requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
|
||||||
|
.setConnectTimeout(Duration.ofMillis(5000)) // connection-timeout
|
||||||
|
.setReadTimeout(Duration.ofMillis(5000)) // read-timeout
|
||||||
|
.additionalMessageConverters(new StringHttpMessageConverter(Charset.forName("UTF-8")))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package com.ticketing.server.global.config;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
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;
|
||||||
|
import springfox.documentation.spi.DocumentationType;
|
||||||
|
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||||
|
import springfox.documentation.spring.web.plugins.Docket;
|
||||||
|
import springfox.documentation.swagger.web.UiConfiguration;
|
||||||
|
import springfox.documentation.swagger.web.UiConfigurationBuilder;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@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()
|
||||||
|
.apiInfo(apiInfo())
|
||||||
|
.securityContexts(Arrays.asList(securityContext()))
|
||||||
|
.securitySchemes(Arrays.asList(apiKey()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiInfo apiInfo() {
|
||||||
|
return new ApiInfoBuilder()
|
||||||
|
.title("Ticketing REST API Document")
|
||||||
|
.version("v1")
|
||||||
|
.description("Ticketing REST API 문서").build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiKey apiKey() {
|
||||||
|
return new ApiKey(SECURITY_SCHEMA_NAME, "Authorization", "header");
|
||||||
|
}
|
||||||
|
|
||||||
|
private SecurityContext securityContext() {
|
||||||
|
return SecurityContext.builder().securityReferences(defaultAuth()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<SecurityReference> defaultAuth() {
|
||||||
|
AuthorizationScope authorizationScope = new AuthorizationScope(AUTHORIZATION_SCOPE_GLOBAL,
|
||||||
|
AUTHORIZATION_SCOPE_GLOBAL_DESC);
|
||||||
|
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
|
||||||
|
authorizationScopes[0] = authorizationScope;
|
||||||
|
return Arrays.asList(new SecurityReference(SECURITY_SCHEMA_NAME, authorizationScopes));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
UiConfiguration uiConfig() {
|
||||||
|
return UiConfigurationBuilder.builder()
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
package com.ticketing.server.global.config;
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
|
||||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@EnableWebSecurity
|
|
||||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public PasswordEncoder passwordEncoder() {
|
|
||||||
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
|
||||||
http
|
|
||||||
.cors().disable()
|
|
||||||
.csrf().disable()
|
|
||||||
.formLogin().disable()
|
|
||||||
.headers().frameOptions().disable();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.ticketing.server.global.factory;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
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;
|
||||||
|
|
||||||
|
public class YamlPropertySourceFactory implements PropertySourceFactory {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
|
||||||
|
Resource resource = encodedResource.getResource();
|
||||||
|
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
|
||||||
|
factoryBean.setResources(resource);
|
||||||
|
|
||||||
|
Properties properties = factoryBean.getObject();
|
||||||
|
return new PropertiesPropertySource(Objects.requireNonNull(resource.getFilename()), Objects.requireNonNull(properties));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.ticketing.server.global.jwt;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import javax.servlet.FilterChain;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
public class JwtFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private final JwtProvider tokenProvider;
|
||||||
|
private final String accessHeader;
|
||||||
|
private final String tokenPrefix;
|
||||||
|
|
||||||
|
public JwtFilter(JwtProperties jwtProperties, JwtProvider tokenProvider) {
|
||||||
|
this.accessHeader = jwtProperties.getAccessHeader();
|
||||||
|
this.tokenPrefix = jwtProperties.getPrefix();
|
||||||
|
this.tokenProvider = tokenProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||||
|
String jwt = resolveToken(request);
|
||||||
|
|
||||||
|
// 토큰이 정상이면 Authentication 을 가져와서 SecurityContext 에 저장
|
||||||
|
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
|
||||||
|
Authentication authentication = tokenProvider.getAuthentication(jwt);
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||||
|
}
|
||||||
|
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveToken(HttpServletRequest request) {
|
||||||
|
String bearerToken = request.getHeader(accessHeader);
|
||||||
|
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(tokenPrefix)) {
|
||||||
|
return bearerToken.substring(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.ticketing.server.global.jwt;
|
||||||
|
|
||||||
|
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.boot.context.properties.ConstructorBinding;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@ConstructorBinding
|
||||||
|
@ConfigurationProperties("jwt")
|
||||||
|
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
|
||||||
|
public class JwtProperties {
|
||||||
|
|
||||||
|
private final String accessHeader;
|
||||||
|
private final String prefix;
|
||||||
|
private final String secretKey;
|
||||||
|
private final Integer tokenValidityInSeconds;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package com.ticketing.server.global.jwt;
|
||||||
|
|
||||||
|
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;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.User;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@Slf4j
|
||||||
|
public class JwtProvider {
|
||||||
|
|
||||||
|
private static final String AUTHORITIES_KEY = "auth";
|
||||||
|
private static final String AUTHORITIES_DELIMITER = ",";
|
||||||
|
|
||||||
|
private final long tokenValidityInMilliseconds;
|
||||||
|
private final Key key;
|
||||||
|
|
||||||
|
public JwtProvider(JwtProperties jwtProperties) {
|
||||||
|
this.tokenValidityInMilliseconds = jwtProperties.getTokenValidityInSeconds();
|
||||||
|
|
||||||
|
byte[] keyBytes = Decoders.BASE64.decode(jwtProperties.getSecretKey());
|
||||||
|
this.key = Keys.hmacShaKeyFor(keyBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
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(accessTokenExpiresIn) // 만료일
|
||||||
|
.signWith(key, SignatureAlgorithm.HS512) // 서명 키 값
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String generateStringToAuthorities(Authentication authentication) {
|
||||||
|
StringJoiner authorities = new StringJoiner(AUTHORITIES_DELIMITER);
|
||||||
|
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
|
||||||
|
String roleName = makeRoleName(grantedAuthority.getAuthority());
|
||||||
|
authorities.add(roleName);
|
||||||
|
}
|
||||||
|
return authorities.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String makeRoleName(String role) {
|
||||||
|
return "ROLE_" + role.toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Authentication getAuthentication(String token) {
|
||||||
|
// 토큰 복호화
|
||||||
|
Claims claims = parseClaims(token);
|
||||||
|
|
||||||
|
List<SimpleGrantedAuthority> authorities =
|
||||||
|
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(AUTHORITIES_DELIMITER))
|
||||||
|
.map(SimpleGrantedAuthority::new)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
UserDetails principal = new User(claims.getSubject(), "", authorities);
|
||||||
|
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean validateToken(String token) {
|
||||||
|
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()
|
||||||
|
.setSigningKey(key)
|
||||||
|
.build()
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.ticketing.server.global.jwt;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class JwtSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||||
|
|
||||||
|
private final JwtFilter jwtFilter;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(HttpSecurity builder) {
|
||||||
|
builder.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.ticketing.server.global.jwt.handle;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
|
||||||
|
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.ticketing.server.global.jwt.handle;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
|
||||||
|
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.ticketing.server.global.security;
|
||||||
|
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
|
||||||
|
public class SecurityUtil {
|
||||||
|
|
||||||
|
private SecurityUtil() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getCurrentUserEmail() {
|
||||||
|
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
|
||||||
|
if (authentication == null || authentication.getName() == null) {
|
||||||
|
throw new IllegalStateException("Security Context 에 인증 정보가 없습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return authentication.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package com.ticketing.server.global.security;
|
||||||
|
|
||||||
|
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.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
|
private final JwtFilter jwtFilter;
|
||||||
|
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||||
|
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
|
||||||
|
http
|
||||||
|
.csrf().disable()
|
||||||
|
.exceptionHandling()
|
||||||
|
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
|
||||||
|
.accessDeniedHandler(jwtAccessDeniedHandler)
|
||||||
|
|
||||||
|
.and()
|
||||||
|
.headers()
|
||||||
|
.frameOptions()
|
||||||
|
.sameOrigin()
|
||||||
|
|
||||||
|
// 시큐리티는 기본적으로 세션을 사용하지만, jwt 을 위해 세션을 Stateless 로 설정
|
||||||
|
.and()
|
||||||
|
.sessionManagement()
|
||||||
|
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||||
|
|
||||||
|
.and()
|
||||||
|
.authorizeRequests()
|
||||||
|
.antMatchers(HttpMethod.POST, "/user").permitAll()
|
||||||
|
.antMatchers(HttpMethod.POST, "/user/login").permitAll()
|
||||||
|
.antMatchers("/l7check").permitAll()
|
||||||
|
.antMatchers("/actuator/health").permitAll()
|
||||||
|
.anyRequest().authenticated()
|
||||||
|
|
||||||
|
.and()
|
||||||
|
.apply(new JwtSecurityConfig(jwtFilter));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ticketing.server.global.service;
|
||||||
|
|
||||||
|
import com.ticketing.server.user.domain.User;
|
||||||
|
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||||
|
import java.util.Collections;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CustomUserDetailsService implements UserDetailsService {
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
||||||
|
return userRepository.findByEmailAndIsDeletedFalse(email)
|
||||||
|
.map(this::createUserDetails)
|
||||||
|
.orElseThrow(() -> new UsernameNotFoundException("존재하지 않는 email 입니다. :: " + email));
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserDetails createUserDetails(User user) {
|
||||||
|
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(user.getGrade().name());
|
||||||
|
|
||||||
|
return new org.springframework.security.core.userdetails.User(
|
||||||
|
user.getEmail()
|
||||||
|
, user.getPassword()
|
||||||
|
, Collections.singleton(grantedAuthority)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,24 @@
|
|||||||
package com.ticketing.server.movie.domain;
|
package com.ticketing.server.movie.domain;
|
||||||
|
|
||||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||||
|
import javax.persistence.Column;
|
||||||
import javax.persistence.Entity;
|
import javax.persistence.Entity;
|
||||||
import javax.validation.constraints.NotNull;
|
import javax.validation.constraints.NotNull;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Getter
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class Movie extends AbstractEntity {
|
public class Movie extends AbstractEntity {
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private String title;
|
@Column(unique = true)
|
||||||
|
private String title;
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private Integer runningTime;
|
private Integer runningTime;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ package com.ticketing.server.movie.domain;
|
|||||||
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
import com.ticketing.server.global.dto.repository.AbstractEntity;
|
||||||
import javax.persistence.Entity;
|
import javax.persistence.Entity;
|
||||||
import javax.validation.constraints.NotNull;
|
import javax.validation.constraints.NotNull;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Getter
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class Theater extends AbstractEntity {
|
public class Theater extends AbstractEntity {
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ import lombok.Getter;
|
|||||||
@Getter
|
@Getter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public enum TicketStatus {
|
public enum TicketStatus {
|
||||||
SALE("판매가능"),
|
SALE("판매가능"),
|
||||||
SCHEDULED("환불"),
|
SCHEDULED("환불"),
|
||||||
SOLD("판매완료");
|
SOLD("판매완료");
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
package com.ticketing.server.movie.domain.repository;
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
import com.ticketing.server.movie.domain.Movie;
|
import com.ticketing.server.movie.domain.Movie;
|
||||||
|
import java.util.Optional;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface MovieRepository extends JpaRepository<Movie, Long> {
|
public interface MovieRepository extends JpaRepository<Movie, Long> {
|
||||||
|
|
||||||
|
Optional<Movie> findByTitle(String title);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
package com.ticketing.server.movie.domain.repository;
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
import com.ticketing.server.movie.domain.Theater;
|
import com.ticketing.server.movie.domain.Theater;
|
||||||
|
import java.util.Optional;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface TheaterRepository extends JpaRepository<Theater, Long> {
|
public interface TheaterRepository extends JpaRepository<Theater, Long> {
|
||||||
|
|
||||||
|
Optional<Theater> findByTheaterNumber(Integer theaterNumber);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.ticketing.server.movie.service;
|
||||||
|
|
||||||
|
import com.ticketing.server.movie.service.interfaces.TMDBService;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class TMBDServiceImpl implements TMDBService {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.ticketing.server.movie.service.interfaces;
|
||||||
|
|
||||||
|
public interface TMDBService {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,18 +1,23 @@
|
|||||||
package com.ticketing.server.user.application;
|
package com.ticketing.server.user.application;
|
||||||
|
|
||||||
|
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.SignUpRequest;
|
||||||
import com.ticketing.server.user.application.request.UserDeleteRequest;
|
import com.ticketing.server.user.application.request.UserDeleteRequest;
|
||||||
import com.ticketing.server.user.application.request.UserModifyPasswordRequest;
|
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.SignUpResponse;
|
||||||
import com.ticketing.server.user.application.response.UserDeleteResponse;
|
|
||||||
import com.ticketing.server.user.application.response.UserChangePasswordResponse;
|
import com.ticketing.server.user.application.response.UserChangePasswordResponse;
|
||||||
|
import com.ticketing.server.user.application.response.UserDeleteResponse;
|
||||||
import com.ticketing.server.user.domain.User;
|
import com.ticketing.server.user.domain.User;
|
||||||
import com.ticketing.server.user.service.UserServiceImpl;
|
import com.ticketing.server.user.service.UserServiceImpl;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.annotation.Secured;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.PatchMapping;
|
import org.springframework.web.bind.annotation.PatchMapping;
|
||||||
@@ -23,27 +28,31 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@RequestMapping("/user")
|
@RequestMapping("/api/user")
|
||||||
@Slf4j
|
@Slf4j
|
||||||
|
|
||||||
public class UserController {
|
public class UserController {
|
||||||
|
|
||||||
private final UserServiceImpl userService;
|
private final UserServiceImpl userService;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final JwtProperties jwtProperties;
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ResponseEntity<Object> register(@RequestBody @Valid SignUpRequest request) {
|
public ResponseEntity<SignUpResponse> register(@RequestBody @Valid SignUpRequest request) {
|
||||||
User user = userService.register(request.toSignUpDto(passwordEncoder));
|
User user = userService.register(request.toSignUpDto(passwordEncoder));
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(SignUpResponse.of(user));
|
return ResponseEntity.status(HttpStatus.CREATED).body(SignUpResponse.of(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping
|
@DeleteMapping
|
||||||
public ResponseEntity<Object> deleteUser(@RequestBody @Valid UserDeleteRequest request) {
|
@Secured("ROLE_GUEST")
|
||||||
|
public ResponseEntity<UserDeleteResponse> deleteUser(@RequestBody @Valid UserDeleteRequest request) {
|
||||||
User user = userService.delete(request.toDeleteUserDto(passwordEncoder));
|
User user = userService.delete(request.toDeleteUserDto(passwordEncoder));
|
||||||
return ResponseEntity.status(HttpStatus.OK).body(UserDeleteResponse.of(user));
|
return ResponseEntity.status(HttpStatus.OK).body(UserDeleteResponse.of(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PatchMapping("/password")
|
@PatchMapping("/password")
|
||||||
public ResponseEntity<Object> changePassword(@RequestBody @Valid UserModifyPasswordRequest request) {
|
@Secured("ROLE_GUEST")
|
||||||
|
public ResponseEntity<UserChangePasswordResponse> changePassword(@RequestBody @Valid UserModifyPasswordRequest request) {
|
||||||
if (request.oldEqualNew()) {
|
if (request.oldEqualNew()) {
|
||||||
log.error("기존 패스워드와 동일한 패스워드로 변경할 수 없습니다.");
|
log.error("기존 패스워드와 동일한 패스워드로 변경할 수 없습니다.");
|
||||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
|
||||||
@@ -53,4 +62,12 @@ public class UserController {
|
|||||||
return ResponseEntity.status(HttpStatus.OK).body(UserChangePasswordResponse.of(user));
|
return ResponseEntity.status(HttpStatus.OK).body(UserChangePasswordResponse.of(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
|
||||||
|
String accessToken = userService.login(loginRequest.toAuthentication());
|
||||||
|
|
||||||
|
response.setHeader(jwtProperties.getAccessHeader(), accessToken);
|
||||||
|
return ResponseEntity.status(HttpStatus.OK).body(LoginResponse.of(accessToken));
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.ticketing.server.user.application.request;
|
||||||
|
|
||||||
|
import javax.validation.constraints.Email;
|
||||||
|
import javax.validation.constraints.NotEmpty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class LoginRequest {
|
||||||
|
|
||||||
|
@NotEmpty(message = "{validation.not.empty.email}")
|
||||||
|
@Email(message = "{validation.email}")
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
@NotEmpty(message = "{validation.not.empty.password}")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
public UsernamePasswordAuthenticationToken toAuthentication() {
|
||||||
|
return new UsernamePasswordAuthenticationToken(email, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -4,10 +4,14 @@ import com.ticketing.server.global.validator.constraints.Phone;
|
|||||||
import com.ticketing.server.user.service.dto.SignUpDTO;
|
import com.ticketing.server.user.service.dto.SignUpDTO;
|
||||||
import javax.validation.constraints.Email;
|
import javax.validation.constraints.Email;
|
||||||
import javax.validation.constraints.NotEmpty;
|
import javax.validation.constraints.NotEmpty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class SignUpRequest {
|
public class SignUpRequest {
|
||||||
|
|
||||||
@NotEmpty(message = "{validation.not.empty.name}")
|
@NotEmpty(message = "{validation.not.empty.name}")
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ package com.ticketing.server.user.application.request;
|
|||||||
import com.ticketing.server.user.service.dto.DeleteUserDTO;
|
import com.ticketing.server.user.service.dto.DeleteUserDTO;
|
||||||
import javax.validation.constraints.Email;
|
import javax.validation.constraints.Email;
|
||||||
import javax.validation.constraints.NotEmpty;
|
import javax.validation.constraints.NotEmpty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class UserDeleteRequest {
|
public class UserDeleteRequest {
|
||||||
|
|
||||||
@NotEmpty(message = "{validation.not.empty.email}")
|
@NotEmpty(message = "{validation.not.empty.email}")
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ package com.ticketing.server.user.application.request;
|
|||||||
import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
||||||
import javax.validation.constraints.Email;
|
import javax.validation.constraints.Email;
|
||||||
import javax.validation.constraints.NotEmpty;
|
import javax.validation.constraints.NotEmpty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
public class UserModifyPasswordRequest {
|
public class UserModifyPasswordRequest {
|
||||||
|
|
||||||
@NotEmpty(message = "{validation.not.empty.email}")
|
@NotEmpty(message = "{validation.not.empty.email}")
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,20 +1,20 @@
|
|||||||
package com.ticketing.server.user.application.response;
|
package com.ticketing.server.user.application.response;
|
||||||
|
|
||||||
import com.ticketing.server.user.domain.User;
|
import com.ticketing.server.user.domain.User;
|
||||||
|
import lombok.AccessLevel;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||||
public class SignUpResponse {
|
public class SignUpResponse {
|
||||||
|
|
||||||
public static SignUpResponse of(User user) {
|
|
||||||
return new SignUpResponse(user.getName(), user.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
public SignUpResponse(String name, String email) {
|
|
||||||
this.name = name;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
private String email;
|
private String email;
|
||||||
|
|
||||||
|
public static SignUpResponse of(User user) {
|
||||||
|
return new SignUpResponse(user.getName(), user.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
package com.ticketing.server.user.application.response;
|
package com.ticketing.server.user.application.response;
|
||||||
|
|
||||||
import com.ticketing.server.user.domain.User;
|
import com.ticketing.server.user.domain.User;
|
||||||
|
import lombok.AccessLevel;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||||
public class UserChangePasswordResponse {
|
public class UserChangePasswordResponse {
|
||||||
|
|
||||||
public static SignUpResponse of(User user) {
|
|
||||||
return new SignUpResponse(user.getName(), user.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserChangePasswordResponse(String name, String email) {
|
|
||||||
this.name = name;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
private String email;
|
private String email;
|
||||||
|
|
||||||
|
public static UserChangePasswordResponse of(User user) {
|
||||||
|
return new UserChangePasswordResponse(user.getName(), user.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
package com.ticketing.server.user.application.response;
|
package com.ticketing.server.user.application.response;
|
||||||
|
|
||||||
import com.ticketing.server.user.domain.User;
|
import com.ticketing.server.user.domain.User;
|
||||||
|
import lombok.AccessLevel;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||||
public class UserDeleteResponse {
|
public class UserDeleteResponse {
|
||||||
|
|
||||||
public static SignUpResponse of(User user) {
|
|
||||||
return new SignUpResponse(user.getName(), user.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserDeleteResponse(String name, String email) {
|
|
||||||
this.name = name;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
private String email;
|
private String email;
|
||||||
|
|
||||||
|
public static UserDeleteResponse of(User user) {
|
||||||
|
return new UserDeleteResponse(user.getName(), user.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ public class User extends AbstractEntity {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkPassword(PasswordMatches passwordMatches) {
|
public void checkPassword(PasswordMatches passwordMatches) {
|
||||||
if (!passwordMatches.passwordMatches(password)) {
|
if (!passwordMatches.passwordMatches(password)) {
|
||||||
throw new PasswordMismatchException();
|
throw new PasswordMismatchException();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.ticketing.server.user.service;
|
package com.ticketing.server.user.service;
|
||||||
|
|
||||||
import com.ticketing.server.global.exception.NotFoundEmailException;
|
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.User;
|
||||||
import com.ticketing.server.user.domain.repository.UserRepository;
|
import com.ticketing.server.user.domain.repository.UserRepository;
|
||||||
import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
||||||
@@ -11,6 +12,9 @@ import java.util.Optional;
|
|||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
@@ -23,6 +27,14 @@ import org.springframework.validation.annotation.Validated;
|
|||||||
public class UserServiceImpl implements UserService {
|
public class UserServiceImpl implements UserService {
|
||||||
|
|
||||||
private final UserRepository userRepository;
|
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
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -39,27 +51,29 @@ public class UserServiceImpl implements UserService {
|
|||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public User delete(@Valid DeleteUserDTO deleteUserDto) {
|
public User delete(@Valid DeleteUserDTO deleteUserDto) {
|
||||||
Optional<User> optionalUser = userRepository.findByEmail(deleteUserDto.getEmail());
|
User user = userRepository.findByEmail(deleteUserDto.getEmail())
|
||||||
if (optionalUser.isEmpty()) {
|
.orElseThrow(() -> {
|
||||||
log.error("존재하지 않는 이메일 입니다. :: {}", deleteUserDto);
|
log.error("존재하지 않는 이메일 입니다. :: {}", deleteUserDto.getEmail());
|
||||||
throw new NotFoundEmailException();
|
throw new NotFoundEmailException();
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
|
||||||
User user = optionalUser.get();
|
|
||||||
return user.delete(deleteUserDto);
|
return user.delete(deleteUserDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public User changePassword(@Valid ChangePasswordDTO changePasswordDto) {
|
public User changePassword(@Valid ChangePasswordDTO changePasswordDto) {
|
||||||
Optional<User> optionalUser = userRepository.findByEmailAndIsDeletedFalse(changePasswordDto.getEmail());
|
User user = findNotDeletedUserByEmail(changePasswordDto.getEmail());
|
||||||
if (optionalUser.isEmpty()) {
|
|
||||||
log.error("존재하지 않는 이메일 입니다. :: {}", changePasswordDto);
|
|
||||||
throw new NotFoundEmailException();
|
|
||||||
}
|
|
||||||
|
|
||||||
User user = optionalUser.get();
|
|
||||||
return user.changePassword(changePasswordDto);
|
return user.changePassword(changePasswordDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private User findNotDeletedUserByEmail(String email) {
|
||||||
|
return userRepository.findByEmailAndIsDeletedFalse(email)
|
||||||
|
.orElseThrow(() -> {
|
||||||
|
log.error("존재하지 않는 이메일 입니다. :: {}", email);
|
||||||
|
throw new NotFoundEmailException();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,9 +5,13 @@ import com.ticketing.server.user.service.dto.ChangePasswordDTO;
|
|||||||
import com.ticketing.server.user.service.dto.DeleteUserDTO;
|
import com.ticketing.server.user.service.dto.DeleteUserDTO;
|
||||||
import com.ticketing.server.user.service.dto.SignUpDTO;
|
import com.ticketing.server.user.service.dto.SignUpDTO;
|
||||||
import javax.validation.Valid;
|
import javax.validation.Valid;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
|
||||||
public interface UserService {
|
public interface UserService {
|
||||||
|
|
||||||
|
String login(UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken);
|
||||||
|
|
||||||
User register(@Valid SignUpDTO signUpDto);
|
User register(@Valid SignUpDTO signUpDto);
|
||||||
|
|
||||||
User delete(@Valid DeleteUserDTO deleteUserDto);
|
User delete(@Valid DeleteUserDTO deleteUserDto);
|
||||||
|
|||||||
@@ -18,3 +18,9 @@ spring:
|
|||||||
jasypt:
|
jasypt:
|
||||||
encryptor:
|
encryptor:
|
||||||
bean: jasyptStringEncryptor
|
bean: jasyptStringEncryptor
|
||||||
|
|
||||||
|
jwt:
|
||||||
|
access-header: ACCESS_TOKEN
|
||||||
|
prefix: Bearer
|
||||||
|
secret-key: Zi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXktZi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXkK
|
||||||
|
token-validity-in-seconds: 86400
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.ticketing.server.global.jwt;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||||
|
|
||||||
|
import com.ticketing.server.global.factory.YamlPropertySourceFactory;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.PropertySource;
|
||||||
|
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||||
|
|
||||||
|
@ExtendWith(SpringExtension.class)
|
||||||
|
@EnableConfigurationProperties(value = JwtProperties.class)
|
||||||
|
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
|
||||||
|
class JwtPropertiesTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JwtProperties jwtProperties;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("yml - jwt 설정파일 체크")
|
||||||
|
void jwtPropertiesCheck() {
|
||||||
|
// given
|
||||||
|
// when
|
||||||
|
// then
|
||||||
|
assertAll(
|
||||||
|
() -> assertThat(jwtProperties.getAccessHeader()).isEqualTo("ACCESS_TOKEN")
|
||||||
|
, () -> assertThat(jwtProperties.getPrefix()).isEqualTo("Bearer")
|
||||||
|
, () -> assertThat(jwtProperties.getTokenValidityInSeconds()).isEqualTo(86400)
|
||||||
|
, () -> assertThat(jwtProperties.getSecretKey()).isNotEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
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.domain.UserGrade;
|
||||||
|
import java.util.Collections;
|
||||||
|
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.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.Authentication;
|
||||||
|
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 TokenProviderTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JwtProperties jwtProperties;
|
||||||
|
|
||||||
|
JwtProvider tokenProvider;
|
||||||
|
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void init() {
|
||||||
|
tokenProvider = new JwtProvider(jwtProperties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("토큰 생성 성공")
|
||||||
|
void createTokenSuccess() {
|
||||||
|
// given
|
||||||
|
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(UserGrade.GUEST.name());
|
||||||
|
UsernamePasswordAuthenticationToken authenticationToken =
|
||||||
|
new UsernamePasswordAuthenticationToken("ticketing@gmail.com", "123456", Collections.singleton(grantedAuthority));
|
||||||
|
|
||||||
|
// when
|
||||||
|
String token = tokenProvider.createToken(authenticationToken);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(token).isNotEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("토큰 복호화 성공")
|
||||||
|
void getAuthentication() {
|
||||||
|
// given
|
||||||
|
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(UserGrade.GUEST.name());
|
||||||
|
UsernamePasswordAuthenticationToken authenticationToken =
|
||||||
|
new UsernamePasswordAuthenticationToken("ticketing@gmail.com", "123456", Collections.singleton(grantedAuthority));
|
||||||
|
|
||||||
|
// when
|
||||||
|
String token = tokenProvider.createToken(authenticationToken);
|
||||||
|
Authentication authentication = tokenProvider.getAuthentication(token);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(authentication.getName()).isEqualTo("ticketing@gmail.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package com.ticketing.server.global.security;
|
||||||
|
|
||||||
|
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.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.context.SecurityContext;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class SecurityContextHolderTest {
|
||||||
|
|
||||||
|
private static final String ANY_USER = "ticketing";
|
||||||
|
private static final String ANY_PASSWORD = "password";
|
||||||
|
private static final String ROLE_GUEST = "ROLE_GUEST";
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void init() {
|
||||||
|
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
|
||||||
|
setMockAuthentication();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void clear() {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("SecurityContextHolder 에 현재 인증된 사용자 정보를 확인한다.")
|
||||||
|
void SecurityContextHolder() {
|
||||||
|
// given
|
||||||
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
|
||||||
|
// when
|
||||||
|
// then
|
||||||
|
assertAll(
|
||||||
|
() -> assertThat(authentication.isAuthenticated()).isTrue()
|
||||||
|
, () -> assertThat(authentication.getName()).isEqualTo(ANY_USER)
|
||||||
|
, () -> assertThat(authentication.getCredentials()).isEqualTo(ANY_PASSWORD)
|
||||||
|
, () -> assertThat(authentication.getAuthorities())
|
||||||
|
.extracting(GrantedAuthority::getAuthority)
|
||||||
|
.contains(ROLE_GUEST)
|
||||||
|
);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void setMockAuthentication() {
|
||||||
|
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||||
|
|
||||||
|
TestingAuthenticationToken mockAuthentication
|
||||||
|
= new TestingAuthenticationToken(SecurityContextHolderTest.ANY_USER, SecurityContextHolderTest.ANY_PASSWORD, SecurityContextHolderTest.ROLE_GUEST);
|
||||||
|
context.setAuthentication(mockAuthentication);
|
||||||
|
|
||||||
|
SecurityContextHolder.setContext(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.ticketing.server.movie.domain;
|
||||||
|
|
||||||
|
public class MovieTest {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.ticketing.server.movie.domain.Movie;
|
||||||
|
import java.util.Optional;
|
||||||
|
import javax.transaction.Transactional;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.MethodOrderer;
|
||||||
|
import org.junit.jupiter.api.Order;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.TestMethodOrder;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.annotation.Rollback;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
|
public class MovieRepositoryTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
MovieRepository movieRepository;
|
||||||
|
|
||||||
|
@Order(1)
|
||||||
|
@Test
|
||||||
|
@Rollback(value = false)
|
||||||
|
@DisplayName("Movie Repository - test saving movie")
|
||||||
|
void shouldAbleToSaveMovie() {
|
||||||
|
// given
|
||||||
|
Movie movie = new Movie("범죄도시 2", 106);
|
||||||
|
|
||||||
|
// when
|
||||||
|
Movie savedMovie = movieRepository.save(movie);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(movie.getTitle(), savedMovie.getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Order(2)
|
||||||
|
@Test
|
||||||
|
@DisplayName("Movie Repository Test - finding movie with title")
|
||||||
|
void ShouldAbleToFindMovieWithTitle() {
|
||||||
|
// given, when
|
||||||
|
Optional<Movie> optionalMovie = movieRepository.findByTitle("범죄도시 2");
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertTrue(optionalMovie.isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Order(3)
|
||||||
|
@Test
|
||||||
|
@DisplayName("Movie Repository Test - finding movie that doesn't exist")
|
||||||
|
void ShouldNotAbleToFindMovie() {
|
||||||
|
// given, when
|
||||||
|
Optional<Movie> optionalMovie = movieRepository.findByTitle("존재하지 않는 영화");
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertFalse(optionalMovie.isPresent());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
|
public class MovieTimesRepositoryTest {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
|
public class SeatRepositoryTest {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import com.ticketing.server.movie.domain.Theater;
|
||||||
|
import javax.transaction.Transactional;
|
||||||
|
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
|
||||||
|
@Transactional
|
||||||
|
public class TheaterRepositoryTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
TheaterRepository theaterRepository;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Theater Repository Test - saving theater")
|
||||||
|
void ShouldAbleToSaveTheater() {
|
||||||
|
// given
|
||||||
|
Theater theater = new Theater(1, 100);
|
||||||
|
|
||||||
|
// when
|
||||||
|
Theater savedTheater = theaterRepository.save(theater);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(theater.getTheaterNumber(), savedTheater.getTheaterNumber());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.ticketing.server.movie.domain.repository;
|
||||||
|
|
||||||
|
public class TicketRepositoryTest {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.ticketing.server.movie.service;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class MovieServiceImplTest {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package com.ticketing.server.movie.service;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
public class TMDBServiceImplTest {
|
||||||
|
|
||||||
|
@Value("${tmdb.api-key}")
|
||||||
|
private String apiKey;
|
||||||
|
|
||||||
|
@Value("${tmdb.read-access-token}")
|
||||||
|
private String readAccessToken;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
RestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("TMDB Service Test - Get [Now Playing] movies")
|
||||||
|
void shouldAbleToGetMovieList() throws Exception {
|
||||||
|
// given
|
||||||
|
assertNotNull(apiKey);
|
||||||
|
assertNotNull(readAccessToken);
|
||||||
|
|
||||||
|
ArrayList<Charset> acceptCharset = new ArrayList<>();
|
||||||
|
acceptCharset.add(StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
HttpHeaders headers = new HttpHeaders();
|
||||||
|
headers.setAcceptCharset(acceptCharset);
|
||||||
|
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
headers.setBearerAuth(readAccessToken);
|
||||||
|
|
||||||
|
Map<String, String> params = new HashMap<>();
|
||||||
|
params.put("api_key", apiKey);
|
||||||
|
params.put("language", "ko");
|
||||||
|
|
||||||
|
HttpEntity<?> request = new HttpEntity<>(headers);
|
||||||
|
|
||||||
|
// when
|
||||||
|
ResponseEntity<?> response = restTemplate.exchange(
|
||||||
|
"https://api.themoviedb.org/3/movie/now_playing?" + mapToUrlParam(params),
|
||||||
|
HttpMethod.GET,
|
||||||
|
request,
|
||||||
|
String.class
|
||||||
|
);
|
||||||
|
|
||||||
|
// JSONParser parser = new JSONParser();
|
||||||
|
// Object obj = parser.parse(String.valueOf(response));
|
||||||
|
// Object results = ((JSONObject) obj).get("results");
|
||||||
|
//
|
||||||
|
// ArrayList<String> movieList = new ArrayList<>();
|
||||||
|
//
|
||||||
|
// ArrayList<JSONObject> jsonMovieList = new ArrayList<>();
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertTrue(response.getStatusCode().is2xxSuccessful());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String mapToUrlParam(Map<String, String> params) {
|
||||||
|
StringBuffer paramData = new StringBuffer();
|
||||||
|
|
||||||
|
for (Map.Entry<String, String> param : params.entrySet()) {
|
||||||
|
if (paramData.length() != 0) {
|
||||||
|
paramData.append('&');
|
||||||
|
}
|
||||||
|
|
||||||
|
paramData.append(param.getKey());
|
||||||
|
paramData.append('=');
|
||||||
|
paramData.append(param.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return paramData.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
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.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.BeforeEach;
|
||||||
|
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;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.ResultActions;
|
||||||
|
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@Transactional
|
||||||
|
class UserControllerTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
WebApplicationContext context;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
UserService userService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
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 {
|
||||||
|
// given
|
||||||
|
LoginRequest request = new LoginRequest("ticketing@gmail.com", "qwe123");
|
||||||
|
|
||||||
|
// when
|
||||||
|
ResultActions actions = mvc.perform(post("/user/login")
|
||||||
|
.content(asJsonString(request))
|
||||||
|
.contentType(MediaType.APPLICATION_JSON));
|
||||||
|
|
||||||
|
// then
|
||||||
|
actions.andDo(print())
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(header().exists("ACCESS_TOKEN"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("로그인 패스워드 인증 실패")
|
||||||
|
void loginPasswordFail() throws Exception {
|
||||||
|
// given
|
||||||
|
LoginRequest request = new LoginRequest("ticketing@gmail.com", "qwe1234");
|
||||||
|
|
||||||
|
// when
|
||||||
|
ResultActions actions = mvc.perform(post("/user/login")
|
||||||
|
.content(asJsonString(request))
|
||||||
|
.contentType(MediaType.APPLICATION_JSON));
|
||||||
|
|
||||||
|
// then
|
||||||
|
actions.andDo(print())
|
||||||
|
.andExpect(status().isUnauthorized());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String asJsonString(Object object) throws JsonProcessingException {
|
||||||
|
return objectMapper.writeValueAsString(object);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -21,4 +21,4 @@ class SignUpDtoTest {
|
|||||||
assertThat(user).isInstanceOf(User.class);
|
assertThat(user).isInstanceOf(User.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,3 +16,14 @@ spring:
|
|||||||
jasypt:
|
jasypt:
|
||||||
encryptor:
|
encryptor:
|
||||||
bean: jasyptStringEncryptor
|
bean: jasyptStringEncryptor
|
||||||
|
|
||||||
|
jwt:
|
||||||
|
access-header: ACCESS_TOKEN
|
||||||
|
prefix: Bearer
|
||||||
|
secret-key: Zi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXktZi1sYWItdGlja2V0aW5nLXByb2plY3Qtc3ByaW5nLWJvb3Qtc2VjdXJpdHktand0LXNlY3JldC1rZXkK
|
||||||
|
token-validity-in-seconds: 86400
|
||||||
|
|
||||||
|
tmdb:
|
||||||
|
api-key: 0d1503b6dcbfe1c514299b5564c649b8
|
||||||
|
read-access-token: eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwZDE1MDNiNmRjYmZlMWM1MTQyOTliNTU2NGM2NDliOCIsInN1YiI6IjYyOWYwODRlNzI2ZmIxMTA2NDA4MjI2NCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.rs8KZea8QLyashILiggWFx2s46lgUtzo-xSWoDgE58A
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user