Skip to content

Commit

Permalink
Merge branch 'develop' into feature/104
Browse files Browse the repository at this point in the history
  • Loading branch information
Programmer-may authored Jan 20, 2024
2 parents 8e8ac80 + 1ab2a5a commit c4174cb
Show file tree
Hide file tree
Showing 33 changed files with 380 additions and 127 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public class EmailConfig {
public JavaMailSender mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port); //todo: 상수 분리
mailSender.setUsername(user); //todo: 상수 분리
mailSender.setPort(port);
mailSender.setUsername(user);
mailSender.setPassword(password);

Properties javaMailProperties = getMailProperties();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package kr.co.fastcampus.yanabada.common.config;

import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;

import java.util.List;
import kr.co.fastcampus.yanabada.common.jwt.filter.JwtAuthFilter;
import kr.co.fastcampus.yanabada.common.jwt.filter.JwtExceptionFilter;
Expand All @@ -11,6 +14,7 @@
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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;
Expand All @@ -34,8 +38,15 @@ public class SecurityConfig {
private final Oauth2LoginFailureHandler oauth2LoginFailureHandler;

private static final String[] PERMIT_PATHS = {
"/",
"/**"
"/auth", "/auth/**"
};

private static final String[] PERMIT_PATHS_POST_METHOD = {
"/accommodations/**", "/orders"
};

private static final String[] PERMIT_PATHS_GET_METHOD = {
"/products", "/products/**"
};

@Bean
Expand All @@ -49,8 +60,11 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
);

http.authorizeHttpRequests(authorize -> authorize
.requestMatchers(PERMIT_PATHS).permitAll()
.anyRequest().authenticated()
.requestMatchers(PERMIT_PATHS).permitAll()
.requestMatchers(POST, PERMIT_PATHS_POST_METHOD).permitAll()
.requestMatchers(GET, PERMIT_PATHS_GET_METHOD).permitAll()
.requestMatchers("/products/own").denyAll()
.anyRequest().authenticated()
);

