Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/main/java/org/example/expert/client/WeatherClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import org.example.expert.client.dto.WeatherDto;
import org.example.expert.domain.common.exception.ServerException;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
Expand All @@ -26,13 +25,16 @@ public String getTodayWeather() {
ResponseEntity<WeatherDto[]> responseEntity =
restTemplate.getForEntity(buildWeatherApiUri(), WeatherDto[].class);

if (!responseEntity.getStatusCode().is2xxSuccessful()) {
throw new ServerException(
"날씨 데이터를 가져오는데 실패했습니다. 상태 코드: " + responseEntity.getStatusCode()
);
}

WeatherDto[] weatherArray = responseEntity.getBody();
if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
throw new ServerException("날씨 데이터를 가져오는데 실패했습니다. 상태 코드: " + responseEntity.getStatusCode());
} else {
if (weatherArray == null || weatherArray.length == 0) {
throw new ServerException("날씨 데이터가 없습니다.");
}

if (weatherArray == null || weatherArray.length == 0) {
throw new ServerException("날씨 데이터가 없습니다.");
}

String today = getCurrentDate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import org.example.expert.domain.user.enums.UserRole;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class AuthUserArgumentResolver implements HandlerMethodArgumentResolver {

@Override
Expand Down
20 changes: 20 additions & 0 deletions src/main/java/org/example/expert/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.example.expert.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

private final AuthUserArgumentResolver authUserArgumentResolver;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(authUserArgumentResolver);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ public class AuthService {
@Transactional
public SignupResponse signup(SignupRequest signupRequest) {

if (userRepository.existsByEmail(signupRequest.getEmail())) {
throw new InvalidRequestException("이미 존재하는 이메일입니다.");
}

String encodedPassword = passwordEncoder.encode(signupRequest.getPassword());

UserRole userRole = UserRole.of(signupRequest.getUserRole());

if (userRepository.existsByEmail(signupRequest.getEmail())) {
throw new InvalidRequestException("이미 존재하는 이메일입니다.");
}


User newUser = new User(
signupRequest.getEmail(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public ManagerSaveResponse saveManager(AuthUser authUser, long todoId, ManagerSa
Todo todo = todoRepository.findById(todoId)
.orElseThrow(() -> new InvalidRequestException("Todo not found"));

if(todo.getUser() == null) {
throw new InvalidRequestException("일정을 생성한 유저만 담당자를 지정할 수 있습니다.");
}

if (!ObjectUtils.nullSafeEquals(user.getId(), todo.getUser().getId())) {
throw new InvalidRequestException("일정을 생성한 유저만 담당자를 지정할 수 있습니다.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import org.example.expert.domain.todo.entity.Todo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Optional;

Expand All @@ -14,10 +14,6 @@ public interface TodoRepository extends JpaRepository<Todo, Long> {
@Query("SELECT t FROM Todo t LEFT JOIN FETCH t.user u ORDER BY t.modifiedAt DESC")
Page<Todo> findAllByOrderByModifiedAtDesc(Pageable pageable);

@Query("SELECT t FROM Todo t " +
"LEFT JOIN FETCH t.user " +
"WHERE t.id = :todoId")
Optional<Todo> findByIdWithUser(@Param("todoId") Long todoId);

int countById(Long todoId);
@EntityGraph(attributePaths = {"user"})
Optional<Todo> findTodoById(Long todoId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public Page<TodoResponse> getTodos(int page, int size) {

@Transactional(readOnly = true)
public TodoResponse getTodo(long todoId) {
Todo todo = todoRepository.findByIdWithUser(todoId)
Todo todo = todoRepository.findTodoById(todoId)
.orElseThrow(() -> new InvalidRequestException("Todo not found"));

User user = todo.getUser();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.example.expert.domain.user.controller;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.expert.domain.common.annotation.Auth;
import org.example.expert.domain.common.dto.AuthUser;
Expand All @@ -21,7 +22,7 @@ public ResponseEntity<UserResponse> getUser(@PathVariable long userId) {
}

@PutMapping("/users")
public void changePassword(@Auth AuthUser authUser, @RequestBody UserChangePasswordRequest userChangePasswordRequest) {
public void changePassword(@Auth AuthUser authUser, @Valid @RequestBody UserChangePasswordRequest userChangePasswordRequest) {
userService.changePassword(authUser.getId(), userChangePasswordRequest);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.example.expert.domain.user.dto.request;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -12,6 +13,11 @@ public class UserChangePasswordRequest {

@NotBlank
private String oldPassword;

@NotBlank
@Pattern(
regexp = "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).{8,}$",
message = "비밀번호는 8자 이상이며, 대문자/소문자/숫자를 포함해야 합니다."
)
private String newPassword;
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@ public UserResponse getUser(long userId) {

@Transactional
public void changePassword(long userId, UserChangePasswordRequest userChangePasswordRequest) {
if (userChangePasswordRequest.getNewPassword().length() < 8 ||
!userChangePasswordRequest.getNewPassword().matches(".*\\d.*") ||
!userChangePasswordRequest.getNewPassword().matches(".*[A-Z].*")) {
throw new InvalidRequestException("새 비밀번호는 8자 이상이어야 하고, 숫자와 대문자를 포함해야 합니다.");
}

User user = userRepository.findById(userId)
.orElseThrow(() -> new InvalidRequestException("User not found"));

Expand Down
18 changes: 18 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/nbcam
username: root
password: 12345678
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
defer-datasource-initialization: true

jwt :
secret :
key : c3ByaW5nc2VjcmV0S2V5c3ByaW5nc2VjcmV0S2V5c3ByaW5nc2VjcmV0S2V5
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ class PasswordEncoderTest {
@Test
void matches_메서드가_정상적으로_동작한다() {
// given
String rawPassword = "testPassword";
String rawPassword = "springsecretKeyspringsecretKeyspringsecretKey";
String encodedPassword = passwordEncoder.encode(rawPassword);

// when
boolean matches = passwordEncoder.matches(encodedPassword, rawPassword);
boolean matches = passwordEncoder.matches(rawPassword, encodedPassword);

// then
assertTrue(matches);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.example.expert.domain.comment.entity.Comment;
import org.example.expert.domain.comment.repository.CommentRepository;
import org.example.expert.domain.common.dto.AuthUser;
import org.example.expert.domain.common.exception.InvalidRequestException;
import org.example.expert.domain.common.exception.ServerException;
import org.example.expert.domain.todo.entity.Todo;
import org.example.expert.domain.todo.repository.TodoRepository;
Expand Down Expand Up @@ -43,7 +44,7 @@ class CommentServiceTest {
given(todoRepository.findById(anyLong())).willReturn(Optional.empty());

// when
ServerException exception = assertThrows(ServerException.class, () -> {
InvalidRequestException exception = assertThrows(InvalidRequestException.class, () -> {
commentService.saveComment(authUser, todoId, request);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.example.expert.domain.user.entity.User;
import org.example.expert.domain.user.enums.UserRole;
import org.example.expert.domain.user.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
Expand All @@ -38,15 +39,22 @@ class ManagerServiceTest {
@InjectMocks
private ManagerService managerService;

@BeforeEach
void init() {
todoRepository.save(new Todo());
}

@Test
public void manager_목록_조회_시_Todo가_없다면_NPE_에러를_던진다() {
public void manager_목록_조회_시_Todo가_없다면_InvalidRequestException_에러를_던진다() {
// given
long todoId = 1L;
given(todoRepository.findById(todoId)).willReturn(Optional.empty());

// when & then
InvalidRequestException exception = assertThrows(InvalidRequestException.class, () -> managerService.getManagers(todoId));
assertEquals("Manager not found", exception.getMessage());
InvalidRequestException exception = assertThrows(
InvalidRequestException.class,
() -> managerService.getManagers(todoId));
assertEquals("Todo not found", exception.getMessage());
}

@Test
Expand Down