Skip to content

Commit

Permalink
Merge pull request #70 from cosmos-1885/feature/1-branch-account
Browse files Browse the repository at this point in the history
refactor: User 기능 수정
  • Loading branch information
comom87 authored Nov 6, 2023
2 parents bf964f4 + e9a5f2f commit cae7968
Show file tree
Hide file tree
Showing 27 changed files with 491 additions and 197 deletions.
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ dependencies {
implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5'

// LocalDate 직렬화 및 역직렬화
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
implementation 'com.fasterxml.jackson.core:jackson-databind'

implementation 'org.springframework.boot:spring-boot-devtools'

Expand Down
34 changes: 9 additions & 25 deletions src/main/java/com/example/demo/config/jwt/JWTTokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import com.example.demo.refreshToken.RefreshToken;
import com.example.demo.refreshToken.RefreshTokenJPARepository;
import com.example.demo.refreshToken.TokenResponse;
import com.example.demo.user.userInterest.UserInterest;
import com.example.demo.user.userInterest.UserInterestJPARepository;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
import lombok.RequiredArgsConstructor;
Expand All @@ -15,6 +17,7 @@
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
Expand All @@ -26,18 +29,17 @@ public class JWTTokenProvider {

public static final String SecretKey = "a2FrYW8tdGVjaC1jYW1wdXMtcHJvamVjdC1nYXJkZW4tc3ByaW5nLXNlY3VyaXR5LWp3dC10b2tlbi1zZWNyZXQta2V5";
public static final int AccessTokenValidTime = 1000 * 60 * 5; // 5분
public static final int RefreshTokenValidTime = 1000 * 60 * 60 * 24; // 1일
public static final int RefreshTokenValidTime = 1000 * 60 * 60 * 24 * 7; // 1주일

private final CustomUserDetailService userDetailService;
private final RefreshTokenJPARepository refreshTokenJPARepository;

public static TokenResponse.TokenDTO createToken(User user) {
String accessToken = createAccessToken(user);
public static TokenResponse.TokenDTO createToken(User user, List<String> userCategoryList) {
String accessToken = createAccessToken(user, userCategoryList);
String refreshToken = createRefreshToken(user);
return new TokenResponse.TokenDTO(accessToken, refreshToken);
}

public static String createAccessToken(User user) {
public static String createAccessToken(User user, List<String> userCategoryList) {
String accessToken = Jwts.builder()
.setSubject(user.getEmail())
.claim("id", user.getId())
Expand All @@ -46,10 +48,11 @@ public static String createAccessToken(User user) {
.claim("email", user.getEmail())
.claim("country", user.getCountry())
.claim("introduction", user.getIntroduction())
.claim("age", user.getAge())
.claim("birthDate", user.getBirthDate().toString())
.claim("phone", user.getPhone())
.claim("profileImage", user.getProfileImage())
.claim("role", user.getRole())
.claim("categoryList", userCategoryList)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + AccessTokenValidTime))
.signWith(SignatureAlgorithm.HS512, SecretKey)
Expand Down Expand Up @@ -106,23 +109,4 @@ public static boolean validateToken(String token) {
}
return false;
}

// public static boolean validateRefreshToken(String token) {
// try {
// Jwts.parserBuilder()
// .setSigningKey(SecretKey)
// .build()
// .parseClaimsJws(token);
// return true;
// } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
// System.out.println("Invalid JWT Token");
// } catch (ExpiredJwtException e) {
// System.out.println("Expired JWT Token");
// } catch (UnsupportedJwtException e) {
// System.out.println("Unsupported JWT Token");
// } catch (IllegalArgumentException e) {
// System.out.println("JWT claims string is empty.");
// }
// return false;
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws

// 11. 인증, 권한 필터 설정
httpSecurity.authorizeRequests(
authorize -> authorize
authorize -> authorize.antMatchers("/profiles", "/users/passwordcheck").authenticated()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.anyRequest().permitAll()
);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/example/demo/interest/Interest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name = "interests")
public class Interest extends BaseTime {
public class Interest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -130,7 +131,7 @@ public static class MenteeDTO{
private String name;
private String country;
private Role role;
private int age;
private LocalDate birthDate;
private ContactStateEnum state;
private List<String> interests;

Expand All @@ -140,7 +141,7 @@ public MenteeDTO(NotConnectedRegisterUser notConnectedRegisterUser, List<UserInt
this.name = notConnectedRegisterUser.getMenteeUser().getFirstName() + " " + notConnectedRegisterUser.getMenteeUser().getLastName();
this.country = notConnectedRegisterUser.getMenteeUser().getCountry();
this.role = notConnectedRegisterUser.getMenteeUser().getRole();
this.age = notConnectedRegisterUser.getMenteeUser().getAge();
this.birthDate = notConnectedRegisterUser.getMenteeUser().getBirthDate();
this.state = notConnectedRegisterUser.getState();
this.interests = userInterests.stream()
.map(userInterest -> userInterest.getInterest().getCategory())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.example.demo.config.auth.CustomUserDetails;
import com.example.demo.config.utils.ApiResponseBuilder;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -18,43 +19,46 @@ public class MentorPostRestController {
private final MentorPostService mentorPostService;

@PostMapping(value = "/mentorings/post")
@Operation(summary = "mentorpost 생성")
public ResponseEntity<?> createMentorPost(@RequestBody @Valid MentorPostRequest.CreateDTO requestDTO, Errors errors, @AuthenticationPrincipal CustomUserDetails userDetails) {
mentorPostService.createMentorPost(requestDTO, userDetails.getUser());
return ResponseEntity.status(HttpStatus.OK).body(ApiResponseBuilder.successWithNoContent());
}

@GetMapping("/mentorings/post")
@Operation(summary = "mentorpost 가져오기", description = "category, search로 필터링, pagination 적용")
public ResponseEntity<?> getMentorPost(
@RequestParam(value = "category", required = false) MentorPostCategoryEnum category,
@RequestParam(value = "category", defaultValue = "NULL") String category,
@RequestParam(value = "search", defaultValue = "") String keyword,
@RequestParam(value = "page", defaultValue = "0") Integer page) {

if(category == null)
category = MentorPostCategoryEnum.NULL;

List<MentorPostResponse.MentorPostAllDTO> responseDTOs = mentorPostService.findAllMentorPost(category, keyword, page);
return ResponseEntity.ok(ApiResponseBuilder.success(responseDTOs));
}

@GetMapping("/mentorings/post/{id}")
@Operation(summary = "mentorpost 개별 페이지 불러오기")
public ResponseEntity<?> getMentorPostId(@PathVariable int id) {
MentorPostResponse.MentorPostDTO responseDTO = mentorPostService.findMentorPost(id);
return ResponseEntity.ok(ApiResponseBuilder.success(responseDTO));
}

@PutMapping(value = "/mentorings/post/{id}")
@Operation(summary = "mentorpost 수정 요청")
public ResponseEntity<?> updateMentorPost(@PathVariable int id, @RequestBody @Valid MentorPostRequest.CreateDTO requestDTO, Errors errors, @AuthenticationPrincipal CustomUserDetails userDetails) {
mentorPostService.updateMentorPost(requestDTO, id, userDetails.getUser());
return ResponseEntity.status(HttpStatus.OK).body(ApiResponseBuilder.successWithNoContent());
}

@DeleteMapping(value = "/mentorings/post/{id}")
@Operation(summary = "mentorpost 삭제 요청")
public ResponseEntity<?> deleteMentorPost(@PathVariable int id, @AuthenticationPrincipal CustomUserDetails userDetails) {
mentorPostService.deleteMentorPost(id, userDetails.getUser());
return ResponseEntity.status(HttpStatus.OK).body(ApiResponseBuilder.successWithNoContent());
}

@PatchMapping(value = "/mentorings/post/{id}/done")
@Operation(summary = "mentorpost 만료 요청")
public ResponseEntity<?> changeMentorPostStatus(@PathVariable int id,@RequestBody @Valid MentorPostRequest.StateDTO requestDTO, Errors errors, @AuthenticationPrincipal CustomUserDetails userDetails) {
mentorPostService.changeMentorPostStatus(requestDTO, id, userDetails.getUser());
return ResponseEntity.status(HttpStatus.OK).body(ApiResponseBuilder.successWithNoContent());
Expand Down
48 changes: 9 additions & 39 deletions src/main/java/com/example/demo/mentoring/MentorPostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@Transactional
Expand Down Expand Up @@ -51,45 +52,18 @@ public void createMentorPost(MentorPostRequest.CreateDTO createDTO, User writer)
/* 1. mentorPostList를 조회
2. 각 List당 writer별 writerInterests를 조회
3. MentorPostDTO 생성*/
public List<MentorPostResponse.MentorPostAllDTO> findAllMentorPost(MentorPostCategoryEnum searchCategory, String keyword, int page) {
public List<MentorPostResponse.MentorPostAllDTO> findAllMentorPost(String search, String keyword, int page) {
Pageable pageable = PageRequest.of(page,5);
Page<MentorPost> pageContent = null;

//검색별 pageContent 검색
if(searchCategory == MentorPostCategoryEnum.NULL)
{
pageContent = mentorPostJPARepository.findAll(pageable);
}
else if(searchCategory == MentorPostCategoryEnum.TITLE)
{
pageContent = mentorPostJPARepository.findAllByTitleKeyword("%" + keyword + "%", pageable);
}
else if(searchCategory == MentorPostCategoryEnum.WRITER)
{
pageContent = mentorPostJPARepository.findAllByWriterKeyword("%" + keyword + "%", pageable);
}
else if(searchCategory == MentorPostCategoryEnum.INTEREST)
{
pageContent = mentorPostJPARepository.findAllByInterestKeyword("%" + keyword + "%", pageable);
}
else
{
throw new Exception404("검색 분류가 잘못되었습니다.");
}

MentorSearchCategory mentorSearchCategory = MentorSearchCategory.valueOf(search.toUpperCase(Locale.ROOT));

if(pageContent.getTotalPages() == 0){
throw new Exception404("해당 글들이 존재하지 않습니다");
}
Page<MentorPost> result = mentorSearchCategory.execute(keyword, pageable, mentorPostJPARepository);
List<MentorPostResponse.MentorPostAllDTO> mentorPostAllDTOS = result.stream().map(mentorPost -> {
List<UserInterest> writerInterests = userInterestJPARepository.findAllById(mentorPost.getWriter().getId());
return new MentorPostResponse.MentorPostAllDTO(mentorPost, writerInterests);
}).collect(Collectors.toList());

//List<MentorPost> mentorPostList = mentorPostJPARepostiory.findAll();
List<MentorPostResponse.MentorPostAllDTO> mentorPostDTOList = pageContent.getContent().stream().map(
mentorPost -> {
List<UserInterest> writerInterests = userInterestJPARepository.findAllById(mentorPost.getWriter().getId());
return new MentorPostResponse.MentorPostAllDTO(mentorPost,writerInterests);
}
).collect(Collectors.toList());
return mentorPostDTOList;
return mentorPostAllDTOS;
}

public MentorPostResponse.MentorPostDTO findMentorPost(int id){
Expand Down Expand Up @@ -149,10 +123,6 @@ public List<MentorPostResponse.MentorPostAllWithTimeStampDTO> findAllMentorPostW
List<MentorPostResponse.MentorPostAllWithTimeStampDTO> mentorPostDTOList = pageContent.stream().map(
mentorPost -> {
List<UserInterest> writerInterests = userInterestJPARepository.findAllById(mentorPost.getWriter().getId());
if(writerInterests.isEmpty()){
throw new Exception404("해당 카테고리는 존재하지 않습니다");
}

return new MentorPostResponse.MentorPostAllWithTimeStampDTO(mentorPost,writerInterests);
}
).collect(Collectors.toList());
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/com/example/demo/mentoring/MentorSearchCategory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.demo.mentoring;

import lombok.Getter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@Getter
public enum MentorSearchCategory {
NULL((keyword, pageable, repo) -> repo.findAll(pageable)),
TITLE((keyword, pageable, repo) -> repo.findAllByTitleKeyword("%" + keyword + "%", pageable)),
WRITER((keyword, pageable, repo) -> repo.findAllByWriterKeyword("%" + keyword + "%", pageable)),
INTEREST((keyword, pageable, repo) -> repo.findAllByInterestKeyword("%" + keyword + "%", pageable));

private final TriFunction<String, Pageable, MentorPostJPARepostiory, Page<MentorPost>> function;

MentorSearchCategory(TriFunction<String, Pageable, MentorPostJPARepostiory, Page<MentorPost>> function) {
this.function = function;
}

public Page<MentorPost> execute(String keyword, Pageable pageable, MentorPostJPARepostiory repository) {
return function.apply(keyword, pageable, repository);
}
}
6 changes: 6 additions & 0 deletions src/main/java/com/example/demo/mentoring/TriFunction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.demo.mentoring;

@FunctionalInterface
public interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -67,7 +68,7 @@ public static class ContactMentorDTO {
private String profileImage;
private String name;
private String country;
private int age;
private LocalDate birthDate;
private Role role;
private List<String> favorites;

Expand All @@ -76,7 +77,7 @@ public ContactMentorDTO(User mentor, List<UserInterest> userInterests) {
this.profileImage = mentor.getProfileImage();
this.name = mentor.getFirstName() + " " + mentor.getLastName();
this.country = mentor.getCountry();
this.age = mentor.getAge();
this.birthDate = mentor.getBirthDate();
this.role = mentor.getRole();
this.favorites = userInterests.stream()
.map(userInterest -> userInterest.getInterest().getCategory())
Expand All @@ -89,7 +90,7 @@ public static class ContactMenteeDTO {
private String profileImage;
private String name;
private String country;
private int age;
private LocalDate birthDate;
private Role role;
private ContactStateEnum state;
private List<String> favorites; // 고민할 부분 : 유저의 favorite List 를 어떻게 가져올 것 인가?
Expand All @@ -106,7 +107,7 @@ public ContactMenteeDTO(NotConnectedRegisterUser notConnectedRegisterUser, List<
this.profileImage = notConnectedRegisterUser.getMenteeUser().getProfileImage();
this.name = notConnectedRegisterUser.getMenteeUser().getFirstName() + " " + notConnectedRegisterUser.getMenteeUser().getLastName();
this.country = notConnectedRegisterUser.getMenteeUser().getCountry();
this.age = notConnectedRegisterUser.getMenteeUser().getAge();
this.birthDate = notConnectedRegisterUser.getMenteeUser().getBirthDate();
this.role = notConnectedRegisterUser.getMenteeUser().getRole();
this.state = notConnectedRegisterUser.getState();
this.favorites = userInterests.stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
@Where(clause = "deleted_at IS NULL")
@SQLDelete(sql = "UPDATE not_connected_register_users SET deleted_at = CURRENT_TIMESTAMP, is_deleted = TRUE where id = ?")
@Table(name = "not_connected_register_users",
indexes = {
@Index(name = "not_connected_register_users_mentor_post_id_idx", columnList = "mentor_post_id"),
@Index(name = "not_connected_register_users_mentee_user_id_idx", columnList = "mentee_user_id")
},
// indexes = {
// @Index(name = "not_connected_register_users_mentor_post_id_idx", columnList = "mentor_post_id"),
// @Index(name = "not_connected_register_users_mentee_user_id_idx", columnList = "mentee_user_id")
// },
uniqueConstraints = {
@UniqueConstraint(name = "uk_not_connected_register_user_mentor_post_mentee_user", columnNames = {"mentor_post_id", "mentee_user_id"})
})
Expand Down
10 changes: 6 additions & 4 deletions src/main/java/com/example/demo/mentoring/done/DoneResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

Expand All @@ -33,7 +34,7 @@ public static class DoneMentorDTO {
private String profileImage;
private String name;
private String country;
private int age;
private LocalDate birthDate;
private Role role;
private List<String> favorites;

Expand All @@ -42,7 +43,7 @@ public DoneMentorDTO(User mentor, List<UserInterest> userInterests) {
this.profileImage = mentor.getProfileImage();
this.name = mentor.getFirstName() + " " + mentor.getLastName();
this.country = mentor.getCountry();
this.age = mentor.getAge();
this.birthDate = mentor.getBirthDate();
this.role = mentor.getRole();
this.favorites = userInterests.stream()
.map(userInterest -> userInterest.getInterest().getCategory())
Expand All @@ -55,15 +56,16 @@ public static class DoneMenteeDTO {
private String profileImage;
private String name;
private String country;
private int age;
private LocalDate birthDate;
private Role role;
private List<String> favorites;

public DoneMenteeDTO(ConnectedUser connectedUser, List<UserInterest> userInterests) {
this.menteeId = connectedUser.getId();
this.profileImage = connectedUser.getMenteeUser().getProfileImage();
this.name = connectedUser.getMenteeUser().getFirstName() + " " + connectedUser.getMenteeUser().getLastName();
this.country = connectedUser.getMenteeUser().getCountry();
this.age = connectedUser.getMenteeUser().getAge();
this.birthDate = connectedUser.getMenteeUser().getBirthDate();
this.role = connectedUser.getMenteeUser().getRole();
this.favorites = userInterests.stream()
.map(userInterest -> userInterest.getInterest().getCategory())
Expand Down
Loading

0 comments on commit cae7968

Please sign in to comment.