Skip to content

Commit

Permalink
feature/Redis 기능 구현 완료#9
Browse files Browse the repository at this point in the history
feature/Redis 기능 구현 완료
  • Loading branch information
dltjdgh0428 authored Apr 8, 2024
2 parents 78280df + 3bc22a3 commit 632b209
Show file tree
Hide file tree
Showing 84 changed files with 745 additions and 400 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/CICD.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ jobs:
if [ "$STATUS" = "200" ]; then
CURRENT_UPSTREAM=$(curl -s "https://${{ secrets.BOOKEVERYWHERE_URL }}/env" | jq -r '.data')
else
CURRENT_UPSTREAM=blue
CURRENT_UPSTREAM=green
fi
echo CURRENT_UPSTREAM=$CURRENT_UPSTREAM >> $GITHUB_ENV
if [ $CURRENT_UPSTREAM = blue ]; then
Expand Down
5 changes: 1 addition & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ build/
!**/src/test/**/build/

src/main/resources/*.yml
!application.yml
src/test/resources/*.yml
!application.yml


src/main/resources/templates/*.html

### STS ###
.apt_generated
Expand Down
10 changes: 8 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,21 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'

//JWT
implementation 'io.jsonwebtoken:jjwt-api:0.12.3'
implementation 'io.jsonwebtoken:jjwt-impl:0.12.3'
implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3'

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
//log를 위한 추가


//Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
//test를 위한 추가
runtimeOnly 'com.h2database:h2'

}
tasks.withType(JavaCompile) {
tasks.withType(JavaCompile).configureEach {
options.compilerArgs += ['-parameters']
sourceCompatibility = '17'
targetCompatibility = '17'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class BookEverywhereApplication {
public static void main(String[] args) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
package com.book_everywhere.auth.config;
package com.book_everywhere.common.auth.config;

import com.book_everywhere.auth.service.CustomOAuth2UserService;
import com.book_everywhere.common.auth.service.CustomOAuth2UserService;
import com.book_everywhere.common.jwt.filter.JwtFilter;
import com.book_everywhere.common.jwt.token.JwtProvider;
import com.book_everywhere.common.jwt.filter.CustomSuccessHandler;
import lombok.RequiredArgsConstructor;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

private final CustomOAuth2UserService customOAuth2UserService;
private final CustomSuccessHandler customSuccessHandler;
private final JwtProvider jwtProvider;

public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) {
this.customOAuth2UserService = customOAuth2UserService;
}

@Bean
public BCryptPasswordEncoder encoder() {
Expand All @@ -37,8 +40,7 @@ public BCryptPasswordEncoder encoder() {
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 또는 패턴을 사용하여 출처 지정
config.setAllowedOriginPatterns(Arrays.asList("https://*.bookeverywhere.site","http://localhost:3000"));
config.setAllowedOriginPatterns(Arrays.asList("https://*.bookeverywhere.site", "http://localhost:3000"));
config.setAllowCredentials(true); // 크리덴셜 허용
config.addAllowedHeader("*");
config.addAllowedMethod("*");
Expand All @@ -47,36 +49,36 @@ public CorsConfigurationSource corsConfigurationSource() {
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
// .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class)
.addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class)
.authorizeHttpRequests((authorizeRequests) -> authorizeRequests
.requestMatchers(new MvcRequestMatcher(introspector, "/")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/health")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/env")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/test/**")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/swagger-ui/**")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/api/review")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/api/map")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/api/tags")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/api/data/**")).permitAll()
.requestMatchers(new MvcRequestMatcher(introspector, "/api/**")).hasRole("MEMBER")
.requestMatchers("/").permitAll()
// 테스트 관련 url
// .requestMatchers("/api/**").permitAll()
.requestMatchers("/health", "/env", "/test/**", "/swagger-ui/**").permitAll()
.requestMatchers("/api/reviews").permitAll()
// 비회원도 볼수있는 url
.requestMatchers("/api/review", "/api/map", "/api/tags", "/api/data/**").permitAll()
// 나머지
// .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER")
.anyRequest().authenticated()
)
.oauth2Login(oauth2Login ->
oauth2Login
.userInfoEndpoint(userInfoEndpointConfig ->
userInfoEndpointConfig.userService(customOAuth2UserService))
.successHandler((request, response, authentication) -> {
response.sendRedirect("https://www.bookeverywhere.site");
}))
.successHandler(customSuccessHandler)
)
;
return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.book_everywhere.auth.dto;
package com.book_everywhere.common.auth.dto;

import com.book_everywhere.auth.entity.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;

Expand All @@ -10,18 +9,15 @@

public class CustomOAuth2User implements OAuth2User {

private final OAuthAttributes oAuthAttributes;
private final Role role;
private final UserDto userDto;

public CustomOAuth2User(OAuthAttributes oAuth2Attributes, Role role) {

this.oAuthAttributes = oAuth2Attributes;
this.role = role;
public CustomOAuth2User(UserDto userDto) {
this.userDto = userDto;
}

@Override
public Map<String, Object> getAttributes() {
return oAuthAttributes.getAttributes();
return null;
}

@Override
Expand All @@ -32,7 +28,7 @@ public Collection<? extends GrantedAuthority> getAuthorities() {
collection.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return String.valueOf(role);
return userDto.getRole();
}
});

Expand All @@ -42,8 +38,9 @@ public String getAuthority() {

@Override
public String getName() {
return oAuthAttributes.getNickname();
return userDto.getNickname();
}



}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.book_everywhere.auth.dto;
package com.book_everywhere.common.auth.dto;

import com.book_everywhere.auth.entity.Role;
import com.book_everywhere.auth.entity.User;
import com.book_everywhere.common.auth.entity.Role;
import com.book_everywhere.common.auth.entity.User;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/book_everywhere/common/auth/dto/UserDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.book_everywhere.common.auth.dto;


import lombok.Data;

@Data
public class UserDto {
private String nickname;
private String role;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.book_everywhere.auth.entity;
package com.book_everywhere.common.auth.entity;

public enum Role {
ROLE_ADMIN,ROLE_MEMBER
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package com.book_everywhere.auth.entity;
package com.book_everywhere.common.auth.entity;

import com.book_everywhere.common.entity.BaseTimeEntity;
import com.book_everywhere.review.entity.Review;
import com.book_everywhere.tag.entity.Tagged;
import com.book_everywhere.pin.entity.Visit;
import com.book_everywhere.domain.review.entity.Review;
import com.book_everywhere.domain.tag.entity.Tagged;
import com.book_everywhere.domain.pin.entity.Visit;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.book_everywhere.auth.repository;
package com.book_everywhere.common.auth.repository;

import com.book_everywhere.auth.entity.User;
import com.book_everywhere.common.auth.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,20 @@
package com.book_everywhere.auth.service;

import com.book_everywhere.auth.dto.CustomOAuth2User;
import com.book_everywhere.auth.dto.OAuthAttributes;
import com.book_everywhere.auth.entity.Role;
import com.book_everywhere.auth.entity.User;
import com.book_everywhere.auth.repository.UserRepository;
package com.book_everywhere.common.auth.service;

import com.book_everywhere.common.auth.dto.CustomOAuth2User;
import com.book_everywhere.common.auth.dto.OAuthAttributes;
import com.book_everywhere.common.auth.dto.UserDto;
import com.book_everywhere.common.auth.entity.Role;
import com.book_everywhere.common.auth.entity.User;
import com.book_everywhere.common.auth.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
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.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;


@Service
@RequiredArgsConstructor
Expand All @@ -34,13 +23,11 @@ public class CustomOAuth2UserService extends DefaultOAuth2UserService {

private final UserRepository userRepository;
private final HttpSession httpSession;
private final CustomUserDetailsService customUserDetailsService;


@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {


OAuth2User oAuth2User = super.loadUser(userRequest);

String registrationId = userRequest.getClientRegistration().getRegistrationId();
Expand All @@ -50,13 +37,11 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic

User user = saveOrUpdate(attributes);
httpSession.setAttribute("user", user);
UserDto userDto = new UserDto();
userDto.setNickname(user.getNickname());
userDto.setRole(String.valueOf(user.getRole()));


UserDetails userDetails = customUserDetailsService.loadUserBySocialId(user.getSocialId());
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

return new CustomOAuth2User(attributes,user.getRole());
return new CustomOAuth2User(userDto);
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.book_everywhere.exception;
package com.book_everywhere.common.exception;


import com.book_everywhere.exception.customs.CustomErrorCode;
import com.book_everywhere.common.exception.customs.CustomErrorCode;
import com.book_everywhere.common.dto.CMRespDto;
import com.book_everywhere.exception.customs.CustomException;
import com.book_everywhere.common.exception.customs.CustomException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.book_everywhere.exception.customs;
package com.book_everywhere.common.exception.customs;

import lombok.Getter;
import org.springframework.http.HttpStatus;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.book_everywhere.exception.customs;
package com.book_everywhere.common.exception.customs;

import lombok.Getter;

Expand Down
Loading

0 comments on commit 632b209

Please sign in to comment.