Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/NewFit/NewFit-Backend in…
Browse files Browse the repository at this point in the history
…to release/dev
  • Loading branch information
Sangwook02 committed Dec 16, 2023
2 parents 5a948d5 + 989d700 commit cf3627e
Show file tree
Hide file tree
Showing 153 changed files with 4,519 additions and 4,159 deletions.
32 changes: 17 additions & 15 deletions src/main/java/com/newfit/reservation/common/S3Service.java
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
package com.newfit.reservation.common;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import lombok.RequiredArgsConstructor;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class S3Service {
private final AmazonS3 amazonS3;
private final AmazonS3 amazonS3;

@Value("${cloud.aws.s3.bucket}")
private String bucket;
@Value("${cloud.aws.s3.bucket}")
private String bucket;

public String uploadFile(MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
metadata.setContentLength(multipartFile.getSize());
public String uploadFile(MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
metadata.setContentLength(multipartFile.getSize());

amazonS3.putObject(bucket, originalFilename, multipartFile.getInputStream(), metadata);
return amazonS3.getUrl(bucket, originalFilename).toString();
}
amazonS3.putObject(bucket, originalFilename, multipartFile.getInputStream(), metadata);
return amazonS3.getUrl(bucket, originalFilename).toString();
}
}
Original file line number Diff line number Diff line change
@@ -1,42 +1,44 @@
package com.newfit.reservation.common.auth;

