Skip to content

Commit

Permalink
Merge pull request #146 from PawWithU/feat/145-review-validation
Browse files Browse the repository at this point in the history
[Feature] 이동봉사자 후기 등록 검증 및 테스트 코드 수정
  • Loading branch information
hojeong2747 authored Nov 22, 2023
2 parents 9b445e4 + d06d8e8 commit 28f0a6d
Show file tree
Hide file tree
Showing 15 changed files with 20 additions and 42 deletions.
7 changes: 0 additions & 7 deletions src/main/java/com/pawwithu/connectdog/config/RedisConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,6 @@ public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.data.redis.host}")
private String host;

@PostConstruct // 해당 메서드는 객체의 모든 의존성이 주입된 직후에 자동으로 호출
public void printValues() {
log.info("Redis Host: " + host);
log.info("Redis Port: " + port);
}


@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
public interface ApplicationRepository extends JpaRepository<Application, Long> {

Boolean existsByPostId(Long postId);
Boolean existsByPostIdAndVolunteerId(Long postId, Long volunteerId);
Optional<Application> findByIdAndVolunteerId(Long id, Long volunteerId);
Optional<Application> findByIdAndIntermediaryId(Long id, Long intermediaryId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,5 @@ public void onAuthenticationFailure(HttpServletRequest request, HttpServletRespo

String errorMessage = "로그인에 실패했습니다. 이메일 혹은 비밀번호를 확인해 주세요.";
response.getWriter().write(errorMessage);

log.info("로그인에 실패했습니다. 메시지 : {}", exception.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,6 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
response.setStatus(HttpServletResponse.SC_OK); // 상태 코드를 200 (OK)로 설정
response.setContentType("application/json");
response.getWriter().write(new ObjectMapper().writeValueAsString(tokenData));

log.info("로그인에 성공하였습니다. 이메일 : {}", email);
log.info("로그인에 성공하였습니다. AccessToken : {}", accessToken);
log.info("발급된 AccessToken 만료 기간 : {}", accessTokenExpirationPeriod);
}

private String extractUsername(Authentication authentication) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ public void volunteerSocialSignUp(String email, SocialSignUpRequest socialSignUp
}

Volunteer volunteer = volunteerRepository.findByEmail(email).orElseThrow(() -> new BadRequestException(VOLUNTEER_NOT_FOUND));
log.info("volunteer: " + volunteer.getEmail());

// 추가 정보 업데이트
String nickname = socialSignUpRequest.nickname();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public List<VolunteerGetMyBadgeResponse> getMyBadges(Long volunteerId) {
.leftJoin(volunteerBadge)
.on(volunteerBadge.badge.id.eq(badge.id)
.and(volunteerBadge.volunteer.id.eq(volunteerId)))
.orderBy(badge.id.asc())
.fetch();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class OAuthController {
@Operation(summary = "이동봉사자 소셜 로그인", description = "이동봉사자 소셜 로그인을 합니다.",
responses = {@ApiResponse(responseCode = "204", description = "이동봉사자 소셜 로그인 성공")
, @ApiResponse(responseCode = "400"
, description = "V1, AccessToken은 필수 입력 값입니다. \t\n V1, provider는 필수 입력 값입니다. \t\n M1, 해당 이동봉사자를 찾을 수 없습니다."
, description = "V1, AccessToken은 필수 입력 값입니다. \t\n V1, provider는 필수 입력 값입니다. \t\n M1, 해당 이동봉사자를 찾을 수 없습니다. \t\n A5, provider 값이 KAKAO 또는 NAVER가 아닙니다."
, content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
})
@PostMapping("/volunteers/login/social")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,8 @@ public LoginResponse volunteerSocialLogin(SocialLoginRequest request) {
OAuthInfoResponse oAuthInfoResponse = requestOAuthInfoService.request(request);
SocialType socialType = oAuthInfoResponse.getSocialType();
String socialId = oAuthInfoResponse.getId();
log.info("socialId: " + socialId);

Long id = findOrSaveVolunteer(socialType, socialId); // Volunteer id 반환
log.info("id: " + id);

String role = String.valueOf(volunteerRepository.findById(id)
.map(Volunteer::getRole)
Expand Down Expand Up @@ -63,7 +61,6 @@ private Long findOrSaveVolunteer(SocialType socialType, String socialId) {
private Long saveVolunteer(SocialType socialType, String socialId) {
// 소셜 로그인 유저도 loginUser 사용 위한 email 랜덤 저장
String email = UUID.randomUUID() + "@socialUser.com";
log.info("email: " + email);
Volunteer createdVolunteer = new Volunteer(email, VolunteerRole.GUEST, socialType, socialId);

return volunteerRepository.save(createdVolunteer).getId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class ReviewController {
responses = {@ApiResponse(responseCode = "204", description = "후기 등록 성공")
, @ApiResponse(responseCode = "400"
, description = "V1, 후기 내용은 필수 입력 값입니다. \t\n V1, 내용은 20~300자로 입력해 주세요. \t\n F1, 파일이 존재하지 않습니다. \t\n F2, 파일 업로드에 실패했습니다. \t\n " +
"M1, 해당 이동봉사자를 찾을 수 없습니다. \t\n P2, 해당 공고를 찾을 수 없습니다."
"M1, 해당 이동봉사자를 찾을 수 없습니다. \t\n P2, 해당 공고를 찾을 수 없습니다. \t\n AP2, 해당 신청 내역을 찾을 수 없습니다."
, content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
})
@PostMapping(value = "/volunteers/posts/{postId}/reviews", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.pawwithu.connectdog.domain.review.service;

import com.pawwithu.connectdog.common.s3.FileService;
import com.pawwithu.connectdog.domain.application.repository.ApplicationRepository;
import com.pawwithu.connectdog.domain.post.entity.Post;
import com.pawwithu.connectdog.domain.post.repository.PostRepository;
import com.pawwithu.connectdog.domain.review.dto.request.ReviewCreateRequest;
Expand Down Expand Up @@ -38,6 +39,7 @@ public class ReviewService {
private final ReviewRepository reviewRepository;
private final ReviewImageRepository reviewImageRepository;
private final CustomReviewRepository customReviewRepository;
private final ApplicationRepository applicationRepository;

public void createReview(String email, Long postId, ReviewCreateRequest request, List<MultipartFile> fileList) {

Expand All @@ -48,6 +50,11 @@ public void createReview(String email, Long postId, ReviewCreateRequest request,
Volunteer volunteer = volunteerRepository.findByEmail(email).orElseThrow(() -> new BadRequestException(VOLUNTEER_NOT_FOUND));
Post post = postRepository.findById(postId).orElseThrow(() -> new BadRequestException(POST_NOT_FOUND));

// 해당 공고에 대한 이동봉사자 신청 건 확인
if (!applicationRepository.existsByPostIdAndVolunteerId(postId, volunteer.getId())) {
throw new BadRequestException(APPLICATION_NOT_FOUND);
}

// 후기 저장 (대표 이미지 제외)
Review review = ReviewCreateRequest.reviewToEntity(request, volunteer, post);
Review saveReview = reviewRepository.save(review);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/pawwithu/connectdog/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public enum ErrorCode {
ALREADY_EXIST_NICKNAME("A2", "이미 사용 중인 닉네임입니다."),
ALREADY_LOGOUT_MEMBER("A3", "이미 로그아웃한 회원입니다"),
EMAIL_SEND_ERROR("A4", "이메일 인증 코드 전송을 실패했습니다."),
UNKNOWN_PROVIDER("A4", "provider 값이 KAKAO 또는 NAVER가 아닙니다."),
UNKNOWN_PROVIDER("A5", "provider 값이 KAKAO 또는 NAVER가 아닙니다."),
NOT_ALLOWED_MEMBER("A6", "해당 요청에 대한 권한이 없습니다."),
NOT_AUTHENTICATED_REQUEST("A7", "유효한 JWT 토큰이 없습니다."),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
filterChain.doFilter(request, response); // NO_CHECK_URLS 요청이 들어오면, 다음 필터 호출
return;
}
log.info("uri = {}, query = {}", request.getRequestURI(), request.getQueryString());
log.info("JwtAuthenticationProcessingFilter 호출");

String accessToken = jwtService.extractAccessToken(request).orElse(null);
if (jwtService.isTokenValid(accessToken)) {
Expand All @@ -44,7 +42,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
return;
}

log.info("유효한 JWT 토큰이 없습니다. uri: {}, {}", request.getRequestURI(), accessToken);
filterChain.doFilter(request, response);
}
}
11 changes: 0 additions & 11 deletions src/main/java/com/pawwithu/connectdog/jwt/service/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ public Map<String, String> sendAccessAndRefreshToken(String roleName, String acc
tokens.put("roleName", roleName);
tokens.put("accessToken", accessToken);
tokens.put("refreshToken", refreshToken);

log.info("Access Token, Refresh Token 전송 준비 완료");
return tokens;
}

Expand Down Expand Up @@ -194,8 +192,6 @@ public boolean isTokenValid(String token) {
* RefreshToken 검증 메소드
*/
public boolean isRefreshTokenMatch(String roleName, Long id, String refreshToken) {

log.info("RefreshToken 검증");
if (redisUtil.get(roleName, id).equals(refreshToken)) {
return true;
}
Expand All @@ -218,9 +214,7 @@ public LoginResponse reIssueToken(String refreshToken) {
String newRefreshToken = null;
switch (roleName) {
case "INTERMEDIARY":
// case "AUTH_INTERMEDIARY":
case "VOLUNTEER":
// case "AUTH_VOLUNTEER":
newAccessToken = createAccessToken(id, roleName);
newRefreshToken = createRefreshToken(id, roleName);
break;
Expand All @@ -232,7 +226,6 @@ public LoginResponse reIssueToken(String refreshToken) {
getAuthentication(newAccessToken);
redisUtil.delete(roleName, id);
updateRefreshToken(roleName, id, newRefreshToken);
log.info("AccessToken, RefreshToken 재발급 완료");

return LoginResponse.of(roleName, newAccessToken, newRefreshToken);
}
Expand All @@ -242,8 +235,6 @@ public LoginResponse reIssueToken(String refreshToken) {
* 인증 허가 처리된 객체를 SecurityContextHolder에 담기
*/
public void getAuthentication(String accessToken) {
log.info("인증 처리 메소드 getAuthentication() 호출");

extractId(accessToken)
.ifPresent(id -> {
Optional<String> roleNameOpt = extractRoleName(accessToken);
Expand Down Expand Up @@ -275,7 +266,6 @@ public void getAuthentication(String accessToken) {
* 파라미터의 유저 : 우리가 만든 회원 객체 / 빌더의 유저 : UserDetails의 User 객체
*/
public void saveIntermediaryAuthentication(Intermediary intermediary) {
log.info("인증 허가 메소드 saveAuthentication() 호출");
String password = intermediary.getPassword();
if (password == null) { // 소셜 로그인 유저의 비밀번호 임의로 설정 하여 소셜 로그인 유저도 인증 되도록 설정
password = PasswordUtil.generateRandomPassword();
Expand All @@ -295,7 +285,6 @@ public void saveIntermediaryAuthentication(Intermediary intermediary) {
}

public void saveVolunteerAuthentication(Volunteer volunteer) {
log.info("인증 허가 메소드 saveAuthentication() 호출");
String password = volunteer.getPassword();
if (password == null) { // 소셜 로그인 유저의 비밀번호 임의로 설정 하여 소셜 로그인 유저도 인증 되도록 설정
password = PasswordUtil.generateRandomPassword();
Expand Down
12 changes: 6 additions & 6 deletions src/main/resources/import.sql
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ UPDATE post SET main_image_id = 15 WHERE id = 15;
UPDATE post SET main_image_id = 16 WHERE id = 16;

-- INSERT VOLUNTEER
INSERT INTO volunteer (id, email, password, nickname, profile_image_num, name, phone, role, is_option_agr, notification, created_date, modified_date) VALUES (1, '[email protected]', '{bcrypt}$2a$10$VieltvcRaI/rJnaRHuRPju9rqM9BvmKRkmn./oOninx7fOGT/q2De', '이동봉사자', 1, '한호정', '01047391908', 'AUTH_VOLUNTEER', false, false, now(), now());
INSERT INTO volunteer (id, email, password, nickname, profile_image_num, name, phone, role, is_option_agr, notification, created_date, modified_date) VALUES (1, '[email protected]', '{bcrypt}$2a$10$VieltvcRaI/rJnaRHuRPju9rqM9BvmKRkmn./oOninx7fOGT/q2De', '이동봉사자', 2, '한호정', '01047391908', 'AUTH_VOLUNTEER', false, false, now(), now());

INSERT INTO volunteer (id, email, password, nickname, profile_image_num, name, phone, role, is_option_agr, notification, created_date, modified_date) VALUES (2, '[email protected]', '{bcrypt}$2a$10$wkmYUG/qvZFThCzq19yHredRc6u8nAhlAopbDE9p7n6JF6NgtLs8y', '하얀마음', 1, '민경혁', '01047391908', 'AUTH_VOLUNTEER', false, false, now(), now());

Expand Down Expand Up @@ -194,8 +194,8 @@ INSERT INTO volunteer_badge(id, badge_id, volunteer_id, created_date, modified_d
INSERT INTO volunteer_badge(id, badge_id, volunteer_id, created_date, modified_date) VALUES (8, 8, 2, now(), now());

-- INSERT BOOKMARK
INSERT INTO bookmark(id, post_id, volunteer_id) VALUES (1, 6, 2);
INSERT INTO bookmark(id, post_id, volunteer_id) VALUES (2, 7, 2);
INSERT INTO bookmark(id, post_id, volunteer_id) VALUES (3, 8, 2);
INSERT INTO bookmark(id, post_id, volunteer_id) VALUES (4, 9, 2);
INSERT INTO bookmark(id, post_id, volunteer_id) VALUES (5, 10, 2);
INSERT INTO bookmark(id, post_id, volunteer_id, created_date, modified_date) VALUES (1, 6, 2, now(), now());
INSERT INTO bookmark(id, post_id, volunteer_id, created_date, modified_date) VALUES (2, 7, 2, now(), now());
INSERT INTO bookmark(id, post_id, volunteer_id, created_date, modified_date) VALUES (3, 8, 2, now(), now());
INSERT INTO bookmark(id, post_id, volunteer_id, created_date, modified_date) VALUES (4, 9, 2, now(), now());
INSERT INTO bookmark(id, post_id, volunteer_id, created_date, modified_date) VALUES (5, 10, 2, now(), now());
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ void setUp() {

// when
ResultActions result = mockMvc.perform(
post("/volunteers/bookmarks/{postId}", postId)
post("/volunteers/posts/{postId}/bookmarks", postId)
);

// then
Expand All @@ -61,7 +61,7 @@ void setUp() {

// when
ResultActions result = mockMvc.perform(
delete("/volunteers/bookmarks/{postId}", postId)
delete("/volunteers/posts/{postId}/bookmarks", postId)
);

// then
Expand Down

0 comments on commit 28f0a6d

Please sign in to comment.