Skip to content

Commit

Permalink
Merge pull request #83 from Team-Solar-Powers/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
yubin-im authored Nov 23, 2023
2 parents 2d7643d + eb04267 commit 9f9cbc3
Show file tree
Hide file tree
Showing 148 changed files with 8,694 additions and 349 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ out/

### VS Code ###
.vscode/

## yml 파일 (aws cloud)
*.yml
6 changes: 6 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
FROM openjdk:11-jdk
LABEL maintainer="yubin"
ARG JAR_FILE=build/libs/*.jar
ADD ${JAR_FILE} app.jar
EXPOSE 8099
ENTRYPOINT ["java","-jar","/app.jar"]
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: java -jar application.jar
51 changes: 47 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ java {
sourceCompatibility = '11'
}

bootJar {
archiveFileName = 'app.jar'
}

jar {
enabled = false
}

configurations {
compileOnly {
extendsFrom annotationProcessor
Expand All @@ -30,20 +38,55 @@ dependencies {
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

testImplementation 'org.springframework.boot:spring-boot-starter-test'

//security
testImplementation 'org.springframework.security:spring-security-test'

// H2
runtimeOnly 'com.h2database:h2'
//s3 access
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'


// // H2
// runtimeOnly 'com.h2database:h2'

//타임리프 레이아웃
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'

// mySQl 설정
implementation 'mysql:mysql-connector-java:8.0.28'

//smtp 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-mail'

//redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

//jwt
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.2'

//gson
implementation 'com.google.code.gson:gson:2.8.9'

//OAuth2
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

//mysql
//implementation 'mysql:mysql-connector-java:8.0.29'

//타입리프 레이아웃
//implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'


}

tasks.named('test') {
useJUnitPlatform()
}

// jar 파일 만들 때 MANIFEST.MF 파일 중복되어서 코드 추가
bootJar {
duplicatesStrategy = 'exclude'
}
16 changes: 13 additions & 3 deletions src/main/java/com/checkcheck/ecoreading/EcoReadingApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,22 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
@SpringBootApplication(
exclude = {
org.springframework.cloud.aws.autoconfigure.context.ContextInstanceDataAutoConfiguration.class,
org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration.class,
org.springframework.cloud.aws.autoconfigure.context.ContextRegionProviderAutoConfiguration.class
// DataSourceAutoConfiguration.class
}
)
public class EcoReadingApplication {

public static void main(String[] args) {
SpringApplication.run(EcoReadingApplication.class, args);
}

}
67 changes: 67 additions & 0 deletions src/main/java/com/checkcheck/ecoreading/config/EmailConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.checkcheck.ecoreading.config;

import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
public class EmailConfig {

@Value("${spring.mail.host}")
private String host;

@Value("${spring.mail.port}")
private int port;

@Value("${spring.mail.username}")
private String username;

@Value("${spring.mail.password}")
private String password;

@Value("${spring.mail.properties.mail.smtp.auth}")
private boolean auth;

@Value("${spring.mail.properties.mail.smtp.starttls.enable}")
private boolean starttlsEnable;

@Value("${spring.mail.properties.mail.smtp.starttls.required}")
private boolean starttlsRequired;

@Value("${spring.mail.properties.mail.smtp.connectiontimeout}")
private int connectionTimeout;

@Value("${spring.mail.properties.mail.smtp.timeout}")
private int timeout;

@Value("${spring.mail.properties.mail.smtp.writetimeout}")
private int writeTimeout;

@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
mailSender.setDefaultEncoding("UTF-8");
mailSender.setJavaMailProperties(getMailProperties());

return mailSender;
}

private Properties getMailProperties() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", auth);
properties.put("mail.smtp.starttls.enable", starttlsEnable);
properties.put("mail.smtp.starttls.required", starttlsRequired);
properties.put("mail.smtp.connectiontimeout", connectionTimeout);
properties.put("mail.smtp.timeout", timeout);
properties.put("mail.smtp.writetimeout", writeTimeout);

return properties;
}
}
32 changes: 32 additions & 0 deletions src/main/java/com/checkcheck/ecoreading/config/RedisConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.checkcheck.ecoreading.config;

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.serializer.StringRedisSerializer;

@Configuration
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;
}
}
33 changes: 33 additions & 0 deletions src/main/java/com/checkcheck/ecoreading/config/S3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.checkcheck.ecoreading.config;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class S3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;

@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;

@Value("${cloud.aws.region.static}")
private String region;

@Bean
public AmazonS3 amazonS3() {
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

return AmazonS3ClientBuilder.standard()
.withRegion(Regions.fromName(region))
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
}
67 changes: 52 additions & 15 deletions src/main/java/com/checkcheck/ecoreading/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,90 @@

import static org.springframework.boot.autoconfigure.security.servlet.PathRequest.toH2Console;

import com.checkcheck.ecoreading.domain.loginHistory.service.LoginHistoryService;
import com.checkcheck.ecoreading.domain.users.exception.AuthenticationEmailException;
import com.checkcheck.ecoreading.domain.users.exception.CustomAuthenticationFailureHandler;
import com.checkcheck.ecoreading.domain.users.repository.UserRepository;
import com.checkcheck.ecoreading.domain.users.service.RedisService;
import com.checkcheck.ecoreading.domain.users.service.UserCustomDetailService;
import com.checkcheck.ecoreading.domain.users.service.UserOAuthCustomService;
import com.checkcheck.ecoreading.domain.users.service.UserService;
import com.checkcheck.ecoreading.security.jwt.JwtAuthenticationFilter;
import com.checkcheck.ecoreading.security.jwt.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Controller;

@RequiredArgsConstructor
@Configuration
public class SecurityConfig {

private final UserCustomDetailService userDetailsService; // UserDetailsService 주입

private final UserOAuthCustomService userOAuthCustomService;
private final JwtTokenProvider jwtTokenProvider;
private final RedisService redisTemplate;

private final UserRepository repository;
private final LoginHistoryService loginHistoryService;


@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring().antMatchers(
"/h2-console/**",
"/api-document/**",
"/swagger-ui/**",
"/static/**"
"/static/**",
"/css/**",
"/js/**",
"/images/**"
);
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter(jwtTokenProvider, redisTemplate, repository, loginHistoryService);
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeRequests(auth -> auth
.anyRequest().permitAll() // 모든 요청에 대해 접근을 허용
// .antMatchers("/login", "/signup", "/user").permitAll() // 로그인, 회원가입, 유저 페이지는 인증 없이 접근 허용
// .antMatchers("/h2-console/**").permitAll() // H2 콘솔 경로도 인증 없이 접근 허용
// .antMatchers("/test").hasAuthority("ROLE_USER") // '/test' 경로는 'ROLE_USER' 권한을 가진 사용자만 접근 가능
// .anyRequest().authenticated() // 나머지 요청은 모두 인증 필요
)
.formLogin(login -> login
.loginPage("/login") // 로그인 페이지 설정
.defaultSuccessUrl("/test") // 로그인 성공 시 이동할 기본 URL 설정
//.antMatchers("/**").permitAll() // 모든 요청에 대해 접근을 허용
.antMatchers("/user/mypage/**").authenticated()
.antMatchers("/user/**").permitAll()
.antMatchers("/main/").permitAll()
.antMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
.anyRequest().authenticated() // 나머지 요청은 모두 인증 필요
)
.logout(logout -> logout
.logoutSuccessUrl("/login") // 로그아웃 성공 시 이동할 URL 설정
.invalidateHttpSession(true) // 로그아웃 시 세션 무효화
.formLogin().disable()
// 403 에러 처리
.exceptionHandling(exception -> exception
.accessDeniedPage("/user/403error")
)
.csrf(csrf -> csrf.disable()) // H2 콘솔 사용 시 CSRF 비활성화 필요
.headers(headers -> headers.frameOptions().disable()) // H2 콘솔은 iframe을 사용하기 때문에 이를 허용해야 함
.oauth2Login(oauth2 -> oauth2
.loginPage("/user/login")
.defaultSuccessUrl("/user/social/login", true)
//커스텀 핸들러 설정
.failureHandler(new CustomAuthenticationFailureHandler())
)
.headers(headers -> headers.frameOptions().disable())
//.userDetailsService(userDetailsService) // UserDetailsService 설정
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}

}
16 changes: 16 additions & 0 deletions src/main/java/com/checkcheck/ecoreading/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.checkcheck.ecoreading.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
public static final String ALLOWED_METHOD_NAMES = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH";

@Override
public void addCorsMappings(final CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods(ALLOWED_METHOD_NAMES.split(","));
}
}
Loading

0 comments on commit 9f9cbc3

Please sign in to comment.