Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

아이디 찾기 #180

Merged
merged 9 commits into from
Sep 20, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.authorizeRequests()
.antMatchers(
API_V1_PREFIX + "/users/sign-up", // 회원가입
API_V1_PREFIX + "/auth/sign-in" // 로그인
API_V1_PREFIX + "/auth/sign-in", // 로그인
API_V1_PREFIX + "/users/student-number/**" // 아이디 찾기
)
.permitAll()
.anyRequest()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.NoSuchElementException;
import java.util.Optional;

import javax.validation.ConstraintViolation;
Expand All @@ -21,7 +22,8 @@
public class GlobalExceptionHandler {

@ExceptionHandler({
IllegalArgumentException.class, IllegalStateException.class,
IllegalArgumentException.class,
IllegalStateException.class,
HttpMessageNotReadableException.class
})
@ResponseStatus(HttpStatus.BAD_REQUEST)
Expand All @@ -30,6 +32,12 @@
return ExceptionResponse.of(HttpStatus.BAD_REQUEST, getMessage(e));
}

@ExceptionHandler(NoSuchElementException.class)
public ExceptionResponse handleNotFoundException(Exception e) {
log.debug("Not Found exception occurred: {}", e.getMessage(), e);
return ExceptionResponse.of(HttpStatus.NOT_FOUND, getMessage(e));

Check warning on line 38 in src/main/java/com/plzgraduate/myongjigraduatebe/core/exception/GlobalExceptionHandler.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/com/plzgraduate/myongjigraduatebe/core/exception/GlobalExceptionHandler.java#L37-L38

Added lines #L37 - L38 were not covered by tests
}