import static com.newfit.reservation.common.exception.ErrorCodeType.*;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import com.newfit.reservation.common.exception.CustomException;
import com.newfit.reservation.domains.authority.domain.Authority;
import com.newfit.reservation.domains.authority.repository.AuthorityRepository;
import com.newfit.reservation.domains.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import static com.newfit.reservation.common.exception.ErrorCodeType.*;
import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class AuthorityCheckService {

private final UserRepository userRepository;
private final AuthorityRepository authorityRepository;

public void validateByUserId(Authentication authentication, Long userId) {
User principal = (User) authentication.getPrincipal();
com.newfit.reservation.domains.user.domain.User user = userRepository.findById(userId)
.orElseThrow(() -> new CustomException(USER_NOT_FOUND));

String nickname = principal.getUsername();
if (!user.getNickname().equals(nickname)) {
throw new CustomException(UNAUTHORIZED_REQUEST);
}
}

public void validateByAuthorityId(Authentication authentication, Long authorityId) {
User principal = (User) authentication.getPrincipal();
Authority authority = authorityRepository.findById(authorityId)
.orElseThrow(() -> new CustomException(AUTHORITY_NOT_FOUND));

String nickname = principal.getUsername();
if (!authority.getUser().getNickname().equals(nickname)) {
throw new CustomException(UNAUTHORIZED_REQUEST);
}
}
private final UserRepository userRepository;
private final AuthorityRepository authorityRepository;

public void validateByUserId(Authentication authentication, Long userId) {
User principal = (User)authentication.getPrincipal();
com.newfit.reservation.domains.user.domain.User user = userRepository.findById(userId)
.orElseThrow(() -> new CustomException(USER_NOT_FOUND));

String nickname = principal.getUsername();
if (!user.getNickname().equals(nickname)) {
throw new CustomException(UNAUTHORIZED_REQUEST);
}
}

public void validateByAuthorityId(Authentication authentication, Long authorityId) {
User principal = (User)authentication.getPrincipal();
Authority authority = authorityRepository.findById(authorityId)
.orElseThrow(() -> new CustomException(AUTHORITY_NOT_FOUND));

String nickname = principal.getUsername();
if (!authority.getUser().getNickname().equals(nickname)) {
throw new CustomException(UNAUTHORIZED_REQUEST);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
package com.newfit.reservation.common.auth.config;

import java.util.stream.Stream;

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.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.newfit.reservation.common.auth.jwt.TokenAuthenticationFilter;
import com.newfit.reservation.common.auth.jwt.TokenProvider;
Expand All @@ -10,98 +23,90 @@
import com.newfit.reservation.common.exception.CustomExceptionHandlingFilter;
import com.newfit.reservation.domains.auth.repository.RefreshTokenRepository;
import com.newfit.reservation.domains.user.repository.UserRepository;

import jakarta.servlet.http.HttpServletRequest;
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.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.stream.Stream;

@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
public class WebSecurityConfig {
private final static String AUTHENTICATION = "Authorization";
private final static String BEARER = "Bearer ";
private final static String AUTHENTICATION = "Authorization";
private final static String BEARER = "Bearer ";

private final TokenProvider tokenProvider;
private final UserRepository userRepository;
private final RefreshTokenRepository refreshTokenRepository;
private final OAuth2UserCustomService oAuth2UserCustomService;
private final OAuth2SuccessHandler oAuth2SuccessHandler;
private final OAuth2FailureHandler oAuth2FailureHandler;
private final ObjectMapper objectMapper;
private final TokenProvider tokenProvider;
private final UserRepository userRepository;
private final RefreshTokenRepository refreshTokenRepository;
private final OAuth2UserCustomService oAuth2UserCustomService;
private final OAuth2SuccessHandler oAuth2SuccessHandler;
private final OAuth2FailureHandler oAuth2FailureHandler;
private final ObjectMapper objectMapper;

// 누구나 접근할 수 있는 URI 패턴을 정의
private static final String[] PERMIT_ALL_PATTERNS = new String[] {
"/login/**",
"/logout/**"
};
// 누구나 접근할 수 있는 URI 패턴을 정의
private static final String[] PERMIT_ALL_PATTERNS = new String[] {
"/login/**",
"/logout/**"
};

// Spring Security가 무시하도록 할 요청을 정의
@Bean
public WebSecurityCustomizer configure() {
return (web) -> web.ignoring()
.requestMatchers(AntPathRequestMatcher.antMatcher("/static/**"));
}
// Spring Security가 무시하도록 할 요청을 정의
@Bean
public WebSecurityCustomizer configure() {
return (web) -> web.ignoring()
.requestMatchers(AntPathRequestMatcher.antMatcher("/static/**"));
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
.requestMatchers(Stream.of(PERMIT_ALL_PATTERNS).map(AntPathRequestMatcher::antMatcher).toArray(AntPathRequestMatcher[]::new)).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/api/v1/manager/**")).hasRole("MANAGER")
.requestMatchers(AntPathRequestMatcher.antMatcher("/v1/admin/**")).hasRole("ADMIN")
.requestMatchers(AntPathRequestMatcher.antMatcher("/api/**")).authenticated()
.anyRequest().permitAll())
.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(customExceptionHandlingFilter(), TokenAuthenticationFilter.class)
.oauth2Login(oauth -> oauth
.userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint.userService(oAuth2UserCustomService))
.successHandler(oAuth2SuccessHandler)
.failureHandler(oAuth2FailureHandler)
.authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint
.authorizationRequestRepository(oAuth2AuthorizationRequestCookieRepository())))
.logout(logout -> logout
.logoutUrl("/logout")
.addLogoutHandler((request, response, authentication) -> {
tokenProvider.disableRefreshToken(getToken(request));
})
.logoutSuccessUrl("/login"))
.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
.requestMatchers(Stream.of(PERMIT_ALL_PATTERNS)
.map(AntPathRequestMatcher::antMatcher)
.toArray(AntPathRequestMatcher[]::new)).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/api/v1/manager/**")).hasRole("MANAGER")
.requestMatchers(AntPathRequestMatcher.antMatcher("/v1/admin/**")).hasRole("ADMIN")
.requestMatchers(AntPathRequestMatcher.antMatcher("/api/**")).authenticated()
.anyRequest().permitAll())
.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(customExceptionHandlingFilter(), TokenAuthenticationFilter.class)
.oauth2Login(oauth -> oauth
.userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint.userService(oAuth2UserCustomService))
.successHandler(oAuth2SuccessHandler)
.failureHandler(oAuth2FailureHandler)
.authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint
.authorizationRequestRepository(oAuth2AuthorizationRequestCookieRepository())))
.logout(logout -> logout
.logoutUrl("/logout")
.addLogoutHandler((request, response, authentication) -> {
tokenProvider.disableRefreshToken(getToken(request));
})
.logoutSuccessUrl("/login"))
.build();
}

@Bean
public TokenAuthenticationFilter tokenAuthenticationFilter() {
return new TokenAuthenticationFilter(tokenProvider, refreshTokenRepository, userRepository);
}
@Bean
public TokenAuthenticationFilter tokenAuthenticationFilter() {
return new TokenAuthenticationFilter(tokenProvider, refreshTokenRepository, userRepository);
}

@Bean
public OAuth2AuthorizationRequestCookieRepository oAuth2AuthorizationRequestCookieRepository() {
return new OAuth2AuthorizationRequestCookieRepository();
}
@Bean
public OAuth2AuthorizationRequestCookieRepository oAuth2AuthorizationRequestCookieRepository() {
return new OAuth2AuthorizationRequestCookieRepository();
}

@Bean
public CustomExceptionHandlingFilter customExceptionHandlingFilter() {
return new CustomExceptionHandlingFilter(objectMapper);
}
@Bean
public CustomExceptionHandlingFilter customExceptionHandlingFilter() {
return new CustomExceptionHandlingFilter(objectMapper);
}

private String getToken(HttpServletRequest request) {
String authorizationHeader = request.getHeader(AUTHENTICATION);
if (authorizationHeader != null && authorizationHeader.startsWith(BEARER)) {
return authorizationHeader.substring(BEARER.length());
}
return null;
}
private String getToken(HttpServletRequest request) {
String authorizationHeader = request.getHeader(AUTHENTICATION);
if (authorizationHeader != null && authorizationHeader.startsWith(BEARER)) {
return authorizationHeader.substring(BEARER.length());
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package com.newfit.reservation.common.auth.jwt;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Component
public class JwtProperties { // JWT 관련 설정 정보를 담는 클래스
@Value("${jwt.issuer}")
private String issuer;
@Value("${jwt.issuer}")
private String issuer;

@Value("${jwt.secret_key}")
private byte[] secretKey;
@Value("${jwt.secret_key}")
private byte[] secretKey;
}
Loading

0 comments on commit cf3627e

Please sign in to comment.