diff --git a/build.gradle b/build.gradle index ff68a3d..8acea08 100644 --- a/build.gradle +++ b/build.gradle @@ -36,19 +36,19 @@ dependencies { // model mapper implementation 'org.modelmapper:modelmapper:3.1.0' - // security - implementation 'org.springframework.boot:spring-boot-starter-security' - - // jwt - implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2' - runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2' - runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2' - - // Oauth2 - implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' - - // Redis - implementation 'org.springframework.boot:spring-boot-starter-data-redis' +// security +// implementation 'org.springframework.boot:spring-boot-starter-security' +// +// // jwt +// implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2' +// runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2' +// runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2' +// +// // Oauth2 +// implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' +// +// // Redis +// implementation 'org.springframework.boot:spring-boot-starter-data-redis' //s3 implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE' diff --git a/src/main/java/aromanticcat/umcproject/converter/MemberConverter.java b/src/main/java/aromanticcat/umcproject/converter/MemberConverter.java index f8065a3..4e82a62 100644 --- a/src/main/java/aromanticcat/umcproject/converter/MemberConverter.java +++ b/src/main/java/aromanticcat/umcproject/converter/MemberConverter.java @@ -1,5 +1,6 @@ package aromanticcat.umcproject.converter; +import aromanticcat.umcproject.entity.FriendStatus; import aromanticcat.umcproject.entity.Member; import aromanticcat.umcproject.web.dto.Member.MemberRequestDTO; import aromanticcat.umcproject.web.dto.Member.MemberResponseDTO; @@ -24,6 +25,7 @@ public static MemberRequestDTO.searchMemberDTO toSearchMemberDTO(Member member) return MemberRequestDTO.searchMemberDTO.builder() .memberId(member.getId()) .nickname(member.getNickname()) + .friendStatus(FriendStatus.NOT_FRIEND) .build(); } } diff --git a/src/main/java/aromanticcat/umcproject/entity/Friend.java b/src/main/java/aromanticcat/umcproject/entity/Friend.java index bc2974e..db43aae 100644 --- a/src/main/java/aromanticcat/umcproject/entity/Friend.java +++ b/src/main/java/aromanticcat/umcproject/entity/Friend.java @@ -51,4 +51,6 @@ public int updateExchange_num() { this.exchange_num++; return exchange_num; } + + public void changeIsFrom(Boolean isFrom){ this.isFrom = isFrom; } } diff --git a/src/main/java/aromanticcat/umcproject/entity/Member.java b/src/main/java/aromanticcat/umcproject/entity/Member.java index 344fd7c..938bc6e 100644 --- a/src/main/java/aromanticcat/umcproject/entity/Member.java +++ b/src/main/java/aromanticcat/umcproject/entity/Member.java @@ -1,6 +1,6 @@ package aromanticcat.umcproject.entity; -import aromanticcat.umcproject.security.Role; +//import aromanticcat.umcproject.security.Role; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; @@ -39,8 +39,8 @@ public class Member extends BaseEntity { private int coin; - @Enumerated(EnumType.STRING) - private Role userRole; +// @Enumerated(EnumType.STRING) +// private Role userRole; @OneToMany(mappedBy = "member", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List memberMissions = new ArrayList<>(); diff --git a/src/main/java/aromanticcat/umcproject/entity/Reward.java b/src/main/java/aromanticcat/umcproject/entity/Reward.java deleted file mode 100644 index e9c67e4..0000000 --- a/src/main/java/aromanticcat/umcproject/entity/Reward.java +++ /dev/null @@ -1,32 +0,0 @@ -package aromanticcat.umcproject.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; -import lombok.Getter; - -@Entity -@Getter -public class Reward extends BaseEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - private int type; - - @Column(columnDefinition = "TEXT") - private String image_url; - - private String name; - - @JoinColumn(name = "mission_id") - @OneToOne(fetch = FetchType.LAZY) - private Mission mission; - -} diff --git a/src/main/java/aromanticcat/umcproject/repository/FriendRepository.java b/src/main/java/aromanticcat/umcproject/repository/FriendRepository.java index d5e81d4..3628eca 100644 --- a/src/main/java/aromanticcat/umcproject/repository/FriendRepository.java +++ b/src/main/java/aromanticcat/umcproject/repository/FriendRepository.java @@ -8,18 +8,33 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Set; public interface FriendRepository extends JpaRepository { - @Query("SELECT f FROM Friend f WHERE f.member = :member AND f.friendStatus IN (:friendStatus)") - Page findFriendByMemberAndFriendStatus(Member member, Set friendStatus, Pageable pageable); + @Query("SELECT f " + + "FROM Friend f " + + "WHERE f.member = :member " + + "AND f.friendStatus IN (:friendStatus)") + Page findFriendByMemberAndFriendStatus(@Param("member") Member member, + @Param("friendStatus") Set friendStatus, + Pageable pageable); List findFriendByMemberAndFriendName(Member member, String friendName); List findFriendByMemberAndFriendId(Member member, Long friendId); Friend findByMemberAndFriendId(Member member, Long friendId); + + @Query("SELECT CASE WHEN COUNT(f) > 0 THEN TRUE ELSE FALSE END " + + "FROM Friend f " + + "WHERE f.member = :member " + + "AND f.friendId = :findMemberId " + + "AND f.friendStatus IN :friendStatus") + Boolean existsByMemberAndFriendIdAndFriendStatus(@Param("member") Member member, + @Param("findMemberId") Long findMemberId, + @Param("friendStatus") Set friendStatus); } diff --git a/src/main/java/aromanticcat/umcproject/repository/RefreshTokenRepository.java b/src/main/java/aromanticcat/umcproject/repository/RefreshTokenRepository.java index 27cb37b..63cb72c 100644 --- a/src/main/java/aromanticcat/umcproject/repository/RefreshTokenRepository.java +++ b/src/main/java/aromanticcat/umcproject/repository/RefreshTokenRepository.java @@ -1,13 +1,13 @@ -package aromanticcat.umcproject.repository; - -import aromanticcat.umcproject.security.jwt.RefreshToken; -import java.util.Optional; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface RefreshTokenRepository extends CrudRepository { - - // accessToken으로 RefreshToken을 찾아온다. - Optional findByAccessToken(String accessToken); -} +//package aromanticcat.umcproject.repository; +// +//import aromanticcat.umcproject.security.jwt.RefreshToken; +//import java.util.Optional; +//import org.springframework.data.repository.CrudRepository; +//import org.springframework.stereotype.Repository; +// +//@Repository +//public interface RefreshTokenRepository extends CrudRepository { +// +// // accessToken으로 RefreshToken을 찾아온다. +// Optional findByAccessToken(String accessToken); +//} diff --git a/src/main/java/aromanticcat/umcproject/security/Role.java b/src/main/java/aromanticcat/umcproject/security/Role.java index 94cbca8..0e340f7 100644 --- a/src/main/java/aromanticcat/umcproject/security/Role.java +++ b/src/main/java/aromanticcat/umcproject/security/Role.java @@ -1,15 +1,15 @@ -package aromanticcat.umcproject.security; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@Getter -@RequiredArgsConstructor -public enum Role { - - GUSET("ROLE_GUEST", "손님"), - USER("ROLE_USER", "일반 사용자"); - - private final String key; - private final String title; -} +//package aromanticcat.umcproject.security; +// +//import lombok.Getter; +//import lombok.RequiredArgsConstructor; +// +//@Getter +//@RequiredArgsConstructor +//public enum Role { +// +// GUSET("ROLE_GUEST", "손님"), +// USER("ROLE_USER", "일반 사용자"); +// +// private final String key; +// private final String title; +//} diff --git a/src/main/java/aromanticcat/umcproject/security/SecurityConfig.java b/src/main/java/aromanticcat/umcproject/security/SecurityConfig.java index b4af011..a426b57 100644 --- a/src/main/java/aromanticcat/umcproject/security/SecurityConfig.java +++ b/src/main/java/aromanticcat/umcproject/security/SecurityConfig.java @@ -1,61 +1,64 @@ -package aromanticcat.umcproject.security; - -import aromanticcat.umcproject.security.jwt.JwtAuthFilter; -import aromanticcat.umcproject.security.jwt.JwtExceptionFilter; -import aromanticcat.umcproject.security.oauth.CustomOAuth2UserService; -import aromanticcat.umcproject.security.oauth.MyAuthenticationFailureHandler; -import aromanticcat.umcproject.security.oauth.MyAuthenticationSuccessHandler; -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.http.SessionCreationPolicy; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - -@Configuration -@EnableWebSecurity -@RequiredArgsConstructor -public class SecurityConfig { - - private final MyAuthenticationSuccessHandler oAuth2LoginSuccessHandler; - private final CustomOAuth2UserService customOAuth2UserService; - private final JwtAuthFilter jwtAuthFilter; - private final MyAuthenticationFailureHandler oAuth2LoginFailureHandler; - private final JwtExceptionFilter jwtExceptionFilter; - - @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http - .httpBasic().disable() // HTTP 기본 인증을 비활성화 - .cors().and() // CORS 활성화 - .csrf().disable() // CSRF 보호 기능 비활성화 - .logout().disable() - .sessionManagement() - .sessionCreationPolicy( - SessionCreationPolicy.STATELESS) // 세션관리 정책을 STATELESS(세션이 있으면 쓰지도 않고, 없으면 만들지도 않는다) - .and() - .authorizeRequests() // 요청에 대한 인증 설정 - .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**").permitAll() - .antMatchers("/", "/login/**", "/signUp/**", "/nangman-collection/", - "/nangman-collection/{nangmanLetterId}/like", - "/nangman-collection/{nangmanLetterId}").permitAll() - .antMatchers("/token/**").permitAll() // 토큰 발급을 위한 경로는 모두 허용 - .antMatchers("/css/**", "/images/**", "/js/**", "/favicon.ico", "/h2-console/**").permitAll() - .anyRequest().authenticated() // 그 외의 모든 요청은 인증이 필요하다. - .and() - .oauth2Login() // OAuth2 로그인 설정시작 - .userInfoEndpoint().userService(customOAuth2UserService) // OAuth2 로그인시 사용자 정보를 가져오는 엔드포인트와 사용자 서비스를 설정 - .and() - .failureHandler(oAuth2LoginFailureHandler) // OAuth2 로그인 실패시 처리할 핸들러를 지정해준다. - .successHandler(oAuth2LoginSuccessHandler); // OAuth2 로그인 성공시 처리할 핸들러를 지정해준다. - - // JWT 인증 필터를 UsernamePasswordAuthenticationFilter 앞에 추가한다. - return http - .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) - .addFilterBefore(jwtExceptionFilter, JwtAuthFilter.class) - .build(); - } - -} +//package aromanticcat.umcproject.security; +// +//import aromanticcat.umcproject.security.jwt.JwtAuthFilter; +//import aromanticcat.umcproject.security.jwt.JwtExceptionFilter; +//import aromanticcat.umcproject.security.oauth.CustomOAuth2UserService; +//import aromanticcat.umcproject.security.oauth.MyAuthenticationFailureHandler; +//import aromanticcat.umcproject.security.oauth.MyAuthenticationSuccessHandler; +//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.http.SessionCreationPolicy; +//import org.springframework.security.web.SecurityFilterChain; +//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +// +//@Configuration +//@EnableWebSecurity +//@RequiredArgsConstructor +//public class SecurityConfig { +// +// private final MyAuthenticationSuccessHandler oAuth2LoginSuccessHandler; +// private final CustomOAuth2UserService customOAuth2UserService; +// private final JwtAuthFilter jwtAuthFilter; +// private final MyAuthenticationFailureHandler oAuth2LoginFailureHandler; +// private final JwtExceptionFilter jwtExceptionFilter; +// +// @Bean +// public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { +// http +// .httpBasic().disable() // HTTP 기본 인증을 비활성화 +// .cors().and() // CORS 활성화 +// .csrf().disable() // CSRF 보호 기능 비활성화 +// .logout().disable() +// .sessionManagement() +// .sessionCreationPolicy( +// SessionCreationPolicy.STATELESS) // 세션관리 정책을 STATELESS(세션이 있으면 쓰지도 않고, 없으면 만들지도 않는다) +// .and() +// .authorizeRequests() // 요청에 대한 인증 설정 +// .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**").permitAll() +// .antMatchers("/", "/login/**", "/signUp/**", "/nangman-collection/", +// "/nangman-collection/{nangmanLetterId}/like", +// "/nangman-collection/{nangmanLetterId},", +// "/missions/**", +// "/address-book/**", +// "/my-collection/letter-paper").permitAll() +// .antMatchers("/token/**").permitAll() // 토큰 발급을 위한 경로는 모두 허용 +// .antMatchers("/css/**", "/images/**", "/js/**", "/favicon.ico", "/h2-console/**").permitAll() +// .anyRequest().authenticated() // 그 외의 모든 요청은 인증이 필요하다. +// .and() +// .oauth2Login() // OAuth2 로그인 설정시작 +// .userInfoEndpoint().userService(customOAuth2UserService) // OAuth2 로그인시 사용자 정보를 가져오는 엔드포인트와 사용자 서비스를 설정 +// .and() +// .failureHandler(oAuth2LoginFailureHandler) // OAuth2 로그인 실패시 처리할 핸들러를 지정해준다. +// .successHandler(oAuth2LoginSuccessHandler); // OAuth2 로그인 성공시 처리할 핸들러를 지정해준다. +// +// // JWT 인증 필터를 UsernamePasswordAuthenticationFilter 앞에 추가한다. +// return http +// .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) +// .addFilterBefore(jwtExceptionFilter, JwtAuthFilter.class) +// .build(); +// } +// +//} diff --git a/src/main/java/aromanticcat/umcproject/security/SecurityUserDto.java b/src/main/java/aromanticcat/umcproject/security/SecurityUserDto.java index 71a664b..a37885d 100644 --- a/src/main/java/aromanticcat/umcproject/security/SecurityUserDto.java +++ b/src/main/java/aromanticcat/umcproject/security/SecurityUserDto.java @@ -1,27 +1,28 @@ -package aromanticcat.umcproject.security; - -import static aromanticcat.umcproject.security.Role.USER; - -import aromanticcat.umcproject.entity.Member; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@Getter -@Builder -@AllArgsConstructor -@NoArgsConstructor -public class SecurityUserDto { - private String nickname; - private String email; - private Role role; - - public Member toEntity() { - return Member.builder() - .email(email) - .nickname(nickname) - .userRole(USER) - .build(); - } -} +//package aromanticcat.umcproject.security; +// +//import static aromanticcat.umcproject.security.Role.USER; +// +//import aromanticcat.umcproject.entity.Member; +//import lombok.AllArgsConstructor; +//import lombok.Builder; +//import lombok.Getter; +//import lombok.NoArgsConstructor; +// +//@Getter +//@Builder +//@AllArgsConstructor +//@NoArgsConstructor +//public class SecurityUserDto { +// +// private String nickname; +// private String email; +// private Role role; +// +// public Member toEntity() { +// return Member.builder() +// .email(email) +// .nickname(nickname) +// .userRole(USER) +// .build(); +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/StatusResponseDto.java b/src/main/java/aromanticcat/umcproject/security/StatusResponseDto.java index 1396c54..40e37a0 100644 --- a/src/main/java/aromanticcat/umcproject/security/StatusResponseDto.java +++ b/src/main/java/aromanticcat/umcproject/security/StatusResponseDto.java @@ -1,22 +1,22 @@ -package aromanticcat.umcproject.security; - -import com.fasterxml.jackson.annotation.JsonInclude; -import lombok.AllArgsConstructor; -import lombok.Getter; - -@Getter -@AllArgsConstructor -@JsonInclude(JsonInclude.Include.NON_NULL) // DTO 를 JSON으로 변환 시 null값인 field 제외 -public class StatusResponseDto { - private Integer status; - private Object data; - - public StatusResponseDto(Integer status) { - this.status = status; - } - - public static StatusResponseDto addStatus(Integer status) { - return new StatusResponseDto(status); - } - -} +//package aromanticcat.umcproject.security; +// +//import com.fasterxml.jackson.annotation.JsonInclude; +//import lombok.AllArgsConstructor; +//import lombok.Getter; +// +//@Getter +//@AllArgsConstructor +//@JsonInclude(JsonInclude.Include.NON_NULL) // DTO 를 JSON으로 변환 시 null값인 field 제외 +//public class StatusResponseDto { +// private Integer status; +// private Object data; +// +// public StatusResponseDto(Integer status) { +// this.status = status; +// } +// +// public static StatusResponseDto addStatus(Integer status) { +// return new StatusResponseDto(status); +// } +// +//} diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/GeneratedToken.java b/src/main/java/aromanticcat/umcproject/security/jwt/GeneratedToken.java index cbbee2c..7f9c5b4 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/GeneratedToken.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/GeneratedToken.java @@ -1,14 +1,14 @@ -package aromanticcat.umcproject.security.jwt; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -@Builder -@Data -@AllArgsConstructor -public class GeneratedToken { - - private String accessToken; - private String refreshToken; -} +//package aromanticcat.umcproject.security.jwt; +// +//import lombok.AllArgsConstructor; +//import lombok.Builder; +//import lombok.Data; +// +//@Builder +//@Data +//@AllArgsConstructor +//public class GeneratedToken { +// +// private String accessToken; +// private String refreshToken; +//} diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/JwtAuthFilter.java b/src/main/java/aromanticcat/umcproject/security/jwt/JwtAuthFilter.java index 43899f2..6ddc0a9 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/JwtAuthFilter.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/JwtAuthFilter.java @@ -1,83 +1,83 @@ -package aromanticcat.umcproject.security.jwt; - -import aromanticcat.umcproject.entity.Member; -import aromanticcat.umcproject.repository.MemberRepository; -import aromanticcat.umcproject.security.SecurityUserDto; -import io.jsonwebtoken.JwtException; -import java.io.IOException; -import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -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.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.OncePerRequestFilter; - -@RequiredArgsConstructor -@Slf4j -@Component -public class JwtAuthFilter extends OncePerRequestFilter { - - private final JwtUtil jwtUtil; - private final MemberRepository memberRepository; - - @Override - protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { - return request.getRequestURI().contains("token/"); - } - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - // request Header에서 AccessToken을 가져온다. - String atc = request.getHeader("Authorization"); - - // 토큰 검사 생략(모두 허용 URL의 경우 토큰 검사 통과) - if (!StringUtils.hasText(atc)) { - doFilter(request, response, filterChain); - return; - } - - // AccessToken을 검증하고, 만료되었을경우 예외를 발생시킨다. - if (!jwtUtil.verifyToken(atc)) { - throw new JwtException("Access Token 만료!"); - } - // AccessToken의 값이 있고, 유효한 경우에 진행한다. - if (jwtUtil.verifyToken(atc)) { - - // AccessToken 내부의 payload에 있는 email로 user를 조회한다. 없다면 예외를 발생시킨다 -> 정상 케이스가 아님 - Member findMember = memberRepository.findByEmail(jwtUtil.getUid(atc)) - .orElseThrow(IllegalStateException::new); - - // SecurityContext에 등록할 User 객체를 만들어준다. - SecurityUserDto userDto = SecurityUserDto.builder() - .email(findMember.getEmail()) - .role(findMember.getUserRole()) - .nickname(findMember.getNickname()) - .build(); - - // SecurityContext에 인증 객체를 등록해준다. - Authentication auth = getAuthentication(userDto); - SecurityContextHolder.getContext().setAuthentication(auth); - } - - filterChain.doFilter(request, response); - } - - - public Authentication getAuthentication(SecurityUserDto member) { - return new UsernamePasswordAuthenticationToken(member, "", - List.of(new SimpleGrantedAuthority(member.getRole().getKey()))); - } - - public static SecurityUserDto getUser() { - return (SecurityUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } -} +//package aromanticcat.umcproject.security.jwt; +// +//import aromanticcat.umcproject.entity.Member; +//import aromanticcat.umcproject.repository.MemberRepository; +//import aromanticcat.umcproject.security.SecurityUserDto; +//import io.jsonwebtoken.JwtException; +//import java.io.IOException; +//import java.util.List; +//import javax.servlet.FilterChain; +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//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.authority.SimpleGrantedAuthority; +//import org.springframework.security.core.context.SecurityContextHolder; +//import org.springframework.stereotype.Component; +//import org.springframework.util.StringUtils; +//import org.springframework.web.filter.OncePerRequestFilter; +// +//@RequiredArgsConstructor +//@Slf4j +//@Component +//public class JwtAuthFilter extends OncePerRequestFilter { +// +// private final JwtUtil jwtUtil; +// private final MemberRepository memberRepository; +// +// @Override +// protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { +// return request.getRequestURI().contains("token/"); +// } +// +// @Override +// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) +// throws ServletException, IOException { +// // request Header에서 AccessToken을 가져온다. +// String atc = request.getHeader("Authorization"); +// +// // 토큰 검사 생략(모두 허용 URL의 경우 토큰 검사 통과) +// if (!StringUtils.hasText(atc)) { +// doFilter(request, response, filterChain); +// return; +// } +// +// // AccessToken을 검증하고, 만료되었을경우 예외를 발생시킨다. +// if (!jwtUtil.verifyToken(atc)) { +// throw new JwtException("Access Token 만료!"); +// } +// // AccessToken의 값이 있고, 유효한 경우에 진행한다. +// if (jwtUtil.verifyToken(atc)) { +// +// // AccessToken 내부의 payload에 있는 email로 user를 조회한다. 없다면 예외를 발생시킨다 -> 정상 케이스가 아님 +// Member findMember = memberRepository.findByEmail(jwtUtil.getUid(atc)) +// .orElseThrow(IllegalStateException::new); +// +// // SecurityContext에 등록할 User 객체를 만들어준다. +// SecurityUserDto userDto = SecurityUserDto.builder() +// .email(findMember.getEmail()) +// .role(findMember.getUserRole()) +// .nickname(findMember.getNickname()) +// .build(); +// +// // SecurityContext에 인증 객체를 등록해준다. +// Authentication auth = getAuthentication(userDto); +// SecurityContextHolder.getContext().setAuthentication(auth); +// } +// +// filterChain.doFilter(request, response); +// } +// +// +// public Authentication getAuthentication(SecurityUserDto member) { +// return new UsernamePasswordAuthenticationToken(member, "", +// List.of(new SimpleGrantedAuthority(member.getRole().getKey()))); +// } +// +// public static SecurityUserDto getUser() { +// return (SecurityUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/JwtExceptionFilter.java b/src/main/java/aromanticcat/umcproject/security/jwt/JwtExceptionFilter.java index d1f70f0..aa9ac84 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/JwtExceptionFilter.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/JwtExceptionFilter.java @@ -1,34 +1,34 @@ -package aromanticcat.umcproject.security.jwt; - -import aromanticcat.umcproject.apiPayload.code.status.ErrorStatus; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.jsonwebtoken.JwtException; -import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; - -@Component -@RequiredArgsConstructor -public class JwtExceptionFilter extends OncePerRequestFilter { - - private final ObjectMapper objectMapper; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { - try { - filterChain.doFilter(request, response); - } catch (JwtException e) { - response.setStatus(401); - response.setContentType(MediaType.APPLICATION_JSON_VALUE); - response.setCharacterEncoding("UTF-8"); - objectMapper.writeValue(response.getWriter(), ErrorStatus.MEMBER_NOT_FOUND); - } - } -} +//package aromanticcat.umcproject.security.jwt; +// +//import aromanticcat.umcproject.apiPayload.code.status.ErrorStatus; +//import com.fasterxml.jackson.databind.ObjectMapper; +//import io.jsonwebtoken.JwtException; +//import java.io.IOException; +//import javax.servlet.FilterChain; +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import lombok.RequiredArgsConstructor; +//import org.springframework.http.MediaType; +//import org.springframework.stereotype.Component; +//import org.springframework.web.filter.OncePerRequestFilter; +// +//@Component +//@RequiredArgsConstructor +//public class JwtExceptionFilter extends OncePerRequestFilter { +// +// private final ObjectMapper objectMapper; +// +// @Override +// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) +// throws ServletException, IOException { +// try { +// filterChain.doFilter(request, response); +// } catch (JwtException e) { +// response.setStatus(401); +// response.setContentType(MediaType.APPLICATION_JSON_VALUE); +// response.setCharacterEncoding("UTF-8"); +// objectMapper.writeValue(response.getWriter(), ErrorStatus.MEMBER_NOT_FOUND); +// } +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/JwtProperties.java b/src/main/java/aromanticcat/umcproject/security/jwt/JwtProperties.java index a7e620e..75bbc39 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/JwtProperties.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/JwtProperties.java @@ -1,12 +1,12 @@ -package aromanticcat.umcproject.security.jwt; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@Data -@Component -@ConfigurationProperties(prefix = "spring.jwt") -public class JwtProperties { - private String secret; -} +//package aromanticcat.umcproject.security.jwt; +// +//import lombok.Data; +//import org.springframework.boot.context.properties.ConfigurationProperties; +//import org.springframework.stereotype.Component; +// +//@Data +//@Component +//@ConfigurationProperties(prefix = "spring.jwt") +//public class JwtProperties { +// private String secret; +//} diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/JwtUtil.java b/src/main/java/aromanticcat/umcproject/security/jwt/JwtUtil.java index 01dfd1c..8ae6351 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/JwtUtil.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/JwtUtil.java @@ -1,114 +1,111 @@ -package aromanticcat.umcproject.security.jwt; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jws; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import java.util.Base64; -import java.util.Date; -import javax.annotation.PostConstruct; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; - -@Slf4j -@Service -@RequiredArgsConstructor -public class JwtUtil { - private final JwtProperties jwtProperties; - private final RefreshTokenService tokenService; - private String secretKey; - - @PostConstruct - protected void init() { - secretKey = Base64.getEncoder().encodeToString(jwtProperties.getSecret().getBytes()); - } - - - public GeneratedToken generateToken(String email, String role) { - // refreshToken과 accessToken을 생성한다. - String refreshToken = generateRefreshToken(email, role); - String accessToken = generateAccessToken(email, role); - log.info("Email: {}, AccessToken: {}, RefreshToken: {}", email, accessToken, refreshToken); - - // 토큰을 Redis에 저장한다. - tokenService.saveTokenInfo(email, refreshToken, accessToken); - - log.info("토큰 저장 성공"); - return new GeneratedToken(accessToken, refreshToken); - } - - public String generateRefreshToken(String email, String role) { - // 토큰의 유효 기간을 밀리초 단위로 설정. - long refreshPeriod = 1000L * 60L * 60L * 24L * 14; // 2주 - - // 새로운 클레임 객체를 생성하고, 이메일과 역할(권한)을 셋팅 - Claims claims = Jwts.claims().setSubject(email); - claims.put("role", role); - - // 현재 시간과 날짜를 가져온다. - Date now = new Date(); - - return Jwts.builder() - // Payload를 구성하는 속성들을 정의한다. - .setClaims(claims) - // 발행일자를 넣는다. - .setIssuedAt(now) - // 토큰의 만료일시를 설정한다. - .setExpiration(new Date(now.getTime() + refreshPeriod)) - // 지정된 서명 알고리즘과 비밀 키를 사용하여 토큰을 서명한다. - .signWith(SignatureAlgorithm.HS256, secretKey) - .compact(); - } - - public String generateAccessToken(String email, String role) { - long tokenPeriod = 1000L * 60L * 30L; // 30분 - //long tokenPeriod = 1000L * 2L; // 2초 - 테스트용 - Claims claims = Jwts.claims().setSubject(email); - claims.put("role", role); - - Date now = new Date(); - return - Jwts.builder() - // Payload를 구성하는 속성들을 정의한다. - .setClaims(claims) - // 발행일자를 넣는다. - .setIssuedAt(now) - // 토큰의 만료일시를 설정한다. - .setExpiration(new Date(now.getTime() + tokenPeriod)) - // 지정된 서명 알고리즘과 비밀 키를 사용하여 토큰을 서명한다. - .signWith(SignatureAlgorithm.HS256, secretKey) - .compact(); - - } - - - public boolean verifyToken(String token) { - try { - Jws claims = Jwts.parser() - .setSigningKey(secretKey) // 비밀키를 설정하여 파싱한다. - .parseClaimsJws(token); // 주어진 토큰을 파싱하여 Claims 객체를 얻는다. - // 토큰의 만료 시간과 현재 시간비교 - return claims.getBody() - .getExpiration() - .after(new Date()); // 만료 시간이 현재 시간 이후인지 확인하여 유효성 검사 결과를 반환 - } catch (Exception e) { - return false; - } - } - - // 토큰에서 Email을 추출한다. - public String getUid(String token) { - return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); - } - - // 토큰에서 ROLE(권한)만 추출한다. - public String getRole(String token) { - return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().get("role", String.class); - } - -} - - - - +//package aromanticcat.umcproject.security.jwt; +// +//import io.jsonwebtoken.Claims; +//import io.jsonwebtoken.Jws; +//import io.jsonwebtoken.Jwts; +//import io.jsonwebtoken.SignatureAlgorithm; +//import java.util.Base64; +//import java.util.Date; +//import javax.annotation.PostConstruct; +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.stereotype.Service; +// +//@Slf4j +//@Service +//@RequiredArgsConstructor +//public class JwtUtil { +// private final JwtProperties jwtProperties; +// private final RefreshTokenService tokenService; +// private String secretKey; +// +// @PostConstruct +// protected void init() { +// secretKey = Base64.getEncoder().encodeToString(jwtProperties.getSecret().getBytes()); +// } +// +// +// public GeneratedToken generateToken(String email, String role) { +// // refreshToken과 accessToken을 생성한다. +// String refreshToken = generateRefreshToken(email, role); +// String accessToken = generateAccessToken(email, role); +// log.info("Email: {}, AccessToken: {}, RefreshToken: {}", email, accessToken, refreshToken); +// +// // 토큰을 Redis에 저장한다. +// tokenService.saveTokenInfo(email, refreshToken, accessToken); +// +// log.info("토큰 저장 성공"); +// return new GeneratedToken(accessToken, refreshToken); +// } +// +// public String generateRefreshToken(String email, String role) { +// // 토큰의 유효 기간을 밀리초 단위로 설정. +// long refreshPeriod = 1000L * 60L * 60L * 24L * 14; // 2주 +// +// // 새로운 클레임 객체를 생성하고, 이메일과 역할(권한)을 셋팅 +// Claims claims = Jwts.claims().setSubject(email); +// claims.put("role", role); +// +// // 현재 시간과 날짜를 가져온다. +// Date now = new Date(); +// +// return Jwts.builder() +// // Payload를 구성하는 속성들을 정의한다. +// .setClaims(claims) +// // 발행일자를 넣는다. +// .setIssuedAt(now) +// // 토큰의 만료일시를 설정한다. +// .setExpiration(new Date(now.getTime() + refreshPeriod)) +// // 지정된 서명 알고리즘과 비밀 키를 사용하여 토큰을 서명한다. +// .signWith(SignatureAlgorithm.HS256, secretKey) +// .compact(); +// } +// +// public String generateAccessToken(String email, String role) { +// long tokenPeriod = 1000L * 60L * 30L; // 30분 +// //long tokenPeriod = 1000L * 2L; // 2초 - 테스트용 +// Claims claims = Jwts.claims().setSubject(email); +// claims.put("role", role); +// +// Date now = new Date(); +// return +// Jwts.builder() +// // Payload를 구성하는 속성들을 정의한다. +// .setClaims(claims) +// // 발행일자를 넣는다. +// .setIssuedAt(now) +// // 토큰의 만료일시를 설정한다. +// .setExpiration(new Date(now.getTime() + tokenPeriod)) +// // 지정된 서명 알고리즘과 비밀 키를 사용하여 토큰을 서명한다. +// .signWith(SignatureAlgorithm.HS256, secretKey) +// .compact(); +// +// } +// +// +// public boolean verifyToken(String token) { +// try { +// Jws claims = Jwts.parser() +// .setSigningKey(secretKey) // 비밀키를 설정하여 파싱한다. +// .parseClaimsJws(token); // 주어진 토큰을 파싱하여 Claims 객체를 얻는다. +// // 토큰의 만료 시간과 현재 시간비교 +// return claims.getBody() +// .getExpiration() +// .after(new Date()); // 만료 시간이 현재 시간 이후인지 확인하여 유효성 검사 결과를 반환 +// } catch (Exception e) { +// return false; +// } +// } +// +// // 토큰에서 Email을 추출한다. +// public String getUid(String token) { +// return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); +// } +// +// // 토큰에서 ROLE(권한)만 추출한다. +// public String getRole(String token) { +// return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().get("role", String.class); +// } +// +//} +// diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/RefreshToken.java b/src/main/java/aromanticcat/umcproject/security/jwt/RefreshToken.java index 99b83ad..516f471 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/RefreshToken.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/RefreshToken.java @@ -1,27 +1,27 @@ -package aromanticcat.umcproject.security.jwt; - -import java.io.Serializable; -import javax.persistence.Id; -import lombok.AllArgsConstructor; -import lombok.Getter; -import org.springframework.data.redis.core.RedisHash; -import org.springframework.data.redis.core.index.Indexed; - -@Getter -@AllArgsConstructor -@RedisHash(value = "jwtToken", timeToLive = 60 * 60 * 24 * 14) -public class RefreshToken implements Serializable { - - @Id - private String id; - - @Indexed - private String accessToken; - - private String refreshToken; - - public void updateAccessToken(String accessToken) { - this.accessToken = accessToken; - } - -} +//package aromanticcat.umcproject.security.jwt; +// +//import java.io.Serializable; +//import javax.persistence.Id; +//import lombok.AllArgsConstructor; +//import lombok.Getter; +//import org.springframework.data.redis.core.RedisHash; +//import org.springframework.data.redis.core.index.Indexed; +// +//@Getter +//@AllArgsConstructor +//@RedisHash(value = "jwtToken", timeToLive = 60 * 60 * 24 * 14) +//public class RefreshToken implements Serializable { +// +// @Id +// private String id; +// +// @Indexed +// private String accessToken; +// +// private String refreshToken; +// +// public void updateAccessToken(String accessToken) { +// this.accessToken = accessToken; +// } +// +//} diff --git a/src/main/java/aromanticcat/umcproject/security/jwt/RefreshTokenService.java b/src/main/java/aromanticcat/umcproject/security/jwt/RefreshTokenService.java index 0db6b34..97d5c57 100644 --- a/src/main/java/aromanticcat/umcproject/security/jwt/RefreshTokenService.java +++ b/src/main/java/aromanticcat/umcproject/security/jwt/RefreshTokenService.java @@ -1,26 +1,26 @@ -package aromanticcat.umcproject.security.jwt; - -import aromanticcat.umcproject.repository.RefreshTokenRepository; -import javax.transaction.Transactional; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -@Service -@RequiredArgsConstructor -public class RefreshTokenService { - - private final RefreshTokenRepository repository; - - @Transactional - public void saveTokenInfo(String email, String refreshToken, String accessToken) { - repository.save(new RefreshToken(email, accessToken, refreshToken)); - } - - @Transactional - public void removeRefreshToken(String accessToken) { - RefreshToken token = repository.findByAccessToken(accessToken) - .orElseThrow(IllegalArgumentException::new); - - repository.delete(token); - } -} +//package aromanticcat.umcproject.security.jwt; +// +//import aromanticcat.umcproject.repository.RefreshTokenRepository; +//import javax.transaction.Transactional; +//import lombok.RequiredArgsConstructor; +//import org.springframework.stereotype.Service; +// +//@Service +//@RequiredArgsConstructor +//public class RefreshTokenService { +// +// private final RefreshTokenRepository repository; +// +// @Transactional +// public void saveTokenInfo(String email, String refreshToken, String accessToken) { +// repository.save(new RefreshToken(email, accessToken, refreshToken)); +// } +// +// @Transactional +// public void removeRefreshToken(String accessToken) { +// RefreshToken token = repository.findByAccessToken(accessToken) +// .orElseThrow(IllegalArgumentException::new); +// +// repository.delete(token); +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/oauth/CustomOAuth2UserService.java b/src/main/java/aromanticcat/umcproject/security/oauth/CustomOAuth2UserService.java index 57e2e9f..fa2b8be 100644 --- a/src/main/java/aromanticcat/umcproject/security/oauth/CustomOAuth2UserService.java +++ b/src/main/java/aromanticcat/umcproject/security/oauth/CustomOAuth2UserService.java @@ -1,68 +1,68 @@ -package aromanticcat.umcproject.security.oauth; - -import aromanticcat.umcproject.entity.Member; -import aromanticcat.umcproject.service.MemberService; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -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; - -@Slf4j -@Service -@RequiredArgsConstructor -public class CustomOAuth2UserService implements OAuth2UserService { - - private final MemberService memberService; - - @Override - public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { - // 기본 OAuth2UserService 객체 생성 - OAuth2UserService oAuth2UserService = new DefaultOAuth2UserService(); - - // OAuth2UserService를 사용하여 OAuth2User 정보를 가져온다. - OAuth2User oAuth2User = oAuth2UserService.loadUser(userRequest); - - // 클라이언트 등록 ID(google, naver, kakao)와 사용자 이름 속성을 가져온다. - String registrationId = userRequest.getClientRegistration().getRegistrationId(); - String userNameAttributeName = userRequest.getClientRegistration() - .getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName(); - - // OAuth2UserService를 사용하여 가져온 OAuth2User 정보로 OAuth2Attribute 객체를 만든다. - OAuth2Attribute oAuth2Attribute = - OAuth2Attribute.of(registrationId, userNameAttributeName, oAuth2User.getAttributes()); - - // OAuth2Attribute의 속성값들을 Map으로 반환 받는다. - Map memberAttribute = oAuth2Attribute.convertToMap(); - - // 사용자 email(또는 id) 정보를 가져온다. - String email = (String) memberAttribute.get("email"); - // 이메일로 가입된 회원인지 조회한다. - Optional findMember = memberService.findByEmail(email); - - if (findMember.isEmpty()) { - // 회원이 존재하지 않을경우, memberAttribute의 exist 값을 false로 넣어준다. - memberAttribute.put("exist", false); - // 회원의 권한(회원이 존재하지 않으므로 기본권한인 ROLE_USER를 넣어준다), 회원속성, 속성이름을 이용해 DefaultOAuth2User 객체를 생성해 반환한다. - return new DefaultOAuth2User( - Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")), - memberAttribute, "email"); - } - - // 회원이 존재할경우, memberAttribute의 exist 값을 true로 넣어준다. - memberAttribute.put("exist", true); - // 회원의 권한과, 회원속성, 속성이름을 이용해 DefaultOAuth2User 객체를 생성해 반환한다. - return new DefaultOAuth2User( - Collections.singleton(new SimpleGrantedAuthority(findMember.get().getUserRole().getKey())), - memberAttribute, "email"); - - } -} +//package aromanticcat.umcproject.security.oauth; +// +//import aromanticcat.umcproject.entity.Member; +//import aromanticcat.umcproject.service.MemberService; +//import java.util.Collections; +//import java.util.Map; +//import java.util.Optional; +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.security.core.authority.SimpleGrantedAuthority; +//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; +// +//@Slf4j +//@Service +//@RequiredArgsConstructor +//public class CustomOAuth2UserService implements OAuth2UserService { +// +// private final MemberService memberService; +// +// @Override +// public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { +// // 기본 OAuth2UserService 객체 생성 +// OAuth2UserService oAuth2UserService = new DefaultOAuth2UserService(); +// +// // OAuth2UserService를 사용하여 OAuth2User 정보를 가져온다. +// OAuth2User oAuth2User = oAuth2UserService.loadUser(userRequest); +// +// // 클라이언트 등록 ID(google, naver, kakao)와 사용자 이름 속성을 가져온다. +// String registrationId = userRequest.getClientRegistration().getRegistrationId(); +// String userNameAttributeName = userRequest.getClientRegistration() +// .getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName(); +// +// // OAuth2UserService를 사용하여 가져온 OAuth2User 정보로 OAuth2Attribute 객체를 만든다. +// OAuth2Attribute oAuth2Attribute = +// OAuth2Attribute.of(registrationId, userNameAttributeName, oAuth2User.getAttributes()); +// +// // OAuth2Attribute의 속성값들을 Map으로 반환 받는다. +// Map memberAttribute = oAuth2Attribute.convertToMap(); +// +// // 사용자 email(또는 id) 정보를 가져온다. +// String email = (String) memberAttribute.get("email"); +// // 이메일로 가입된 회원인지 조회한다. +// Optional findMember = memberService.findByEmail(email); +// +// if (findMember.isEmpty()) { +// // 회원이 존재하지 않을경우, memberAttribute의 exist 값을 false로 넣어준다. +// memberAttribute.put("exist", false); +// // 회원의 권한(회원이 존재하지 않으므로 기본권한인 ROLE_USER를 넣어준다), 회원속성, 속성이름을 이용해 DefaultOAuth2User 객체를 생성해 반환한다. +// return new DefaultOAuth2User( +// Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")), +// memberAttribute, "email"); +// } +// +// // 회원이 존재할경우, memberAttribute의 exist 값을 true로 넣어준다. +// memberAttribute.put("exist", true); +// // 회원의 권한과, 회원속성, 속성이름을 이용해 DefaultOAuth2User 객체를 생성해 반환한다. +// return new DefaultOAuth2User( +// Collections.singleton(new SimpleGrantedAuthority(findMember.get().getUserRole().getKey())), +// memberAttribute, "email"); +// +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationFailureHandler.java b/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationFailureHandler.java index e528e8b..a3d08f2 100644 --- a/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationFailureHandler.java +++ b/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationFailureHandler.java @@ -1,22 +1,22 @@ -package aromanticcat.umcproject.security.oauth; - -import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.stereotype.Component; - -@Component -@Slf4j -public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler { - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, - AuthenticationException exception) throws IOException, ServletException { - // 인증 실패시 메인 페이지로 이동 - response.sendRedirect("http://localhost:3000/login"); - } - -} +//package aromanticcat.umcproject.security.oauth; +// +//import java.io.IOException; +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.security.core.AuthenticationException; +//import org.springframework.security.web.authentication.AuthenticationFailureHandler; +//import org.springframework.stereotype.Component; +// +//@Component +//@Slf4j +//public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler { +// @Override +// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, +// AuthenticationException exception) throws IOException, ServletException { +// // 인증 실패시 메인 페이지로 이동 +// response.sendRedirect("http://localhost:3000/login"); +// } +// +//} diff --git a/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationSuccessHandler.java b/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationSuccessHandler.java index 0f15cb8..f9beced 100644 --- a/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationSuccessHandler.java +++ b/src/main/java/aromanticcat/umcproject/security/oauth/MyAuthenticationSuccessHandler.java @@ -1,87 +1,87 @@ -package aromanticcat.umcproject.security.oauth; - -import aromanticcat.umcproject.security.jwt.GeneratedToken; -import aromanticcat.umcproject.security.jwt.JwtUtil; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.core.user.OAuth2User; -import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; -import org.springframework.stereotype.Component; -import org.springframework.web.util.UriComponentsBuilder; - -@Slf4j -@Component -@RequiredArgsConstructor -public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { - - private final JwtUtil jwtUtil; - - @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, - Authentication authentication) throws IOException, ServletException { - - // OAuth2User로 캐스팅하여 인증된 사용자 정보를 가져온다. - OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal(); - // 사용자 이메일을 가져온다. - String email = oAuth2User.getAttribute("email"); - // 서비스 제공 플랫폼(GOOGLE, KAKAO, NAVER)이 어디인지 가져온다. - String provider = oAuth2User.getAttribute("provider"); - - // CustomOAuth2UserService에서 셋팅한 로그인한 회원 존재 여부를 가져온다. - boolean isExist = oAuth2User.getAttribute("exist"); - // OAuth2User로 부터 Role을 얻어온다. - String role = oAuth2User.getAuthorities().stream(). - findFirst() // 첫번째 Role을 찾아온다. - .orElseThrow(IllegalAccessError::new) // 존재하지 않을 시 예외를 던진다. - .getAuthority(); // Role을 가져온다. - - // 회원이 존재할경우 - if (isExist) { - // 회원이 존재하면 jwt token 발행을 시작한다. - GeneratedToken token = jwtUtil.generateToken(email, role); - log.info("jwtToken = {}", token.getAccessToken()); - - // accessToken을 쿼리스트링에 담는 url을 만들어준다. - String targetUrl = UriComponentsBuilder.fromUriString("http://localhost:3000/") -// .queryParam("accessToken", token.getAccessToken()) - .build() - .encode(StandardCharsets.UTF_8) - .toUriString(); - // JWT 토큰을 Response Header에 설정 - response.addHeader("Authorization", token.getAccessToken()); - log.info("redirect 준비"); -// 사용자가 이전에 있던 페이지로 리다이렉트 시킨다. -// SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); +//package aromanticcat.umcproject.security.oauth; // -// if (savedRequest != null) { -// targetUrl = savedRequest.getRedirectUrl(); -// if (targetUrl.equals("http://localhost:8080/login")) { -// targetUrl = "http://localhost:8080/"; -// } -// } - - getRedirectStrategy().sendRedirect(request, response, targetUrl); - - - } else { - - // 회원이 존재하지 않을경우, 서비스 제공자와 email을 쿼리스트링으로 전달하는 url을 만들어준다. - String targetUrl = UriComponentsBuilder.fromUriString("http://localhost:3000/signUp") - .queryParam("email", (String) oAuth2User.getAttribute("email")) - .queryParam("provider", provider) - .build() - .encode(StandardCharsets.UTF_8) - .toUriString(); - log.info("redirect 준비"); - // 회원가입 페이지로 리다이렉트 시킨다. - getRedirectStrategy().sendRedirect(request, response, targetUrl); - } - } - -} +//import aromanticcat.umcproject.security.jwt.GeneratedToken; +//import aromanticcat.umcproject.security.jwt.JwtUtil; +//import java.io.IOException; +//import java.nio.charset.StandardCharsets; +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.security.core.Authentication; +//import org.springframework.security.oauth2.core.user.OAuth2User; +//import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +//import org.springframework.stereotype.Component; +//import org.springframework.web.util.UriComponentsBuilder; +// +//@Slf4j +//@Component +//@RequiredArgsConstructor +//public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { +// +// private final JwtUtil jwtUtil; +// +// @Override +// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, +// Authentication authentication) throws IOException, ServletException { +// +// // OAuth2User로 캐스팅하여 인증된 사용자 정보를 가져온다. +// OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal(); +// // 사용자 이메일을 가져온다. +// String email = oAuth2User.getAttribute("email"); +// // 서비스 제공 플랫폼(GOOGLE, KAKAO, NAVER)이 어디인지 가져온다. +// String provider = oAuth2User.getAttribute("provider"); +// +// // CustomOAuth2UserService에서 셋팅한 로그인한 회원 존재 여부를 가져온다. +// boolean isExist = oAuth2User.getAttribute("exist"); +// // OAuth2User로 부터 Role을 얻어온다. +// String role = oAuth2User.getAuthorities().stream(). +// findFirst() // 첫번째 Role을 찾아온다. +// .orElseThrow(IllegalAccessError::new) // 존재하지 않을 시 예외를 던진다. +// .getAuthority(); // Role을 가져온다. +// +// // 회원이 존재할경우 +// if (isExist) { +// // 회원이 존재하면 jwt token 발행을 시작한다. +// GeneratedToken token = jwtUtil.generateToken(email, role); +// log.info("jwtToken = {}", token.getAccessToken()); +// +// // accessToken을 쿼리스트링에 담는 url을 만들어준다. +// String targetUrl = UriComponentsBuilder.fromUriString("http://localhost:3000/") +//// .queryParam("accessToken", token.getAccessToken()) +// .build() +// .encode(StandardCharsets.UTF_8) +// .toUriString(); +// // JWT 토큰을 Response Header에 설정 +// response.addHeader("Authorization", token.getAccessToken()); +// log.info("redirect 준비"); +//// 사용자가 이전에 있던 페이지로 리다이렉트 시킨다. +//// SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); +//// +//// if (savedRequest != null) { +//// targetUrl = savedRequest.getRedirectUrl(); +//// if (targetUrl.equals("http://localhost:8080/login")) { +//// targetUrl = "http://localhost:8080/"; +//// } +//// } +// +// getRedirectStrategy().sendRedirect(request, response, targetUrl); +// +// +// } else { +// +// // 회원이 존재하지 않을경우, 서비스 제공자와 email을 쿼리스트링으로 전달하는 url을 만들어준다. +// String targetUrl = UriComponentsBuilder.fromUriString("http://localhost:3000/signUp") +// .queryParam("email", (String) oAuth2User.getAttribute("email")) +// .queryParam("provider", provider) +// .build() +// .encode(StandardCharsets.UTF_8) +// .toUriString(); +// log.info("redirect 준비"); +// // 회원가입 페이지로 리다이렉트 시킨다. +// getRedirectStrategy().sendRedirect(request, response, targetUrl); +// } +// } +// +//} diff --git a/src/main/java/aromanticcat/umcproject/security/oauth/OAuth2Attribute.java b/src/main/java/aromanticcat/umcproject/security/oauth/OAuth2Attribute.java index 19a2d4c..3a432bd 100644 --- a/src/main/java/aromanticcat/umcproject/security/oauth/OAuth2Attribute.java +++ b/src/main/java/aromanticcat/umcproject/security/oauth/OAuth2Attribute.java @@ -1,93 +1,93 @@ -package aromanticcat.umcproject.security.oauth; - -import lombok.AccessLevel; -import lombok.Builder; -import lombok.Getter; -import lombok.ToString; -import java.util.HashMap; -import java.util.Map; - -@ToString -@Builder(access = AccessLevel.PRIVATE) // Builder 메서드를 외부에서 사용하지 않으므로, Private 제어자로 지정 -@Getter -public class OAuth2Attribute { - private Map attributes; // 사용자 속성 정보를 담는 Map - private String attributeKey; // 사용자 속성의 키 값 - private String email; // 이메일 정보 - private String name; // 이름 정보 - private String provider; // 제공자 정보 - - // 서비스에 따라 OAuth2Attribute 객체를 생성하는 메서드 - static OAuth2Attribute of(String provider, String attributeKey, - Map attributes) { - switch (provider) { - case "google": - return ofGoogle(provider, attributeKey, attributes); - case "kakao": - return ofKakao(provider, "email", attributes); - case "naver": - return ofNaver(provider, "id", attributes); - default: - throw new RuntimeException(); - } - } - - /* - * Google 로그인일 경우 사용하는 메서드, 사용자 정보가 따로 Wrapping 되지 않고 제공되어, - * 바로 get() 메서드로 접근이 가능하다. - * */ - private static OAuth2Attribute ofGoogle(String provider, String attributeKey, - Map attributes) { - return OAuth2Attribute.builder() - .email((String) attributes.get("email")) - .provider(provider) - .attributes(attributes) - .attributeKey(attributeKey) - .build(); - } - - /* - * Kakao 로그인일 경우 사용하는 메서드, 필요한 사용자 정보가 kakaoAccount -> kakaoProfile 두번 감싸져 있어서, - * 두번 get() 메서드를 이용해 사용자 정보를 담고있는 Map을 꺼내야한다. - * */ - private static OAuth2Attribute ofKakao(String provider, String attributeKey, - Map attributes) { - Map kakaoAccount = (Map) attributes.get("kakao_account"); - Map kakaoProfile = (Map) kakaoAccount.get("profile"); - - return OAuth2Attribute.builder() - .email((String) kakaoAccount.get("email")) - .provider(provider) - .attributes(kakaoAccount) - .attributeKey(attributeKey) - .build(); - } - - /* - * Naver 로그인일 경우 사용하는 메서드, 필요한 사용자 정보가 response Map에 감싸져 있어서, - * 한번 get() 메서드를 이용해 사용자 정보를 담고있는 Map을 꺼내야한다. - * */ - private static OAuth2Attribute ofNaver(String provider, String attributeKey, - Map attributes) { - Map response = (Map) attributes.get("response"); - - return OAuth2Attribute.builder() - .email((String) response.get("email")) - .attributes(response) - .provider(provider) - .attributeKey(attributeKey) - .build(); - } - - - // OAuth2User 객체에 넣어주기 위해서 Map으로 값들을 반환해준다. - Map convertToMap() { - Map map = new HashMap<>(); - map.put("id", attributeKey); - map.put("key", attributeKey); - map.put("email", email); - map.put("provider", provider); - - return map; - } -} +//package aromanticcat.umcproject.security.oauth; +// +//import lombok.AccessLevel; +//import lombok.Builder; +//import lombok.Getter; +//import lombok.ToString; +//import java.util.HashMap; +//import java.util.Map; +// +//@ToString +//@Builder(access = AccessLevel.PRIVATE) // Builder 메서드를 외부에서 사용하지 않으므로, Private 제어자로 지정 +//@Getter +//public class OAuth2Attribute { +// private Map attributes; // 사용자 속성 정보를 담는 Map +// private String attributeKey; // 사용자 속성의 키 값 +// private String email; // 이메일 정보 +// private String name; // 이름 정보 +// private String provider; // 제공자 정보 +// +// // 서비스에 따라 OAuth2Attribute 객체를 생성하는 메서드 +// static OAuth2Attribute of(String provider, String attributeKey, +// Map attributes) { +// switch (provider) { +// case "google": +// return ofGoogle(provider, attributeKey, attributes); +// case "kakao": +// return ofKakao(provider, "email", attributes); +// case "naver": +// return ofNaver(provider, "id", attributes); +// default: +// throw new RuntimeException(); +// } +// } +// +// /* +// * Google 로그인일 경우 사용하는 메서드, 사용자 정보가 따로 Wrapping 되지 않고 제공되어, +// * 바로 get() 메서드로 접근이 가능하다. +// * */ +// private static OAuth2Attribute ofGoogle(String provider, String attributeKey, +// Map attributes) { +// return OAuth2Attribute.builder() +// .email((String) attributes.get("email")) +// .provider(provider) +// .attributes(attributes) +// .attributeKey(attributeKey) +// .build(); +// } +// +// /* +// * Kakao 로그인일 경우 사용하는 메서드, 필요한 사용자 정보가 kakaoAccount -> kakaoProfile 두번 감싸져 있어서, +// * 두번 get() 메서드를 이용해 사용자 정보를 담고있는 Map을 꺼내야한다. +// * */ +// private static OAuth2Attribute ofKakao(String provider, String attributeKey, +// Map attributes) { +// Map kakaoAccount = (Map) attributes.get("kakao_account"); +// Map kakaoProfile = (Map) kakaoAccount.get("profile"); +// +// return OAuth2Attribute.builder() +// .email((String) kakaoAccount.get("email")) +// .provider(provider) +// .attributes(kakaoAccount) +// .attributeKey(attributeKey) +// .build(); +// } +// +// /* +// * Naver 로그인일 경우 사용하는 메서드, 필요한 사용자 정보가 response Map에 감싸져 있어서, +// * 한번 get() 메서드를 이용해 사용자 정보를 담고있는 Map을 꺼내야한다. +// * */ +// private static OAuth2Attribute ofNaver(String provider, String attributeKey, +// Map attributes) { +// Map response = (Map) attributes.get("response"); +// +// return OAuth2Attribute.builder() +// .email((String) response.get("email")) +// .attributes(response) +// .provider(provider) +// .attributeKey(attributeKey) +// .build(); +// } +// +// +// // OAuth2User 객체에 넣어주기 위해서 Map으로 값들을 반환해준다. +// Map convertToMap() { +// Map map = new HashMap<>(); +// map.put("id", attributeKey); +// map.put("key", attributeKey); +// map.put("email", email); +// map.put("provider", provider); +// +// return map; +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/redis/RedisConfig.java b/src/main/java/aromanticcat/umcproject/security/redis/RedisConfig.java index 86458cb..6911ac5 100644 --- a/src/main/java/aromanticcat/umcproject/security/redis/RedisConfig.java +++ b/src/main/java/aromanticcat/umcproject/security/redis/RedisConfig.java @@ -1,40 +1,40 @@ -package aromanticcat.umcproject.security.redis; - -import lombok.RequiredArgsConstructor; -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.RedisStandaloneConfiguration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; - -@Configuration -@EnableRedisRepositories -@RequiredArgsConstructor -public class RedisConfig { - - private final RedisProperties redisProperties; - - @Bean - public RedisConnectionFactory redisConnectionFactory() { - RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); - redisStandaloneConfiguration.setHostName(redisProperties.getHost()); - redisStandaloneConfiguration.setPort(redisProperties.getPort()); - return new LettuceConnectionFactory(redisStandaloneConfiguration); - } - - @Bean - public RedisTemplate redisTemplate() { - - // redisTemplate 를 받아와서 set, get, delete 를 사용 - RedisTemplate redisTemplate = new RedisTemplate<>(); - /* - * setKeySerializer, setValueSerializer 설정 - * redis-cli 을 통해 직접 데이터를 조회 시 알아볼 수 없는 형태로 출력되는 것을 방지 - */ - redisTemplate.setConnectionFactory(redisConnectionFactory()); - - return redisTemplate; - } -} +//package aromanticcat.umcproject.security.redis; +// +//import lombok.RequiredArgsConstructor; +//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.RedisStandaloneConfiguration; +//import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +//import org.springframework.data.redis.core.RedisTemplate; +//import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; +// +//@Configuration +//@EnableRedisRepositories +//@RequiredArgsConstructor +//public class RedisConfig { +// +// private final RedisProperties redisProperties; +// +// @Bean +// public RedisConnectionFactory redisConnectionFactory() { +// RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); +// redisStandaloneConfiguration.setHostName(redisProperties.getHost()); +// redisStandaloneConfiguration.setPort(redisProperties.getPort()); +// return new LettuceConnectionFactory(redisStandaloneConfiguration); +// } +// +// @Bean +// public RedisTemplate redisTemplate() { +// +// // redisTemplate 를 받아와서 set, get, delete 를 사용 +// RedisTemplate redisTemplate = new RedisTemplate<>(); +// /* +// * setKeySerializer, setValueSerializer 설정 +// * redis-cli 을 통해 직접 데이터를 조회 시 알아볼 수 없는 형태로 출력되는 것을 방지 +// */ +// redisTemplate.setConnectionFactory(redisConnectionFactory()); +// +// return redisTemplate; +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/security/redis/RedisProperties.java b/src/main/java/aromanticcat/umcproject/security/redis/RedisProperties.java index 1f428c1..69a9e89 100644 --- a/src/main/java/aromanticcat/umcproject/security/redis/RedisProperties.java +++ b/src/main/java/aromanticcat/umcproject/security/redis/RedisProperties.java @@ -1,15 +1,15 @@ -package aromanticcat.umcproject.security.redis; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@Data -@Component -@ConfigurationProperties(prefix = "spring.redis") -public class RedisProperties { - - private String host; - private int port; - //private String password; -} +//package aromanticcat.umcproject.security.redis; +// +//import lombok.Data; +//import org.springframework.boot.context.properties.ConfigurationProperties; +//import org.springframework.stereotype.Component; +// +//@Data +//@Component +//@ConfigurationProperties(prefix = "spring.redis") +//public class RedisProperties { +// +// private String host; +// private int port; +// //private String password; +//} diff --git a/src/main/java/aromanticcat/umcproject/service/FriendService/FriendCommandServiceImpl.java b/src/main/java/aromanticcat/umcproject/service/FriendService/FriendCommandServiceImpl.java index 84cd1e7..60a8fb8 100644 --- a/src/main/java/aromanticcat/umcproject/service/FriendService/FriendCommandServiceImpl.java +++ b/src/main/java/aromanticcat/umcproject/service/FriendService/FriendCommandServiceImpl.java @@ -11,6 +11,8 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.List; + @Service @RequiredArgsConstructor @Transactional(readOnly = true) @@ -34,22 +36,41 @@ public void requestFriendship(String userEmail, Long toMemberId) { // 친구 요청을 받는 사용자 Member toMember = memberRepository.findById(toMemberId).orElse(null); - // 새로운 친구 객체 생성1 (fromMember 기준) - Friend newFriend1 = FriendConverter.toFriend(fromMember, toMember, true); - - // 새로운 친구 객체 생성2 (toMember 기준) - Friend newFriend2 = FriendConverter.toFriend(toMember, fromMember, false); - - // 각 사용자의 친구 리스트에 새로 만든 친구 객체 추가 - toMember.getFriends().add(newFriend1); - fromMember.getFriends().add(newFriend2); - - // 각 객체의 변경 사항을 db에 반영 - friendRepository.save(newFriend1); - friendRepository.save(newFriend2); - - newFriend1.setCounterpartId(newFriend2.getId()); - newFriend2.setCounterpartId(newFriend1.getId()); + // 이미 친구 추가를 보낸 적이 있는지 확인하기 위함 + List friendList = friendRepository.findFriendByMemberAndFriendId(fromMember, toMemberId); + + if(friendList == null){ // 이전에 친구 요청을 보낸 적이 없음 + // 새로운 친구 객체 생성1 (fromMember 기준) + Friend newFriend1 = FriendConverter.toFriend(fromMember, toMember, true); + + // 새로운 친구 객체 생성2 (toMember 기준) + Friend newFriend2 = FriendConverter.toFriend(toMember, fromMember, false); + + // 각 사용자의 친구 리스트에 새로 만든 친구 객체 추가 + toMember.getFriends().add(newFriend1); + fromMember.getFriends().add(newFriend2); + + // 각 객체의 변경 사항을 db에 반영 + friendRepository.save(newFriend1); + friendRepository.save(newFriend2); + + newFriend1.setCounterpartId(newFriend2.getId()); + newFriend2.setCounterpartId(newFriend1.getId()); + } else { // 친구 요청을 전에 보낸 적이 있음 + for(Friend friend : friendList){ + if(friend.getFriendStatus() == FriendStatus.APPROVED || friend.getFriendStatus() == FriendStatus.CLOSE_FRIEND){ // 이미 친구인 사용자 + throw new IllegalArgumentException("이미 친구인 사용자입니다. 친구 아이디: " + toMemberId); + } else if (friend.getFriendStatus() == FriendStatus.WAITING) { + throw new IllegalArgumentException("이미 친구 추가를 보낸 사용자입니다. 친구 아이디: " + toMemberId); // 이미 친구 추가를 보낸 사용자 + } else if (friend.getFriendStatus() == FriendStatus.REJECTED) { // 이전에 친구 추가를 보냈는데 거절이 된 경우 + friend.changeFriendStatus(FriendStatus.WAITING); + friend.changeIsFrom(true); + Friend counterpart = friendRepository.findById(friend.getCounterpartId()).orElse(null); + counterpart.changeFriendStatus(FriendStatus.WAITING); + counterpart.changeIsFrom(false); + } + } + } } @Override diff --git a/src/main/java/aromanticcat/umcproject/service/MemberService.java b/src/main/java/aromanticcat/umcproject/service/MemberService.java index 11b84f3..892e389 100644 --- a/src/main/java/aromanticcat/umcproject/service/MemberService.java +++ b/src/main/java/aromanticcat/umcproject/service/MemberService.java @@ -1,7 +1,7 @@ package aromanticcat.umcproject.service; import aromanticcat.umcproject.entity.Member; -import aromanticcat.umcproject.security.SecurityUserDto; +//import aromanticcat.umcproject.security.SecurityUserDto; import aromanticcat.umcproject.web.dto.Member.MemberRequestDTO; import aromanticcat.umcproject.web.dto.Member.MemberResponseDTO; @@ -12,16 +12,16 @@ public interface MemberService { Optional findByEmail(String email); - Member createUser(String email, String nickname); +// Member createUser(String email, String nickname); - void isNicknameExist(String nickname); +// void isNicknameExist(String nickname); - void isNicknameUnique(String nickname); +// void isNicknameUnique(String nickname); - SecurityUserDto getUserInfo(); +// SecurityUserDto getUserInfo(); - Member updateNickname(String nickname); +// Member updateNickname(String nickname); - Member findByMemberId(Long memberId); + Member findByMemberId(Long memberId, String userEmail); } diff --git a/src/main/java/aromanticcat/umcproject/service/MemberServiceImpl.java b/src/main/java/aromanticcat/umcproject/service/MemberServiceImpl.java index 911dc28..7a83f1a 100644 --- a/src/main/java/aromanticcat/umcproject/service/MemberServiceImpl.java +++ b/src/main/java/aromanticcat/umcproject/service/MemberServiceImpl.java @@ -2,15 +2,15 @@ import aromanticcat.umcproject.apiPayload.code.status.ErrorStatus; import aromanticcat.umcproject.apiPayload.exception.handler.MemberHandler; +import aromanticcat.umcproject.entity.FriendStatus; import aromanticcat.umcproject.entity.Member; +import aromanticcat.umcproject.repository.FriendRepository; import aromanticcat.umcproject.repository.MemberRepository; -import aromanticcat.umcproject.security.Role; -import aromanticcat.umcproject.security.SecurityUserDto; -import aromanticcat.umcproject.security.jwt.JwtAuthFilter; +//import aromanticcat.umcproject.security.Role; +//import aromanticcat.umcproject.security.SecurityUserDto; +//import aromanticcat.umcproject.security.jwt.JwtAuthFilter; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; +import java.util.*; import javax.transaction.Transactional; import aromanticcat.umcproject.web.dto.Member.MemberResponseDTO; @@ -22,72 +22,84 @@ @Transactional public class MemberServiceImpl implements MemberService { - private final MemberRepository repository; + private final FriendRepository friendRepository; @Override public Optional findByEmail(String email) { return repository.findByEmail(email); } - @Override - public Member createUser(String email, String nickname) { - isNicknameExist(nickname); - isNicknameUnique(nickname); - - Member newUser = Member.builder() - .email(email) - .nickname(nickname) - .userRole(Role.USER) - .build(); - - return repository.save(newUser); - } +// @Override +// public Member createUser(String email, String nickname) { +// isNicknameExist(nickname); +// isNicknameUnique(nickname); +// +// Member newUser = Member.builder() +// .email(email) +// .nickname(nickname) +// .userRole(Role.USER) +// .build(); +// +// return repository.save(newUser); +// } + +// @Override +// public void isNicknameExist(String nickname) { +// if (nickname.isEmpty()) { +// throw new MemberHandler(ErrorStatus.NICKNAME_NOT_EXIST); +// } +// } +// +// @Override +// public void isNicknameUnique(String nickname) { +// Optional existingMember = repository.findByNickname(nickname); +// if (existingMember.isPresent()) { +// throw new MemberHandler(ErrorStatus.NICKNAME_ALREADY_EXIST); +// } +// } + +// @Override +// public SecurityUserDto getUserInfo() { +// return JwtAuthFilter.getUser(); +// } + + +// @Override +// public Member updateNickname(String newNickname) { +// isNicknameExist(newNickname); +// isNicknameUnique(newNickname); +// +// //Security context로부터 user 정보 받아옴 +// Optional memberOptional = findByEmail(getUserInfo().getEmail()); +// if (memberOptional.isPresent()) { +// Member member = memberOptional.get(); +// // 닉네임 업데이트 +// member.setNickname(newNickname); +// // 변경된 멤버 저장 후 반환 +// return repository.save(member); +// } else { +// // 해당 이메일에 해당하는 회원이 없을 경우 +// throw new MemberHandler(ErrorStatus.MEMBER_NOT_FOUND); +// } +// } @Override - public void isNicknameExist(String nickname) { - if (nickname.isEmpty()) { - throw new MemberHandler(ErrorStatus.NICKNAME_NOT_EXIST); - } - } + public Member findByMemberId(Long findMemberId, String userEmail) { - @Override - public void isNicknameUnique(String nickname) { - Optional existingMember = repository.findByNickname(nickname); - if (existingMember.isPresent()) { - throw new MemberHandler(ErrorStatus.NICKNAME_ALREADY_EXIST); - } - } - - @Override - public SecurityUserDto getUserInfo() { - return JwtAuthFilter.getUser(); - } + Member member = findByEmail(userEmail).orElse(null); + // 이미 존재하는 친구인지를 확인하기 위함 + Set friendStatus = new HashSet<>(); + friendStatus.add(FriendStatus.APPROVED); + friendStatus.add(FriendStatus.CLOSE_FRIEND); + Boolean isFriend = friendRepository.existsByMemberAndFriendIdAndFriendStatus(member, findMemberId, friendStatus); - @Override - public Member updateNickname(String newNickname) { - isNicknameExist(newNickname); - isNicknameUnique(newNickname); - - //Security context로부터 user 정보 받아옴 - Optional memberOptional = findByEmail(getUserInfo().getEmail()); - if (memberOptional.isPresent()) { - Member member = memberOptional.get(); - // 닉네임 업데이트 - member.setNickname(newNickname); - // 변경된 멤버 저장 후 반환 - return repository.save(member); + if(isFriend){ // 이미 친구인 경우 예외 처리 + throw new IllegalArgumentException("이미 친구인 사용자입니다. 친구 아이디: " + findMemberId); } else { - // 해당 이메일에 해당하는 회원이 없을 경우 - throw new MemberHandler(ErrorStatus.MEMBER_NOT_FOUND); + return repository.findById(findMemberId).orElse(null); // 사용자가 검색하려는 멤버 ID } } - @Override - public Member findByMemberId(Long memberId) { - Member member = repository.findById(memberId).orElse(null); - return member; - } - } diff --git a/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandService.java b/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandService.java index 2f83d2c..56f1e45 100644 --- a/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandService.java +++ b/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandService.java @@ -5,5 +5,5 @@ public interface MissionCommandService { void stepCompleted(String userEmail, Long missionId); -// void resetDailyMissions(); + void resetDailyMissions(); } diff --git a/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandServiceImpl.java b/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandServiceImpl.java index 46017db..4db8874 100644 --- a/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandServiceImpl.java +++ b/src/main/java/aromanticcat/umcproject/service/MissionService/MissionCommandServiceImpl.java @@ -56,22 +56,22 @@ public void stepCompleted(String userEmail, Long missionId) { // 미션 안 } } -// @Override -// @Transactional -// @Scheduled(cron = "0 0 0 * * *") // 매일 자정에 실행되도록 설정 -// public void resetDailyMissions() { -// -// List memberMissions = memberMissionRepository.findAll(); -// -// for (MemberMission memberMission : memberMissions) { -// Mission mission = memberMission.getMission(); -// if (mission.isEveryday()) { -// memberMission.resetStep(); -// memberMission.setMissionStatus(MissionStatus.NOT_STARTED); -// // MemberMission 엔티티를 저장하여 변경 사항을 데이터베이스에 반영 -// memberMissionRepository.save(memberMission); -// } -// } -// } + @Override + @Transactional + @Scheduled(cron = "0 0 0 * * *") // 매일 자정에 실행되도록 설정 + public void resetDailyMissions() { + + List memberMissions = memberMissionRepository.findAll(); + + for (MemberMission memberMission : memberMissions) { + Mission mission = memberMission.getMission(); + if (mission.isEveryday()) { + memberMission.resetStep(); + memberMission.setMissionStatus(MissionStatus.NOT_STARTED); + // MemberMission 엔티티를 저장하여 변경 사항을 데이터베이스에 반영 + memberMissionRepository.save(memberMission); + } + } + } } diff --git a/src/main/java/aromanticcat/umcproject/web/controller/AuthController.java b/src/main/java/aromanticcat/umcproject/web/controller/AuthController.java index d0b2d91..f09d01e 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/AuthController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/AuthController.java @@ -1,78 +1,78 @@ -package aromanticcat.umcproject.web.controller; - -import aromanticcat.umcproject.apiPayload.ApiResponse; -import aromanticcat.umcproject.repository.RefreshTokenRepository; -import aromanticcat.umcproject.security.StatusResponseDto; -import aromanticcat.umcproject.security.jwt.JwtUtil; -import aromanticcat.umcproject.security.jwt.RefreshToken; -import aromanticcat.umcproject.security.jwt.RefreshTokenService; -import io.swagger.annotations.ApiOperation; -import java.util.Optional; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@Slf4j -@RestController -@RequiredArgsConstructor -@RequestMapping("/") -public class AuthController { - - private final RefreshTokenRepository tokenRepository; - private final RefreshTokenService tokenService; - private final JwtUtil jwtUtil; - - @PostMapping("/token/logout") - @ApiOperation(value = "로그아웃 API", notes = " 엑세스 토큰으로 현재 Redis 정보를 삭제하는 API입니다.") - public ApiResponse logout(@RequestHeader("Authorization") final String accessToken) { - - // 엑세스 토큰으로 현재 Redis 정보 삭제 - tokenService.removeRefreshToken(accessToken); - return ApiResponse.onSuccess(StatusResponseDto.addStatus(200)); - } - - @PostMapping("/token/refresh") - @ApiOperation(value = "액세스 토큰 재발급 API", notes = " 엑세스 토큰을 재발급하는 API입니다.") - public ResponseEntity refresh(@RequestHeader("Authorization") final String accessToken) { - - // 액세스 토큰으로 Refresh 토큰 객체를 조회 - Optional refreshToken = tokenRepository.findByAccessToken(accessToken); - - // RefreshToken이 존재하고 유효하다면 실행 - if (refreshToken.isPresent() && jwtUtil.verifyToken(refreshToken.get().getRefreshToken())) { - // RefreshToken 객체를 꺼내온다. - RefreshToken resultToken = refreshToken.get(); - // 권한과 아이디를 추출해 새로운 액세스토큰을 만든다. - String newAccessToken = jwtUtil.generateAccessToken(resultToken.getId(), - jwtUtil.getRole(resultToken.getRefreshToken())); - // 액세스 토큰의 값을 수정해준다. - resultToken.updateAccessToken(newAccessToken); - tokenRepository.save(resultToken); - // 새로운 액세스 토큰을 반환해준다. - return ResponseEntity.ok(TokenResponseStatus.addStatus(200, newAccessToken)); - } - - return ResponseEntity.badRequest().body(TokenResponseStatus.addStatus(400, null)); - } - - @Data - @AllArgsConstructor - static class TokenResponseStatus { - - private Integer code; - private String msg; - - public static TokenResponseStatus addStatus(Integer code, String msg) { - return new TokenResponseStatus(code, msg); - } - - - } - -} +//package aromanticcat.umcproject.web.controller; +// +//import aromanticcat.umcproject.apiPayload.ApiResponse; +//import aromanticcat.umcproject.repository.RefreshTokenRepository; +//import aromanticcat.umcproject.security.StatusResponseDto; +//import aromanticcat.umcproject.security.jwt.JwtUtil; +//import aromanticcat.umcproject.security.jwt.RefreshToken; +//import aromanticcat.umcproject.security.jwt.RefreshTokenService; +//import io.swagger.annotations.ApiOperation; +//import java.util.Optional; +//import lombok.AllArgsConstructor; +//import lombok.Data; +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.http.ResponseEntity; +//import org.springframework.web.bind.annotation.PostMapping; +//import org.springframework.web.bind.annotation.RequestHeader; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RestController; +// +//@Slf4j +//@RestController +//@RequiredArgsConstructor +//@RequestMapping("/") +//public class AuthController { +// +// private final RefreshTokenRepository tokenRepository; +// private final RefreshTokenService tokenService; +// private final JwtUtil jwtUtil; +// +// @PostMapping("/token/logout") +// @ApiOperation(value = "로그아웃 API", notes = " 엑세스 토큰으로 현재 Redis 정보를 삭제하는 API입니다.") +// public ApiResponse logout(@RequestHeader("Authorization") final String accessToken) { +// +// // 엑세스 토큰으로 현재 Redis 정보 삭제 +// tokenService.removeRefreshToken(accessToken); +// return ApiResponse.onSuccess(StatusResponseDto.addStatus(200)); +// } +// +// @PostMapping("/token/refresh") +// @ApiOperation(value = "액세스 토큰 재발급 API", notes = " 엑세스 토큰을 재발급하는 API입니다.") +// public ResponseEntity refresh(@RequestHeader("Authorization") final String accessToken) { +// +// // 액세스 토큰으로 Refresh 토큰 객체를 조회 +// Optional refreshToken = tokenRepository.findByAccessToken(accessToken); +// +// // RefreshToken이 존재하고 유효하다면 실행 +// if (refreshToken.isPresent() && jwtUtil.verifyToken(refreshToken.get().getRefreshToken())) { +// // RefreshToken 객체를 꺼내온다. +// RefreshToken resultToken = refreshToken.get(); +// // 권한과 아이디를 추출해 새로운 액세스토큰을 만든다. +// String newAccessToken = jwtUtil.generateAccessToken(resultToken.getId(), +// jwtUtil.getRole(resultToken.getRefreshToken())); +// // 액세스 토큰의 값을 수정해준다. +// resultToken.updateAccessToken(newAccessToken); +// tokenRepository.save(resultToken); +// // 새로운 액세스 토큰을 반환해준다. +// return ResponseEntity.ok(TokenResponseStatus.addStatus(200, newAccessToken)); +// } +// +// return ResponseEntity.badRequest().body(TokenResponseStatus.addStatus(400, null)); +// } +// +// @Data +// @AllArgsConstructor +// static class TokenResponseStatus { +// +// private Integer code; +// private String msg; +// +// public static TokenResponseStatus addStatus(Integer code, String msg) { +// return new TokenResponseStatus(code, msg); +// } +// +// +// } +// +//} diff --git a/src/main/java/aromanticcat/umcproject/web/controller/FriendController.java b/src/main/java/aromanticcat/umcproject/web/controller/FriendController.java index 77b11cb..ad19938 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/FriendController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/FriendController.java @@ -42,7 +42,8 @@ public ApiResponse> getFriendList( @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(defaultValue = "alphabetical") String sort) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 요청 받은 페이지의 친구 수를 가져옴 List friendDTOList = friendQueryService.findFriendList(userEmail, page, sort); @@ -66,7 +67,8 @@ public ApiResponse> getCloseFriendList( @RequestParam(defaultValue = "alphabetical") String sort) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 테스트용 // 요청 받은 페이지의 친구 수를 가져옴 List friendDTOList = friendQueryService.findCloseFriendList(userEmail, page, sort); @@ -87,7 +89,8 @@ public ApiResponse> getCloseFriendList( public ApiResponse> getFriendbyInfo( @RequestParam(value = "friend_info") String friendInfo) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; List friendInfoDTOList; // 검색하고자 하는 친구 정보와 관련된 DTO 선언 @@ -114,10 +117,12 @@ public ApiResponse> getFriendbyInfo( }) public ApiResponse getMemberbyId(@RequestParam(value = "member_info") String memberInfo) { try { +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; String memberIdString = memberInfo.substring(1); - Long memberId = Long.parseLong(memberIdString); // 친구 추가하려는 사용자 아이디 - Member member = memberService.findByMemberId(memberId); + Long findMemberId = Long.parseLong(memberIdString); // 친구 추가하려는 사용자 아이디 + Member member = memberService.findByMemberId(findMemberId, userEmail); MemberRequestDTO.searchMemberDTO memberDTO = MemberConverter.toSearchMemberDTO(member); @@ -136,7 +141,8 @@ public ApiResponse getMemberbyId(@RequestParam }) public ApiResponse sendFriendRequest(@RequestParam(value = "to_member_Id") Long toMemberId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친구 요청 보낸기 friendCommandService.requestFriendship(userEmail, toMemberId); @@ -153,7 +159,8 @@ public ApiResponse sendFriendRequest(@RequestParam(value = "to_member_Id @ApiOperation(value = "사용자가 친구 추가 받은 요청 조회 API") public ApiResponse> getReceivedFriendList() { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친구 요청을 보낸 사용자들의 목록 조회 List friendList = friendQueryService.getFriendReceivedList(userEmail); @@ -176,7 +183,8 @@ public ApiResponse> getReceivedFriendLi public ApiResponse> getRequestedFriendList() { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친구 요청을 보낸 사용자들의 목록 조회 List friendList = friendQueryService.getFriendRequestedList(userEmail); @@ -201,7 +209,8 @@ public ApiResponse> getRequestedFriendL }) public ApiResponse approveFriendRequest(@RequestParam(value = "friend_id") Long friendId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친구 요청 수락하기 friendCommandService.approveFriendship(userEmail, friendId); @@ -221,7 +230,8 @@ public ApiResponse approveFriendRequest(@RequestParam(value = "friend_id }) public ApiResponse rejectFriendRequest(@RequestParam(value = "friend_id") Long friendId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친구 요청 거절하기 friendCommandService.rejectFriendship(userEmail, friendId); @@ -241,7 +251,8 @@ public ApiResponse rejectFriendRequest(@RequestParam(value = "friend_id" }) public ApiResponse registerCloseFriend(@RequestParam(value = "friend_id") Long friendId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친한 친구로 등록하기 friendCommandService.setCloseFriend(userEmail, friendId); @@ -261,7 +272,8 @@ public ApiResponse registerCloseFriend(@RequestParam(value = "friend_id" }) public ApiResponse deleteCloseFriend(@RequestParam(value = "friend_id") Long friendId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 친한 친구 해제하기 friendCommandService.deleteCloseFriend(userEmail, friendId); diff --git a/src/main/java/aromanticcat/umcproject/web/controller/MemberController.java b/src/main/java/aromanticcat/umcproject/web/controller/MemberController.java index 66cdf3c..783416c 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/MemberController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/MemberController.java @@ -1,46 +1,46 @@ -package aromanticcat.umcproject.web.controller; - -import aromanticcat.umcproject.apiPayload.ApiResponse; -import aromanticcat.umcproject.converter.MemberConverter; -import aromanticcat.umcproject.entity.Member; -import aromanticcat.umcproject.service.MemberService; -import aromanticcat.umcproject.web.dto.Member.MemberResponseDTO; -import io.swagger.annotations.ApiOperation; -import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequiredArgsConstructor -public class MemberController { - - private final MemberService service; - - @PostMapping("/signUp") - @ApiOperation(value = "회원가입 API", notes = "회원가입 API입니다.") - public ApiResponse signup(@RequestBody String nickname, - @RequestParam String email) { - try { - Member user = service.createUser(email, nickname); - - return ApiResponse.onSuccess(MemberConverter.toMemberDTO(user)); - } catch (Exception e) { - return ApiResponse.onFailure(HttpStatus.INTERNAL_SERVER_ERROR.toString(), e.getMessage(), null); - } - } - - @PostMapping("/mypage/nickname") - @ApiOperation(value = "닉네임 변경 API", notes = "닉네임 변경 API입니다.") - public ApiResponse updateNickname(@RequestBody String nickname) { - try { - Member user = service.updateNickname(nickname); - - return ApiResponse.onSuccess(MemberConverter.toMemberDTO(user)); - } catch (Exception e) { - return ApiResponse.onFailure(HttpStatus.INTERNAL_SERVER_ERROR.toString(), e.getMessage(), null); - } - } -} +//package aromanticcat.umcproject.web.controller; +// +//import aromanticcat.umcproject.apiPayload.ApiResponse; +//import aromanticcat.umcproject.converter.MemberConverter; +//import aromanticcat.umcproject.entity.Member; +//import aromanticcat.umcproject.service.MemberService; +//import aromanticcat.umcproject.web.dto.Member.MemberResponseDTO; +//import io.swagger.annotations.ApiOperation; +//import lombok.RequiredArgsConstructor; +//import org.springframework.http.HttpStatus; +//import org.springframework.web.bind.annotation.PostMapping; +//import org.springframework.web.bind.annotation.RequestBody; +//import org.springframework.web.bind.annotation.RequestParam; +//import org.springframework.web.bind.annotation.RestController; +// +//@RestController +//@RequiredArgsConstructor +//public class MemberController { +// +// private final MemberService service; +// +// @PostMapping("/signUp") +// @ApiOperation(value = "회원가입 API", notes = "회원가입 API입니다.") +// public ApiResponse signup(@RequestBody String nickname, +// @RequestParam String email) { +// try { +// Member user = service.createUser(email, nickname); +// +// return ApiResponse.onSuccess(MemberConverter.toMemberDTO(user)); +// } catch (Exception e) { +// return ApiResponse.onFailure(HttpStatus.INTERNAL_SERVER_ERROR.toString(), e.getMessage(), null); +// } +// } +// +// @PostMapping("/mypage/nickname") +// @ApiOperation(value = "닉네임 변경 API", notes = "닉네임 변경 API입니다.") +// public ApiResponse updateNickname(@RequestBody String nickname) { +// try { +// Member user = service.updateNickname(nickname); +// +// return ApiResponse.onSuccess(MemberConverter.toMemberDTO(user)); +// } catch (Exception e) { +// return ApiResponse.onFailure(HttpStatus.INTERNAL_SERVER_ERROR.toString(), e.getMessage(), null); +// } +// } +//} diff --git a/src/main/java/aromanticcat/umcproject/web/controller/MissionController.java b/src/main/java/aromanticcat/umcproject/web/controller/MissionController.java index 56bfd8c..50adc4c 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/MissionController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/MissionController.java @@ -29,7 +29,8 @@ public class MissionController { @Operation(summary = "미션 목록 조회 API", description = "모든 미션을 조회합니다.") public ApiResponse> getAllMissions() { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 모든 미션 가져오기 List MissionList = missionQueryService.findMissionList(userEmail); @@ -61,7 +62,8 @@ public ApiResponse MissionDetails(@PathVar @Operation(summary = "미션 한 단계 완료 API", description = "특정 미션의 한 스텝이 완료된 것을 적용합니다. 미션의 모든 단계가 완료 되었으면 보상으로 코인이 주어집니다.") public ApiResponse MissionStepCompleted(@PathVariable Long missionId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; missionCommandService.stepCompleted(userEmail, missionId); diff --git a/src/main/java/aromanticcat/umcproject/web/controller/MyCollectionController.java b/src/main/java/aromanticcat/umcproject/web/controller/MyCollectionController.java index 3abde0c..941d9e4 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/MyCollectionController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/MyCollectionController.java @@ -31,7 +31,8 @@ public ApiResponse> g @RequestParam(defaultValue = "12") int pageSize, @RequestParam(defaultValue = "false") boolean onlyMyDesign) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 Page letterPaperPage = myCollectionService.findLetterPaperList( userEmail, page, pageSize, onlyMyDesign); @@ -51,7 +52,8 @@ public ApiResponse> getMySt @RequestParam(defaultValue = "12") int pageSize, @RequestParam(defaultValue = "false") boolean onlyMyDesign) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 Page stampPage = myCollectionService.findStampList( userEmail, page, pageSize, onlyMyDesign); diff --git a/src/main/java/aromanticcat/umcproject/web/controller/NangmanCollectionController.java b/src/main/java/aromanticcat/umcproject/web/controller/NangmanCollectionController.java index ff9d27a..2b763ff 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/NangmanCollectionController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/NangmanCollectionController.java @@ -82,7 +82,9 @@ public ApiResponse userLetterPage = nangmanCollectionService.getMyLetterPage( @@ -107,7 +109,8 @@ public ApiResponse userReplyPage = nangmanCollectionService.getMyReplyPage( diff --git a/src/main/java/aromanticcat/umcproject/web/controller/NangmanLetterboxController.java b/src/main/java/aromanticcat/umcproject/web/controller/NangmanLetterboxController.java index c1f5450..e56e2dd 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/NangmanLetterboxController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/NangmanLetterboxController.java @@ -44,7 +44,8 @@ public ApiResponse getRandomNickname() { public ApiResponse sendLetter( @RequestBody NangmanLetterboxRequestDTO.SendLetterDTO request) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 //편지 작성 및 발송 NangmanLetter nangmanLetter = nangmanLetterBoxService.sendLetter(userEmail, request); @@ -68,7 +69,8 @@ public ApiResponse> getLetterList( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "9") int pageSize) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 //편지 페이지의 편지 목록 조회 Page letterList = nangmanLetterBoxService.getLetterPage(userEmail, page, pageSize); @@ -108,7 +110,8 @@ public ApiResponse getNangm public ApiResponse sendReply(@PathVariable Long nangmanLetterId, @RequestBody NangmanLetterboxRequestDTO.SendReplyDTO request) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 NangmanLetterBoxResponseDTO.SendReplyResultDTO replyResultDTO = nangmanLetterBoxService.sendReply(userEmail, request, nangmanLetterId); diff --git a/src/main/java/aromanticcat/umcproject/web/controller/StoreController.java b/src/main/java/aromanticcat/umcproject/web/controller/StoreController.java index 651316e..1ba5c09 100644 --- a/src/main/java/aromanticcat/umcproject/web/controller/StoreController.java +++ b/src/main/java/aromanticcat/umcproject/web/controller/StoreController.java @@ -23,7 +23,8 @@ public class StoreController { @ApiOperation(value = "사용자 코인 조회 API") public ApiResponse getUserCoin(){ try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 Integer userCoin = storeService.findUserCoin(userEmail); @@ -43,7 +44,8 @@ public ApiResponse> getAllLetterPape @RequestParam(defaultValue = "16") int pageSize, @RequestParam(defaultValue = "latest") String sort) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 Page letterPaperPage = storeService.findLetterPaperList(userEmail, page, pageSize, sort); @@ -64,7 +66,8 @@ public ApiResponse> getAllStampList( @RequestParam(defaultValue = "15") int pageSize, @RequestParam(defaultValue = "latest") String sort) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 Page stampPage = storeService.findStampList(userEmail, page, pageSize, sort); @@ -78,7 +81,8 @@ public ApiResponse> getAllStampList( @ApiOperation(value = "편지지 구매 API") public ApiResponse purchasedLetterPaper(@PathVariable Long letterPaperId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 storeService.purchasedLetterPaper(userEmail, letterPaperId); @@ -94,7 +98,8 @@ public ApiResponse purchasedLetterPaper(@PathVariable Long letterPaperId @ApiOperation(value = "우표 구매 API") public ApiResponse purchasedStamp(@PathVariable Long stampId) { try { - String userEmail = memberService.getUserInfo().getEmail(); +// String userEmail = memberService.getUserInfo().getEmail(); + String userEmail = "testFront@gmail.com"; // 로그인 구현 전 임시 이메일 storeService.purchasedStamp(userEmail, stampId); diff --git a/src/main/java/aromanticcat/umcproject/web/dto/Member/MemberRequestDTO.java b/src/main/java/aromanticcat/umcproject/web/dto/Member/MemberRequestDTO.java index eac364e..41877a9 100644 --- a/src/main/java/aromanticcat/umcproject/web/dto/Member/MemberRequestDTO.java +++ b/src/main/java/aromanticcat/umcproject/web/dto/Member/MemberRequestDTO.java @@ -1,5 +1,6 @@ package aromanticcat.umcproject.web.dto.Member; +import aromanticcat.umcproject.entity.FriendStatus; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -14,5 +15,6 @@ public class MemberRequestDTO { public static class searchMemberDTO{ // 친구 추가에서 사용자 찾기에 사용되는 DTO String nickname; // 사용자 닉네임 Long memberId; // 사용자 우편함 번호 + FriendStatus friendStatus; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 441ff9d..3f16840 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -17,37 +17,37 @@ spring: hbm2ddl: auto: update default_batch_fetch_size: 1000 - redis: - host: ${REDIS_HOST} - port: ${REDIS_PORT} +# redis: +# host: ${REDIS_HOST} +# port: ${REDIS_PORT} mvc: pathmatch: matching-strategy: ant_path_matcher - security: - oauth2: - client: - registration: - google: - client-id: ${GOOGLE_ID} - client-secret: ${GOOGLE_SECRET} - redirect-uri: "https://dev.nangmancat.shop/login/oauth2/code/google" - authorization-grant-type: authorization_code - scope: email - kakao: - client-id: ${KAKAO_ID} - redirect-uri: "https://dev.nangmancat.shop/login/oauth2/code/kakao" - client-authentication-method: POST - authorization-grant-type: authorization_code - scope: profile_nickname, account_email - provider: - kakao: - authorization_uri: https://kauth.kakao.com/oauth/authorize - token_uri: https://kauth.kakao.com/oauth/token - user-info-uri: https://kapi.kakao.com/v2/user/me - user_name_attribute: id - jwt: - secret: ${TOKEN_SECRET} +# security: +# oauth2: +# client: +# registration: +# google: +# client-id: ${GOOGLE_ID} +# client-secret: ${GOOGLE_SECRET} +# redirect-uri: "https://dev.nangmancat.shop/login/oauth2/code/google" +# authorization-grant-type: authorization_code +# scope: email +# kakao: +# client-id: ${KAKAO_ID} +# redirect-uri: "https://dev.nangmancat.shop/login/oauth2/code/kakao" +# client-authentication-method: POST +# authorization-grant-type: authorization_code +# scope: profile_nickname, account_email +# provider: +# kakao: +# authorization_uri: https://kauth.kakao.com/oauth/authorize +# token_uri: https://kauth.kakao.com/oauth/token +# user-info-uri: https://kapi.kakao.com/v2/user/me +# user_name_attribute: id +# jwt: +# secret: ${TOKEN_SECRET} cloud: