레스토랑 예약 사이트 만들기 10 - 회원 가입

Security 설정하기

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().disable()
.csrf().disable()
.formLogin().disable()
.headers().frameOptions().disable();
}
}
@Service
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

public User registerUser(String email, String name, String password) {
User user = User.builder()
.email(email)
.name(name)
.password(encodedPassword)
.level(1L)
.build();

userRepository.save(user);

return user;
}
}

패스워드에 암호화 하기

@Service
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

public User registerUser(String email, String name, String password) {
// 패스워드를 암호화해서 저장한다.
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);

User user = User.builder()
.email(email)
.name(name)
.password(encodedPassword)
.level(1L)
.build();

userRepository.save(user);

return user;
}
}
class UserServiceTest {

@Mock
private UserRepository userRepository;

private UserService userService;

@BeforeEach
public void setUp(){
MockitoAnnotations.openMocks(this);
userService = new UserService(userRepository);
}

@Test @DisplayName("사용자를 등록한다.")
public void registerUser(){
String email = "test@example.com";
String name = "Tester";
String password = "test";

User user = userService.registerUser(email, name, password);
assertThat(user.getEmail()).isEqualTo(email);
assertThat(user.getName()).isEqualTo(name);
assertThat(user.getPassword()).isEqualTo(password);

verify(userRepository).save(any());
}
}
@RestController
@RequiredArgsConstructor
public class UserController {

private final UserService userService;

@PostMapping("/users")
public ResponseEntity<?> create(@RequestBody User resource){
String email = resource.getEmail();
String name = resource.getName();
String password = resource.getPassword();

User user = userService.registerUser(email, name, password);
String url = "/users/" + user.getId();
return ResponseEntity.created(URI.create(url)).body("{}");
}
}
@WebMvcTest(UserController.class)
class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;


@Test
@DisplayName("사용자를 생성한다.")
public void create() throws Exception {
String email = "tester@example.com";
String name = "Tester";
String password = "test";

User mockUser = User.builder()
.Id(1004L)
.email(email)
.password(password)
.name(name)
.build();

given(userService.registerUser(email, name, password))
.willReturn(mockUser);

ResultActions resultActions = mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\" : \"tester@example.com\", \"name\" : \"Tester\", \"password\" : \"test\"}"));

resultActions
.andExpect(status().isCreated())
.andExpect(header().string("location", "/users/1004"));

verify(userService).registerUser(any(), any(), any());
}
}

존재하는 회원에 대한 예외처리

public class EmailExistedException extends RuntimeException{
public EmailExistedException(String email){
super("Email is already registered: " + email);
}
}
@Service
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

public User registerUser(String email, String name, String password) {
// 회원이 이미 등록되어 있는지 Email을 통해 유효성 검사
Optional<User> optional = userRepository.findByEmail(email);

// 회원이 이미 존재하는 경우 예외처리를 한다.
if(optional.isPresent()){
throw new EmailExistedException(email);
}

// 패스워드를 암호화해서 저장한다.
// 암호화 방식은 BCrypt방식을 이용해 암호화를 진행
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);

User user = User.builder()
.email(email)
.name(name)
.password(encodedPassword)
.level(1L)
.build();

userRepository.save(user);

return user;
}
}
@Test
@DisplayName("사용자가 이미 등록돼 있는경우 예외처리를 한다.")
public void registerUserWithExistedEmail(){
String email = "test@example.com";
String name = "Tester";
String password = "test";
User mockUser = User.builder()
.email(email)
.name(name)
.password(password)
.build();

given(userRepository.findByEmail(email)).willReturn(Optional.of(mockUser));

// 예외처리가 발생되는지 확인한다.
assertThatThrownBy(() -> {
userService.registerUser(email, name, password);
}).isInstanceOf(EmailExistedException.class);

verify(userRepository).findByEmail(any());
}
Share