@ExceptionHandler(UnAuthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ExceptionResponse handleUnAuthorizedException(Exception e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.plzgraduate.myongjigraduatebe.user.adaptor.in.web.findauthid;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.plzgraduate.myongjigraduatebe.core.meta.WebAdapter;
import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.FindUserAuthIdUseCase;
import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.UserAuthIdResponse;

import lombok.RequiredArgsConstructor;

@WebAdapter
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class FindAuthIdController {

private final FindUserAuthIdUseCase findUserAuthIdUseCase;

@GetMapping("/student-number/{studentNumber}")
public UserAuthIdResponse findUserAuthId(@PathVariable String studentNumber) {
return findUserAuthIdUseCase.findUserAuthId(studentNumber);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ public Optional<User> findUserByAuthId(String authId) {
return Optional.of(userMapper.mapToDomainEntity(userJpaEntity));
}

@Override
public Optional<User> findUserByStudentNumber(String studentNumber) {
return userRepository.findByStudentNumber(studentNumber).map(userMapper::mapToDomainEntity);
}

@Override
public boolean checkDuplicateAuthId(String authId) {
return userRepository.existsByAuthId(authId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
public interface UserRepository extends JpaRepository<UserJpaEntity, Long> {
Optional<UserJpaEntity> findByAuthId(String authId);

Optional<UserJpaEntity> findByStudentNumber(String studentNumber);

boolean existsByAuthId(String authId);

boolean existsByStudentNumber(String studentNumber);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.plzgraduate.myongjigraduatebe.user.application.port.in.find;

public interface FindUserAuthIdUseCase {

UserAuthIdResponse findUserAuthId(String studentNumber);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.plzgraduate.myongjigraduatebe.user.application.port.in.find;

import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor

Check warning on line 8 in src/main/java/com/plzgraduate/myongjigraduatebe/user/application/port/in/find/UserAuthIdResponse.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/com/plzgraduate/myongjigraduatebe/user/application/port/in/find/UserAuthIdResponse.java#L8

Added line #L8 was not covered by tests
public class UserAuthIdResponse {

private String authId;
private String studentNumber;

@Builder
private UserAuthIdResponse(String authId, String studentNumber) {
this.authId = authId;
this.studentNumber = studentNumber;
}

public static UserAuthIdResponse from(String encryptedAutId, String studentNumber) {
return UserAuthIdResponse.builder()
.authId(encryptedAutId)
.studentNumber(studentNumber).build();
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from -> of

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ public interface FindUserPort {

Optional<User> findUserById(Long id);
Optional<User> findUserByAuthId(String authId);

Optional<User> findUserByStudentNumber(String studentNumber);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.plzgraduate.myongjigraduatebe.user.application.service.find;

import java.util.NoSuchElementException;

import org.springframework.transaction.annotation.Transactional;

import com.plzgraduate.myongjigraduatebe.core.meta.UseCase;
import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.FindUserAuthIdUseCase;
import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.UserAuthIdResponse;
import com.plzgraduate.myongjigraduatebe.user.application.port.out.FindUserPort;
import com.plzgraduate.myongjigraduatebe.user.domain.model.User;

import lombok.RequiredArgsConstructor;

@UseCase
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class FindUserAuthIdService implements FindUserAuthIdUseCase {

private final FindUserPort findUserPort;

@Override
public UserAuthIdResponse findUserAuthId(String studentNumber) {
User user = findUserPort.findUserByStudentNumber(studentNumber)
.orElseThrow(() -> new NoSuchElementException("해당 학번의 사용자가 존재하지 않습니다"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

request body로 하고 400으로 수정해버리자. 기존 api 수정할 사항 있으면 그냥 하자.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

음 저는 400번 보다는 404가 맞는거 같은게 학번으로 조회하는 요청 자체는 잘못된 요청이 아니고 찾으려는 자원이 존재하지 않는거니 404가 더 알맞은 에러코드인거 같습니다.

return UserAuthIdResponse.from(user.getEncryptedAuthId(), studentNumber);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ public void matchPassword(PasswordEncoder passwordEncoder, String password) {
throw new IllegalArgumentException("비밀번호가 일치하지 않습니다.");
}
}

public String getEncryptedAuthId() {
return authId.replace(authId.substring(authId.length() - 3), "***");
}
private static int parseEntryYearInStudentNumber(String studentNumber) {
return Integer.parseInt(studentNumber.substring(2, 4));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.plzgraduate.myongjigraduatebe.user.adaptor.in.web.findauthid;

import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import com.plzgraduate.myongjigraduatebe.support.WebAdaptorTestSupport;
import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.FindUserAuthIdUseCase;
import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.UserAuthIdResponse;

@WebMvcTest(controllers = FindAuthIdController.class)
class FindAuthIdControllerTest extends WebAdaptorTestSupport {

@MockBean
private FindUserAuthIdUseCase findUserAuthIdUseCase;

@DisplayName("학번으로 해당 학생의 아이디를 조회한다.")
@Test
void findUserAuthId() throws Exception {
//given
String studentNumber = "60191111";
String encryptedAuthId = "test***";
UserAuthIdResponse userAuthIdResponse = UserAuthIdResponse.builder()
.authId(encryptedAuthId)
.studentNumber(studentNumber).build();
given(findUserAuthIdUseCase.findUserAuthId(studentNumber)).willReturn(userAuthIdResponse);

//when //then
mockMvc.perform(get("/api/v1/users/student-number/{studentNumber}", studentNumber))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.authId", is(encryptedAuthId)))
.andExpect(jsonPath("$.studentNumber", is(studentNumber)));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,22 @@ class UserPersistenceAdaptorTest extends PersistenceTestSupport {
assertThat(user.get().getAuthId()).isEqualTo(authId);
}

@DisplayName("학번으로 사용자를 조회한다.")
@Test
void findUserByStudentNumber() {
//given
String studentNumber = "60181666";
UserJpaEntity userJpaEntity = createUserEntity("mju1001", "1q2w3e4r!", studentNumber);
userRepository.save(userJpaEntity);

//when
Optional<User> user = userPersistenceAdaptor.findUserByStudentNumber(studentNumber);

//then
assertThat(user).isPresent();
assertThat(user.get().getStudentNumber()).isEqualTo(studentNumber);
}

@DisplayName("아이디가 이미 존재하는지 확인한다.")
@Test
void 중복_아이디_확인() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.plzgraduate.myongjigraduatebe.user.adaptor.out.persistence;

import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.*;

import java.util.List;
Expand Down Expand Up @@ -33,6 +32,22 @@ class UserRepositoryTest extends PersistenceTestSupport {
assertThat(user.get().getAuthId()).isEqualTo("mju1001");
}

@DisplayName("학번을 통해 유저를 조회한다.")
@Test
void findByStudentNumber() {
//given
String studentNumber = "60181666";
UserJpaEntity userJpaEntity = createUserEntity("mju1001", "1q2w3e4r!", studentNumber);
userRepository.save(userJpaEntity);

//when
Optional<UserJpaEntity> user = userRepository.findByStudentNumber(studentNumber);

//then
assertThat(user).isPresent();
assertThat(user.get().getStudentNumber()).isEqualTo(studentNumber);
}

@DisplayName("아이디가 이미 존재하는지 확인한다.")
@Test
void 중복_아이디_확인() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.plzgraduate.myongjigraduatebe.user.application.service.find;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;

import java.util.NoSuchElementException;
import java.util.Optional;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.plzgraduate.myongjigraduatebe.user.application.port.in.find.UserAuthIdResponse;
import com.plzgraduate.myongjigraduatebe.user.application.port.out.FindUserPort;
import com.plzgraduate.myongjigraduatebe.user.domain.model.User;

@ExtendWith(MockitoExtension.class)
class FindUserAuthIdServiceTest {

@Mock
private FindUserPort findUserPort;

@InjectMocks
private FindUserAuthIdService findUserAuthIdService;

@DisplayName("학번을 통해 해당 학번 학생의 암호화된 로그인 아이디를 얻는다.")
@Test
void findUserAuthId() {
//given
String studentNumber = "60191111";
User user = User.builder()
.authId("tester00")
.password("tester00!")
.studentNumber(studentNumber)
.build();
given(findUserPort.findUserByStudentNumber(anyString())).willReturn(Optional.of(user));

//when
UserAuthIdResponse userAuthIdResponse = findUserAuthIdService.findUserAuthId(studentNumber);

//then
assertThat(userAuthIdResponse).extracting("authId", "studentNumber")
.contains("teste***", studentNumber);
}

@DisplayName("학번에 해당하는 유저가 존재하지 않을 경우 예외가 발생한다.")
@Test
void findUserAuthIdWithoutUser() {
//given
String studentNumber = "60191111";
given(findUserPort.findUserByStudentNumber(anyString())).willReturn(Optional.empty());

//when //then
assertThatThrownBy(() -> findUserAuthIdService.findUserAuthId(studentNumber))
.isInstanceOf(NoSuchElementException.class)
.hasMessage("해당 학번의 사용자가 존재하지 않습니다");
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.plzgraduate.myongjigraduatebe.user.domain.model;

import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.MockitoAnnotations.openMocks;
Expand Down Expand Up @@ -56,7 +55,6 @@ void updateStudentInformation() {
.contains("테스터2", "경영학과", "데이터테크놀로지학과", null, StudentCategory.CHANGE_MAJOR);
}


@DisplayName("checkBeforeEntryYear 메서드 테스트")
@Test
void checkBeforeEntryYear() {
Expand Down Expand Up @@ -97,4 +95,22 @@ void matchWrongPassword() {
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("비밀번호가 일치하지 않습니다.");
}

@DisplayName("유저의 암호화된 로그인 아이디(뒷 세자리 *** 대체)를 반환한다.")
@Test
void getEncryptedAuthId() {
//given
String authId = "testAuthId";
User user = User.builder()
.authId(authId).build();

//when
String encryptedAuthId = user.getEncryptedAuthId();

//then
assertThat(encryptedAuthId.substring(0, encryptedAuthId.length() - 4))
.isEqualTo(authId.substring(0, authId.length() - 4));
assertThat(encryptedAuthId.substring(encryptedAuthId.length() - 3)).isEqualTo(
"***");
}
}
Loading