http.oauth2Login(oauth2 -> oauth2
Expand All @@ -73,7 +87,7 @@ CorsConfigurationSource corsConfigurationSource() {
configuration.setAllowedMethods(List.of("*"));
configuration.setAllowedHeaders(List.of("*"));
configuration.addExposedHeader("Authorization");
configuration.setAllowCredentials(true); //todo : 쿠키를 포함한 크로스 도메인 요청을 허용? 확인필요
configuration.setAllowCredentials(true); //쿠키를 포함한 크로스 도메인 요청을 허용
configuration.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
Expand All @@ -83,7 +97,7 @@ CorsConfigurationSource corsConfigurationSource() {

@Bean
@ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true")
public WebSecurityCustomizer configureH2ConsoleEnable() { // h2-console 화면설정
public WebSecurityCustomizer configureH2ConsoleEnable() {
return web -> web.ignoring()
.requestMatchers(PathRequest.toH2Console());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package kr.co.fastcampus.yanabada.common.exception;

import static kr.co.fastcampus.yanabada.common.response.ErrorCode.NOT_MATCHED_PROVIDER_NAME;

public class NotMatchedProviderNameException extends BaseException {
public NotMatchedProviderNameException() {
super(NOT_MATCHED_PROVIDER_NAME.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import kr.co.fastcampus.yanabada.common.exception.FcmAccessTokenGetFailedException;
import kr.co.fastcampus.yanabada.common.exception.FcmMessageSendFailedException;
import kr.co.fastcampus.yanabada.common.exception.JsonProcessFailedException;
import kr.co.fastcampus.yanabada.common.exception.NotMatchedProviderNameException;
import kr.co.fastcampus.yanabada.common.exception.OkHttp3RequestFailedException;
import kr.co.fastcampus.yanabada.common.exception.TokenExpiredException;
import kr.co.fastcampus.yanabada.common.jwt.dto.TokenExpiredResponse;
Expand Down Expand Up @@ -177,4 +178,13 @@ public ResponseBody<Void> fcmAccessTokenGetFailedException(
return ResponseBody.fail(e.getMessage());
}

@ExceptionHandler(NotMatchedProviderNameException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBody<Void> notMatchedProviderNameException(
NotMatchedProviderNameException e
) {
log.error("[NotMatchedProviderNameException] Message = {}", e.getMessage());
return ResponseBody.fail(e.getMessage());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class JwtAuthFilter extends OncePerRequestFilter {
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
/* 토큰 로그인, 회원가입 경우 해당 필터 실행 안됨 */
return request.getRequestURI().contains("/sign-up")
|| request.getRequestURI().contains("/login"); //todo: 로그아웃 추가 고민
|| request.getRequestURI().contains("/login");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ public enum ErrorCode {

OKHTTP3_REQUEST_FAILED("okhttp3의 리퀘스트 생성이 실패하였습니다."),
FCM_MESSAGE_SEND_FAILED("FCM 메세지 전송이 실패하였습니다."),
FCM_ACCESS_TOKEN_GET_FAILED("FCM 엑세스 토큰을 발급 받는 데 실패하였습니다.")
FCM_ACCESS_TOKEN_GET_FAILED("FCM 엑세스 토큰을 발급 받는 데 실패하였습니다."),

NOT_MATCHED_PROVIDER_NAME("Provider 이름이 매칭이 안됩니다."),

;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import java.util.HashMap;
import java.util.Map;
import kr.co.fastcampus.yanabada.common.exception.NotMatchedProviderNameException;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -28,7 +29,7 @@ static Oauth2Attribute of(
return ofKakao(KAKAO.name(), "email", attributes);
//todo: 다른 OAuth 구현 시 조건문 추가
}
throw new RuntimeException(); //todo: CustomEx
throw new NotMatchedProviderNameException();
}

private static Oauth2Attribute ofKakao(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,24 @@
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Oauth2LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

@Value("${spring.login.root-url}")
String rootUrl;

@Override
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception
) throws IOException, ServletException {
response.sendRedirect("http://localhost:8080/");
//todo: 환경 변수로 뺄 예정
) throws IOException {
response.sendRedirect(rootUrl);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import kr.co.fastcampus.yanabada.domain.member.entity.ProviderType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
Expand All @@ -26,10 +27,14 @@
@RequiredArgsConstructor
public class Oauth2LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

private final JwtProvider jwtProvider;
private final TokenService tokenService;
private final AuthService authService;
private final ObjectMapper objectMapper;
@Value("${spring.login.root-url}")
String rootUrl;
@Value("${spring.login.oauth2-redirect-url}")
String oauthRedirectUrl;
@Value("${spring.login.oauth2-password}")
String oauthPassword;

@Override
@Transactional
Expand All @@ -48,7 +53,6 @@ public void onAuthenticationSuccess(

if (isExist) {
/* 바로 로그인 */
String oauthPassword = "oauth-password"; //todo: 환경 변수 분리
LoginRequest loginRequest = new LoginRequest(email, oauthPassword);
LoginResponse loginResponse
= authService.loginOauth(loginRequest, ProviderType.valueOf(provider));
Expand All @@ -58,8 +62,9 @@ public void onAuthenticationSuccess(
response.getWriter().write(loginResponseJson);
} else {
/* 회원 가입 필요 */
//todo: url 변경 예정, 환경 변수(서버, 로컬) 분리 예정
String redirectUrl = "http://localhost:8080/redirect-url"
//todo: url 변경 예정
String redirectUrl = rootUrl
+ oauthRedirectUrl
+ "?email=" + attribute.get("email")
+ "&provider=" + attribute.get("provider");
response.sendRedirect(redirectUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static kr.co.fastcampus.yanabada.domain.member.entity.ProviderType.EMAIL;
import static kr.co.fastcampus.yanabada.domain.member.entity.RoleType.ROLE_USER;

import java.util.Random;
import kr.co.fastcampus.yanabada.common.exception.EmailDuplicatedException;
import kr.co.fastcampus.yanabada.common.jwt.dto.TokenIssueResponse;
import kr.co.fastcampus.yanabada.common.jwt.dto.TokenRefreshResponse;
Expand All @@ -17,6 +18,7 @@
import kr.co.fastcampus.yanabada.domain.member.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -35,6 +37,8 @@ public class AuthService {
private final JwtProvider jwtProvider;
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final TokenService tokenService;
@Value("${spring.login.oauth2-password}")
String oauthPassword;

@Transactional
public Long signUp(SignUpRequest signUpRequest) {
Expand All @@ -43,14 +47,16 @@ public Long signUp(SignUpRequest signUpRequest) {
}

String encodedPassword = passwordEncoder.encode(signUpRequest.password());

Member member = Member.builder()
.email(signUpRequest.email())
.nickName(signUpRequest.nickName())
.password(encodedPassword)
.phoneNumber(signUpRequest.phoneNumber())
.roleType(ROLE_USER)
.providerType(EMAIL)
.build();
.email(signUpRequest.email())
.nickName(signUpRequest.nickName())
.password(encodedPassword)
.phoneNumber(signUpRequest.phoneNumber())
.roleType(ROLE_USER)
.image(getRandomProfileImage())
.providerType(EMAIL)
.build();

Member savedMember = memberRepository.save(member);
return savedMember.getId();
Expand All @@ -59,21 +65,27 @@ public Long signUp(SignUpRequest signUpRequest) {
@Transactional
public Long oauthSignUp(OauthSignUpRequest signUpRequest) {

String encodedPassword = passwordEncoder.encode("oauth-password");
//todo: 패스워드 환경변수 분리
String encodedPassword = passwordEncoder.encode(oauthPassword);
Member member = Member.builder()
.email(signUpRequest.email())
.nickName(signUpRequest.nickName())
.password(encodedPassword)
.phoneNumber(signUpRequest.phoneNumber())
.roleType(ROLE_USER)
.image(getRandomProfileImage())
.providerType(signUpRequest.provider())
.build();

Member savedMember = memberRepository.save(member);
return savedMember.getId();
}

private String getRandomProfileImage() {
Random random = new Random();
int randomNumber = random.nextInt(5) + 1;
return randomNumber + "profile.png"; //todo: 환경 변수 분리
}

@Transactional
public LoginResponse login(LoginRequest loginRequest) {
UsernamePasswordAuthenticationToken authenticationToken = loginRequest.toAuthentication();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static SendChatMessage from(
.chatRoomCode(chatRoom.getCode())
.sendId(sender.getId())
.senderNickname(sender.getNickName())
.senderProfileImage(sender.getImageUrl())
.senderProfileImage(sender.getImage())
.content(content)
.sendTime(sendTime)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static ChatMessageInfoResponse from(
) {
return ChatMessageInfoResponse.builder()
.senderId(sender.getId())
.senderImage(sender.getImageUrl())
.senderImage(sender.getImage())
.senderNickname(sender.getNickName())
.content(content)
.sendDateTime(sendDateTime)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static ChatRoomSummaryResponse from(
) {
return ChatRoomSummaryResponse.builder()
.chatRoomCode(chatRoomCode)
.partnerImage(partner.getImageUrl())
.partnerImage(partner.getImage())
.partnerNickname(partner.getNickName())
.lastChatMessage(message.getContent())
.lastSentMessageTime(message.getSendDateTime())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import kr.co.fastcampus.yanabada.common.response.ResponseBody;
import kr.co.fastcampus.yanabada.common.security.PrincipalDetails;
import kr.co.fastcampus.yanabada.domain.member.dto.request.FcmTokenUpdateRequest;
import kr.co.fastcampus.yanabada.domain.member.dto.request.ImgUrlModifyRequest;
import kr.co.fastcampus.yanabada.domain.member.dto.request.NickNameModifyRequest;
import kr.co.fastcampus.yanabada.domain.member.dto.request.PasswordModifyRequest;
import kr.co.fastcampus.yanabada.domain.member.dto.request.PhoneNumberModifyRequest;
Expand Down Expand Up @@ -69,17 +68,6 @@ public ResponseBody<Void> modifyPhoneNumber(
return ResponseBody.ok();
}

@PutMapping("/image")
public ResponseBody<Void> modifyImage(
@AuthenticationPrincipal PrincipalDetails principalDetails,
@RequestBody @Valid ImgUrlModifyRequest imgUrlRequest
) {
memberService.modifyImageUrl(
imgUrlRequest, principalDetails.email(), principalDetails.provider()
);
return ResponseBody.ok();
}

@PutMapping("/fcm-token")
public ResponseBody<Void> updateFcmToken(
@AuthenticationPrincipal PrincipalDetails principalDetails,
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public record MemberDetailResponse(
String email,
String nickName,
String phoneNumber,
String imageUrl,
String image,
Integer point,
ProviderType provider
) {
Expand All @@ -20,7 +20,7 @@ public static MemberDetailResponse from(Member member) {
.email(member.getEmail())
.nickName(member.getNickName())
.phoneNumber(member.getPhoneNumber())
.imageUrl(member.getImageUrl())
.image(member.getImage())
.point(member.getPoint())
.provider(member.getProviderType())
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
public record MemberSummaryResponse(
Long id,
String nickname,
String imageUrl
String image
) {

public static MemberSummaryResponse from(Member member) {
return MemberSummaryResponse.builder()
.id(member.getId())
.nickname(member.getNickName())
.imageUrl(member.getImageUrl())
.image(member.getImage())
.build();
}
}
Loading

0 comments on commit c4174cb

Please sign in to comment.