diff --git a/.gitignore b/.gitignore index c2065bc..63d2f1a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -HELP.md .gradle build/ !gradle/wrapper/gradle-wrapper.jar diff --git a/build.gradle b/build.gradle index 8d6b6e3..5146da0 100644 --- a/build.gradle +++ b/build.gradle @@ -2,6 +2,7 @@ plugins { id 'java' id 'org.springframework.boot' version '2.7.11' id 'io.spring.dependency-management' version '1.0.15.RELEASE' + id 'jacoco' } group = 'org.poolc' @@ -19,12 +20,19 @@ repositories { } dependencies { + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.apache.commons:commons-lang3:3.12.0' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.apache.commons:commons-collections4:4.4' + implementation 'org.eclipse.persistence:javax.persistence:2.2.1' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + runtimeOnly 'com.h2database:h2' testImplementation 'org.springframework.boot:spring-boot-starter-test' + } tasks.named('test') { diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..d6684c1 --- /dev/null +++ b/readme.md @@ -0,0 +1,29 @@ +# PoolC-Spring-Practice + +풀씨 백엔드와 유사하지만, 일부 기능들을 개선한 서버를 만들어봅시다. 물론 풀씨 페이지는 규모가 상당히 크기에, 모든 컴포넌트를 만들 수 없으니 기본적인 것들만 구현해 봅시다. + +진행 방식 +--- +- Spring 프로그래밍 연습 스터디는, 하나의 큰 과제를 수행해야 합니다. + - Java 스터디에 비해 자유도가 조금 높으며, 요구 사항이 다소 추상적입니다. +- 직접적인 main 브랜치로의 커밋은 금지 되며, 반드시 Step 수행 이후 Pull Request 요청을 통해 확인이 진행됩니다. + - 본인의 닉네임/이름에 해당하는 브랜치를 만들고, 각 Step 에 대한 브랜치를 만들어서 PR을 진행해 주세요. + - ex) KBC 브랜치를 만들고, Step 1에 대한 결과물은 KBC-step1 로 만들어 주세요. + - 그 이후, PR은 KBC-step1 -> KBC 꼴로 요청해 주세요. +- 각 커밋의 단위는 최소화 해야하며, 다음과 같은 커밋 메시지 양식을 준수해 주세요. + - https://vsfe.notion.site/Git-Convention-84e1df4868974a58a1609b052e815095 + +요구 사항 (공통) +--- +- 해당 과제는 여러 Step으로 구성되어 있으며, 앞 Step에 대한 PR 및 리뷰가 완료 되어야 뒤 Step을 진행할 수 있습니다. +- 포함된 라이브러리는 기본적인 라이브러리만 포함되어 있으며, 필요에 따라 추가 라이브러리를 사용해도 됩니다. +- 모든 Java 코드는 반드시 Java 코드 컨벤션 가이드를 준수해야 합니다. +- 작성한 메서드에 대한 테스트 코드 작성이 진행되어야 합니다. + - Jacoco 기준, Test Coverage 및 Branch Coverage가 80% 이상이어야 합니다. + - 통합 테스트/단위 테스트 여부는 자유롭게 설정하셔도 됩니다. + - 하지만, 통합 테스트 수행 시, 실제 DB에 전혀 영향이 가지 않아야 합니다. +- 사용하는 DB는 제한이 없습니다. + +요구 사항 (단계) +--- +- 특정 Step 을 마치지 못했다면, 그 다음 Step의 요구 사항을 보지 않는 것을 권장합니다. https://vsfe.notion.site/Spring-PoolC-Backend-Reborn-281c69c2eaf543459fedace987868ea4 diff --git a/src/main/java/org/poolc/springpractice/PoolCSpringPracticeSeason2Application.java b/src/main/java/org/poolc/PoolCSpringPracticeSeason2Application.java similarity index 90% rename from src/main/java/org/poolc/springpractice/PoolCSpringPracticeSeason2Application.java rename to src/main/java/org/poolc/PoolCSpringPracticeSeason2Application.java index 6c56a52..1e215ab 100644 --- a/src/main/java/org/poolc/springpractice/PoolCSpringPracticeSeason2Application.java +++ b/src/main/java/org/poolc/PoolCSpringPracticeSeason2Application.java @@ -1,4 +1,4 @@ -package org.poolc.springpractice; +package org.poolc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/src/main/java/org/poolc/config/SecurityConfig.java b/src/main/java/org/poolc/config/SecurityConfig.java new file mode 100644 index 0000000..82980bc --- /dev/null +++ b/src/main/java/org/poolc/config/SecurityConfig.java @@ -0,0 +1,24 @@ +package org.poolc.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + + +@Configuration @EnableWebSecurity +public class SecurityConfig{ + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ + http + .csrf().disable() // post 방식으로 값을 전송할 때 token을 사용해야하는 보안 설정을 해제 + .authorizeRequests() + .antMatchers("/", "/members/**").permitAll() + .anyRequest().authenticated(); + return http.build(); + } +} diff --git a/src/main/java/org/poolc/config/SpringConfig.java b/src/main/java/org/poolc/config/SpringConfig.java new file mode 100644 index 0000000..e068b82 --- /dev/null +++ b/src/main/java/org/poolc/config/SpringConfig.java @@ -0,0 +1,43 @@ +package org.poolc.config; + + + +import org.poolc.repository.JpaMemberRepository; +import org.poolc.repository.MemberRepository; +import org.poolc.repository.MemoryMemberRepository; +import org.poolc.service.MemberService; +import org.poolc.service.MemberServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + + +@Configuration +public class SpringConfig { + + @PersistenceContext + private EntityManager em; + + @Bean + public PasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public MemberService memberService(){ + + return new MemberServiceImpl(memberRepository(),bCryptPasswordEncoder() ); + } + + @Bean + public MemberRepository memberRepository(){ + + //return new MemoryMemberRepository(); + return new JpaMemberRepository(em); + } +} diff --git a/src/main/java/org/poolc/controller/HomeController.java b/src/main/java/org/poolc/controller/HomeController.java new file mode 100644 index 0000000..24aecd7 --- /dev/null +++ b/src/main/java/org/poolc/controller/HomeController.java @@ -0,0 +1,37 @@ +package org.poolc.controller; + +import lombok.RequiredArgsConstructor; +import org.poolc.controller.session.SessionConst; +import org.poolc.controller.session.SessionManager; +import org.poolc.domain.Member; +import org.poolc.repository.MemberRepository; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.CookieValue; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.SessionAttribute; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +@Controller +@RequiredArgsConstructor +public class HomeController { + + private final MemberRepository memberRepository; + private final SessionManager sessionManager; + + @GetMapping("/") + public String homeLoginV2( + @SessionAttribute(name = SessionConst.LOGIN_MEMBER, required = false) Member loginMember, Model model){ + + //세션에 회원데이터가 없으면 home + if(loginMember ==null){ + return "home"; + } + + //세션이 유지되면 회원 홈(로그인 모드 홈)으로 이동 + model.addAttribute("member", loginMember); + return "loginHome"; + } +} diff --git a/src/main/java/org/poolc/controller/LoginController.java b/src/main/java/org/poolc/controller/LoginController.java new file mode 100644 index 0000000..4c653c7 --- /dev/null +++ b/src/main/java/org/poolc/controller/LoginController.java @@ -0,0 +1,66 @@ +package org.poolc.controller; + +import lombok.RequiredArgsConstructor; +import org.poolc.controller.form.LoginFormController; +import org.poolc.controller.session.SessionConst; +import org.poolc.controller.session.SessionManager; +import org.poolc.domain.Member; +import org.poolc.service.LoginServiceImpl; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Controller; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.util.CookieGenerator; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.validation.Valid; + +@Controller +@RequiredArgsConstructor +public class LoginController { + + private final LoginServiceImpl loginService; + + // 로그인 페이지로 이동 + @GetMapping("/members/login") + public String loginForm(@ModelAttribute("loginForm") LoginFormController form){ + return "members/loginMemberForm"; + } + + @PostMapping("/members/login") + public String login(@Valid @ModelAttribute("loginForm") LoginFormController form, BindingResult bindingResult, HttpServletRequest request){ + // valid한 입력이 아닐경우(채우지 않은 칸이 존재), 로그인 화면으로 다시 redirection + if(bindingResult.hasErrors()){ + return "members/loginMemberForm"; + } + // 가입하지 않은 아이디일 경우, 로그인 화면으로 다시 redirection + Member loginMember = loginService.login(form.getLoginId(), form.getPassword()); + if(loginMember == null){ + return "members/loginMemberForm"; + } + + //로그인 성공 -> 세션이 있으면 해당 세션 반환, 없으면 신규세션 생성(default=true) false면 세션 없으면 null을 반환 + HttpSession session = request.getSession(); + //세션에 로그인 회원 정보 보관. + session.setAttribute(SessionConst.LOGIN_MEMBER, loginMember); + + return "redirect:/"; + } + + // 로그아웃 page로 이동 + @RequestMapping(value="/members/logout" , method = {RequestMethod.GET, RequestMethod.POST}) + public String logout(HttpServletRequest request){ + //로그아웃시 해당 세션 삭제 후 홈으로 이동 + HttpSession session = request.getSession(false); + if(session != null){ + session.invalidate(); + } + return "redirect:/"; + } + + + +} diff --git a/src/main/java/org/poolc/controller/MemberController.java b/src/main/java/org/poolc/controller/MemberController.java new file mode 100644 index 0000000..b993d5f --- /dev/null +++ b/src/main/java/org/poolc/controller/MemberController.java @@ -0,0 +1,96 @@ +package org.poolc.controller; + +import com.sun.xml.bind.v2.TODO; +import org.poolc.controller.session.SessionConst; +import org.poolc.domain.Member; +import org.poolc.service.MemberService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.SessionAttribute; + +import javax.validation.Valid; +import java.util.List; +import java.util.Optional; + +@Controller +public class MemberController { + + private final MemberService memberService; + + @Autowired + public MemberController(MemberService memberService){ + this.memberService = memberService; + } + + //회원 가입 페이지 + @GetMapping("/members/new") + public String createForm(@ModelAttribute("member") Member member){ + return "members/createMemberForm"; + } + + @PostMapping("/members/new") + + public String create(@Valid @ModelAttribute("member") Member member, BindingResult bindingResult){ + // 회원가입 정보가 valid하지않은 경우(채우지 않은 칸 존재) -> 다시 회원 가입 창으로 redirection + if(bindingResult.hasErrors()){ + return "members/createMemberForm"; + } + + //기존에 있는 회원 아이디와 동이한지 체크 + if(memberService.findByUserId(member.getUserId()).isPresent()){ + return "members/createMemberForm"; + } + + memberService.join(member); + + return "redirect:/"; + } + + // 회원들 리스트 나열 + @GetMapping("/members") + public String list(Model model){ + List members = memberService.findMembers(); + model.addAttribute("members", members); + return "members/memberList"; + } + + // 회원정보 수정 창 -> 회원 전용 홈(후술 로그인 홈)에서만 접근 가능해야함 + @GetMapping("/members/update") + public String UpdateForm(@SessionAttribute(name = SessionConst.LOGIN_MEMBER, required = false) + Member loginMember, Model model){ + //세션에 회원데이터가 없으면 home + if(loginMember ==null){ + return "home"; + } + + //세션이 유지되면(로그인된 상태면) 회원 업데이트 화면으로 이동 + model.addAttribute("member", loginMember); + return "members/updateMemberForm"; + } + + + @PostMapping("/members/update") + public String update(@SessionAttribute(name = SessionConst.LOGIN_MEMBER, required = false) Member loginMember, + @Valid @ModelAttribute("member") Member member, BindingResult bindingResult){ + //세션에 회원데이터가 없으면 home ->의도적 API접근 막기 위함 + if(loginMember ==null){ + return "home"; + } + if(bindingResult.hasErrors()){ + return "members/updateMemberForm"; + } + // 업데이트 + memberService.update(loginMember.getId(), member); + + return "redirect:/members/logout"; + } + + + +} diff --git a/src/main/java/org/poolc/controller/form/LoginFormController.java b/src/main/java/org/poolc/controller/form/LoginFormController.java new file mode 100644 index 0000000..d880e8d --- /dev/null +++ b/src/main/java/org/poolc/controller/form/LoginFormController.java @@ -0,0 +1,30 @@ +package org.poolc.controller.form; + +import lombok.Data; + +import javax.validation.constraints.NotEmpty; + +public class LoginFormController { + + @NotEmpty + private String loginId; + + @NotEmpty + private String password; + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/org/poolc/controller/session/SessionConst.java b/src/main/java/org/poolc/controller/session/SessionConst.java new file mode 100644 index 0000000..5596c66 --- /dev/null +++ b/src/main/java/org/poolc/controller/session/SessionConst.java @@ -0,0 +1,5 @@ +package org.poolc.controller.session; + +public abstract class SessionConst { + public static final String LOGIN_MEMBER = "loginMember"; +} diff --git a/src/main/java/org/poolc/controller/session/SessionManager.java b/src/main/java/org/poolc/controller/session/SessionManager.java new file mode 100644 index 0000000..7678177 --- /dev/null +++ b/src/main/java/org/poolc/controller/session/SessionManager.java @@ -0,0 +1,69 @@ +package org.poolc.controller.session; + +import org.springframework.stereotype.Component; +import org.springframework.web.util.CookieGenerator; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class SessionManager { + + private static final String SESSION_COOKIE_NAME = "mySessionId"; + private Map sessionStore = new ConcurrentHashMap<>(); + + /** + * 세션 생성 + */ + public void createSession(Object value, HttpServletResponse response){ + + //세션 id 생성 후 값을 세션에 저장 + String sessionId = UUID.randomUUID().toString(); + sessionStore.put(sessionId, value); + + // Cookie mySessionCookie = new Cookie(SESSION_COOKIE_NAME, sessionId); + + CookieGenerator cg = new CookieGenerator(); + cg.setCookieName(SESSION_COOKIE_NAME); + cg.addCookie(response, sessionId); + +// mySessionCookie.setPath("/"); +// response.addCookie(mySessionCookie); + } + + /** + * 세션 조회 ->request로부터 온 Session에 저장해둔 memberID가 있는지 체크/ 있다면 value return + */ + public Object getSession(HttpServletRequest request) { + Cookie sessionCookie = findCookie(request, SESSION_COOKIE_NAME); + if (sessionCookie == null) { + return null; + } + return sessionStore.get(sessionCookie.getValue()); + } + /** + * 세션 만료 + */ + public void expire(HttpServletRequest request) { + Cookie sessionCookie = findCookie(request, SESSION_COOKIE_NAME); + if (sessionCookie != null) { + sessionStore.remove(sessionCookie.getValue()); + } + + } + + private Cookie findCookie(HttpServletRequest request, String cookieName) { + if (request.getCookies() == null) { + return null; + } + return Arrays.stream(request.getCookies()) + .filter(cookie -> cookie.getName().equals(cookieName)) + .findAny() + .orElse(null); + } +} diff --git a/src/main/java/org/poolc/domain/Member.java b/src/main/java/org/poolc/domain/Member.java new file mode 100644 index 0000000..0891da7 --- /dev/null +++ b/src/main/java/org/poolc/domain/Member.java @@ -0,0 +1,113 @@ +package org.poolc.domain; + +import lombok.Data; + +import javax.persistence.*; +import javax.validation.constraints.NotEmpty; + +@Entity //@Data가 들어왔을때 전체 coverage 가능한 테스트는 어떻게 할까? +public class Member { + + //this is PK + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "USERID") @NotEmpty + private String userId; + + @Column(name = "NAME") @NotEmpty + private String name; + + @Column(name = "PASSWORD") @NotEmpty + private String passWord; + + @Column(name = "EMAIL") @NotEmpty + private String email; + + @Column(name = "PHONENUM") @NotEmpty + private String phoneNum; + + @Column(name = "DEPARTMENT") @NotEmpty + private String department; + + @Column(name = "STUDENTID") @NotEmpty + private String studentId; + + public Member(){} + + public Member( String userId, String name, String passWord, + String email, String phoneNum, String department, String studentId) { + this.userId = userId; + this.name = name; + this.passWord = passWord; + this.email = email; + this.phoneNum = phoneNum; + this.department = department; + this.studentId = studentId; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPassWord() { + return passWord; + } + + public void setPassWord(String passWord) { + this.passWord = passWord; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhoneNum() { + return phoneNum; + } + + public void setPhoneNum(String phoneNum) { + this.phoneNum = phoneNum; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + + public String getStudentId() { + return studentId; + } + + public void setStudentId(String studentId) { + this.studentId = studentId; + } + +} diff --git a/src/main/java/org/poolc/repository/JpaMemberRepository.java b/src/main/java/org/poolc/repository/JpaMemberRepository.java new file mode 100644 index 0000000..a0e280f --- /dev/null +++ b/src/main/java/org/poolc/repository/JpaMemberRepository.java @@ -0,0 +1,47 @@ +package org.poolc.repository; + +import org.poolc.domain.Member; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityManager; +import java.util.List; +import java.util.Optional; + +@Transactional +public class JpaMemberRepository implements MemberRepository{ + + private final EntityManager em; + + public JpaMemberRepository(EntityManager em) { + this.em = em; + } + + @Override + public Member save(Member member) { + em.persist(member); + return member; + } + + @Override + public Optional findById(Long id) { + Member member = em.find(Member.class, id); + return Optional.ofNullable(member); + } + + @Override + public Optional findByUserId(String userId) { + List result = em.createQuery("select m from Member m where m.userId = :userId", + Member.class) + .setParameter("userId", userId) + .getResultList(); + return result.stream().findAny(); + } + + @Override + public List findAll() { + return em.createQuery("select m from Member m", Member.class) + .getResultList(); + } + +} diff --git a/src/main/java/org/poolc/repository/MemberRepository.java b/src/main/java/org/poolc/repository/MemberRepository.java new file mode 100644 index 0000000..d6da963 --- /dev/null +++ b/src/main/java/org/poolc/repository/MemberRepository.java @@ -0,0 +1,13 @@ +package org.poolc.repository; + +import org.poolc.domain.Member; + +import java.util.List; +import java.util.Optional; + +public interface MemberRepository { + Member save(Member member); + Optional findById(Long id); + Optional findByUserId(String userId); + List findAll(); +} diff --git a/src/main/java/org/poolc/repository/MemoryMemberRepository.java b/src/main/java/org/poolc/repository/MemoryMemberRepository.java new file mode 100644 index 0000000..983c594 --- /dev/null +++ b/src/main/java/org/poolc/repository/MemoryMemberRepository.java @@ -0,0 +1,41 @@ +package org.poolc.repository; + +import org.poolc.domain.Member; + +import java.util.*; + +public class MemoryMemberRepository implements MemberRepository{ + + //저장공간 ->key:회원id/value:Member static으로 공유변수일때는 동시성 문제때문에 concurrnetHashmap써야함 + private static Map store = new HashMap<>(); + //키값을 생성해주는얘, 애도 동시성 문제때문에 atom long등을 해주어야함 + private static long sequence = 0L; + + @Override + public Member save(Member member) { + member.setId(++sequence); + store.put(member.getId(),member); + return member; + } + + @Override + public Optional findById(Long id) { + return Optional.ofNullable(store.get(id)); + } + + @Override + public Optional findByUserId(String userId) { + return store.values().stream().filter(member -> member.getUserId().equals(userId)) + .findAny(); + } + + @Override + public List findAll() { + return new ArrayList<>(store.values()); + } + + + public void clearStore(){ + store.clear(); + } +} diff --git a/src/main/java/org/poolc/service/LoginServiceImpl.java b/src/main/java/org/poolc/service/LoginServiceImpl.java new file mode 100644 index 0000000..3fc64ea --- /dev/null +++ b/src/main/java/org/poolc/service/LoginServiceImpl.java @@ -0,0 +1,31 @@ +package org.poolc.service; + +import lombok.RequiredArgsConstructor; +import org.poolc.domain.Member; +import org.poolc.repository.MemberRepository; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class LoginServiceImpl { + + private final MemberRepository memberRepository; + private final PasswordEncoder passwordEncoder; + + /** + * + * @return null->로그인 실패 + */ + public Member login(String loginId, String password){ + //로그인 시도한 아이디가 있는지 체크 + Optional findMember = memberRepository.findByUserId(loginId); + //암호화된 비밀번호화 Match 되었는지 체크 + return findMember.filter(m->passwordEncoder.matches(password,m.getPassWord())) + .orElse(null); + + } + +} diff --git a/src/main/java/org/poolc/service/MemberService.java b/src/main/java/org/poolc/service/MemberService.java new file mode 100644 index 0000000..5730697 --- /dev/null +++ b/src/main/java/org/poolc/service/MemberService.java @@ -0,0 +1,16 @@ +package org.poolc.service; + +import org.poolc.domain.Member; + +import java.util.List; +import java.util.Optional; + +public interface MemberService { + + Long join(Member member); + List findMembers(); + Optional findOne(Long memberId); + Optional findByUserId(String userId); + Long update(Long id, Member afterMember); + +} diff --git a/src/main/java/org/poolc/service/MemberServiceImpl.java b/src/main/java/org/poolc/service/MemberServiceImpl.java new file mode 100644 index 0000000..c2be2e7 --- /dev/null +++ b/src/main/java/org/poolc/service/MemberServiceImpl.java @@ -0,0 +1,72 @@ +package org.poolc.service; + +import org.poolc.domain.Member; +import org.poolc.repository.MemberRepository; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + + + +public class MemberServiceImpl implements MemberService{ + + private final MemberRepository memberRepository; + private final PasswordEncoder bCryptPasswordEncoder; + + //member Repository를 외부에서 넣어주도록 설계. + public MemberServiceImpl(MemberRepository memberRepository, PasswordEncoder bCryptPasswordEncoder) { + this.memberRepository = memberRepository; + this.bCryptPasswordEncoder = bCryptPasswordEncoder; + } + + @Override + public Long join(Member member) { + validateDuplicateMember(member); //중복회원 검증 후 비밀번호 암호화해서 저장 + member.setPassWord(bCryptPasswordEncoder.encode(member.getPassWord())); + memberRepository.save(member); + + return member.getId(); + } + + @Override + public List findMembers() { + return memberRepository.findAll(); + } + + @Override + public Optional findOne(Long id) { + return memberRepository.findById(id); + } + + @Override + public Optional findByUserId(String userId){ + return memberRepository.findByUserId(userId); + } + + private void validateDuplicateMember(Member member){ + //ifPresent-> 해당 userID를 가지고 있는 user가 있으면 예외 발생 + memberRepository.findByUserId(member.getUserId()) + .ifPresent(m->{ + throw new IllegalStateException("이미 존재하는 회원입니다."); + }); + } + + @Override @Transactional //DB에서 자동으로 수정된 정보 반영 + public Long update(Long id, Member afterMember) { + validateDuplicateMember(afterMember); + afterMember.setPassWord(bCryptPasswordEncoder.encode(afterMember.getPassWord())); + Member beforeMember = memberRepository.findById(id).get(); + beforeMember.setEmail(afterMember.getEmail()); + beforeMember.setUserId(afterMember.getUserId()); + beforeMember.setName(afterMember.getName()); + beforeMember.setPassWord(afterMember.getPassWord()); + beforeMember.setPhoneNum(afterMember.getPhoneNum()); + beforeMember.setDepartment(afterMember.getDepartment()); + beforeMember.setStudentId(afterMember.getStudentId()); + + return beforeMember.getId(); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8b13789..b71bfa0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1 +1,8 @@ - +spring.security.user.name = sjb7773 +spring.security.user.password =1234 +server.servlet.session.tracking-modes=cookie +spring.datasource.url=jdbc:h2:tcp://localhost/~/test +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 0000000..355ea40 --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,11 @@ + + + + + + + +Hello +hello + + \ No newline at end of file diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 0000000..098819f --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,18 @@ + + + + +
+
+

Hello Spring JB

+

회원 기능

+

+ 로그인 + 회원 가입 + 회원 목록 +

+
+
+ + + diff --git a/src/main/resources/templates/loginHome.html b/src/main/resources/templates/loginHome.html new file mode 100644 index 0000000..89c4d54 --- /dev/null +++ b/src/main/resources/templates/loginHome.html @@ -0,0 +1,19 @@ + + + + +
+
+

Hello Spring JB

+

로그인 사용자 이름

+

회원 기능

+
+ + 회원 정보 수정 +
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/members/createMemberForm.html b/src/main/resources/templates/members/createMemberForm.html new file mode 100644 index 0000000..52a9de8 --- /dev/null +++ b/src/main/resources/templates/members/createMemberForm.html @@ -0,0 +1,40 @@ + + + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/members/loginMemberForm.html b/src/main/resources/templates/members/loginMemberForm.html new file mode 100644 index 0000000..449245a --- /dev/null +++ b/src/main/resources/templates/members/loginMemberForm.html @@ -0,0 +1,19 @@ + + + + +
+
+
+ + +
+
+ + +
+ +
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/members/memberList.html b/src/main/resources/templates/members/memberList.html new file mode 100644 index 0000000..e40fce6 --- /dev/null +++ b/src/main/resources/templates/members/memberList.html @@ -0,0 +1,24 @@ + + + + +
+
+ + + + + + + + + + + + + +
#이름
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/members/updateMemberForm.html b/src/main/resources/templates/members/updateMemberForm.html new file mode 100644 index 0000000..89b5d75 --- /dev/null +++ b/src/main/resources/templates/members/updateMemberForm.html @@ -0,0 +1,40 @@ + + + +

회원 수정란

+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+ + \ No newline at end of file diff --git a/src/test/java/org/poolc/controller/ControllerTest.java b/src/test/java/org/poolc/controller/ControllerTest.java new file mode 100644 index 0000000..84d5a9e --- /dev/null +++ b/src/test/java/org/poolc/controller/ControllerTest.java @@ -0,0 +1,140 @@ +package org.poolc.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.poolc.controller.form.LoginFormController; +import org.poolc.controller.session.SessionConst; +import org.poolc.controller.session.SessionManager; +import org.poolc.domain.Member; +import org.poolc.repository.MemberRepository; +import org.poolc.service.LoginServiceImpl; +import org.poolc.service.MemberService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.transaction.annotation.Transactional; + +import javax.servlet.http.HttpServletRequest; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +//@WebMvcTest(HomeController.class) +@AutoConfigureMockMvc @SpringBootTest @Transactional +public class ControllerTest { + + + @Autowired + private SessionManager sessionManager; + + + @Autowired + private MemberService memberService; + @Autowired + private LoginServiceImpl loginService; + + ObjectMapper objectMapper = new ObjectMapper(); + + + @Autowired + private MockMvc mvc; + + + @Test + public void home() throws Exception { + + // perform() - 요청을 전송하는 역할, 결과로 ResultActions객체를 받고, 이 객체에서 리턴값을 검증하고 확인할 수 있는 andExcpect()메소드를 제공함. + mvc.perform(MockMvcRequestBuilders.get("/")) + //상태코드 -> isOk()는 상태코드 200 + .andExpect(status().isOk()) + // 응답본문의 내용을 검증함 -> Controller에서 'home'을 리턴하기 때문에 이값이 맞는지 검증한다. + .andExpect(view().name("home")); + } + + @Test + public void loginHome() throws Exception { + + Member member =new Member("123","김","123","123","123", + "123","123"); + memberService.join(member); + loginService.login("123", "123"); + MockHttpServletResponse response = new MockHttpServletResponse(); + sessionManager.createSession(member, response); + //request에 응답 쿠키 저장 + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpSession session = new MockHttpSession(); + //세션에 로그인 회원 정보 보관. + session.setAttribute(SessionConst.LOGIN_MEMBER, member); + + + mvc.perform(MockMvcRequestBuilders.get("/") + .session(session)) + .andExpect(status().isOk()) + .andExpect(view().name("loginHome")); + } + + @Test + public void loginGet() throws Exception { + + mvc.perform(MockMvcRequestBuilders.get("/members/login")) + .andExpect(status().isOk()) + .andExpect(view().name("members/loginMemberForm")); + } + + @Test + public void loginPost() throws Exception { + Member member =new Member("123","김","123","123","123", + "123","123"); + memberService.join(member); + LoginFormController form = new LoginFormController(); + form.setLoginId("1234"); + form.setPassword("1234"); + mvc.perform(post("/members/login")) + .andExpect(status().isOk()) + //나중에 변경 + .andExpect(view().name("members/loginMemberForm")); + + mvc.perform(post("/members/login") + .flashAttr("loginForm",form)) + .andExpect(status().isOk()) + //나중에 변경 + .andExpect(view().name("members/loginMemberForm")); + form.setLoginId("123"); + form.setPassword("123"); + mvc.perform(post("/members/login") + .flashAttr("loginForm",form)) + //나중에 변경 + .andExpect(view().name("redirect:/")); + } + + @Test + public void logoutGetAndPost() throws Exception { + Member member =new Member("123","김","123","123","123", + "123","123"); + memberService.join(member); + loginService.login("123", "123"); + + mvc.perform(MockMvcRequestBuilders.get("/members/logout")) + .andExpect(view().name("redirect:/")); + + MockHttpServletResponse response = new MockHttpServletResponse(); + sessionManager.createSession(member, response); + MockHttpSession session = new MockHttpSession(); + session.setAttribute(SessionConst.LOGIN_MEMBER, member); + + mvc.perform(post("/members/logout") + .session(session)) + .andExpect(view().name("redirect:/")); + } + +} diff --git a/src/test/java/org/poolc/controller/MemberControllerTest.java b/src/test/java/org/poolc/controller/MemberControllerTest.java new file mode 100644 index 0000000..e810fe2 --- /dev/null +++ b/src/test/java/org/poolc/controller/MemberControllerTest.java @@ -0,0 +1,153 @@ +package org.poolc.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.poolc.controller.session.SessionConst; +import org.poolc.controller.session.SessionManager; +import org.poolc.domain.Member; +import org.poolc.repository.MemberRepository; +import org.poolc.service.LoginServiceImpl; +import org.poolc.service.MemberService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.ModelAttribute; + +import javax.servlet.http.HttpSession; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +@SpringBootTest @Transactional @AutoConfigureMockMvc +public class MemberControllerTest { + + + @Autowired + private MemberService memberService; + @Autowired + private LoginServiceImpl loginService; + @Autowired + SessionManager sessionManager; + + ObjectMapper objectMapper = new ObjectMapper(); + + @Autowired + private MockMvc mvc; + + @Test + public void createFormGet() throws Exception { + + mvc.perform(MockMvcRequestBuilders.get("/members/new")) + .andExpect(status().isOk()) + .andExpect(view().name("members/createMemberForm")); + } + + @Test + public void createFormPost() throws Exception { + mvc.perform(MockMvcRequestBuilders.post("/members/new")) + .andExpect(status().isOk()) + .andExpect(view().name("members/createMemberForm")); + + Member member =new Member("123","김","123","123","123", + "123","123"); + memberService.join(member); + + Member member2 =new Member("123","김","123","123","123", + "123","123"); + mvc.perform(MockMvcRequestBuilders.post("/members/new") + .flashAttr("member", member2)) + .andExpect(status().isOk()) + .andExpect(view().name("members/createMemberForm")); + + member2.setUserId("456"); + member2.setPassWord("456"); + member2.setName("성"); + mvc.perform(MockMvcRequestBuilders.post("/members/new") + .flashAttr("member", member2)) + .andExpect(view().name("redirect:/")); + } + + @Test + public void MemberListGet() throws Exception { + + mvc.perform(MockMvcRequestBuilders.get("/members")) + .andExpect(status().isOk()) + .andExpect(view().name("members/memberList")); + } + + @Test + public void updateFormGet() throws Exception { + + Member member =new Member("123","김","123","123","123", + "123","123"); + memberService.join(member); + loginService.login("123", "123"); + MockHttpServletResponse response = new MockHttpServletResponse(); + sessionManager.createSession(member, response); + + mvc.perform(MockMvcRequestBuilders.get("/members/update")) + .andExpect(status().isOk()) + .andExpect(view().name("home")); + //request에 응답 쿠키 저장 + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpSession session = new MockHttpSession(); + //세션에 로그인 회원 정보 보관. + session.setAttribute(SessionConst.LOGIN_MEMBER, member); + + mvc.perform(MockMvcRequestBuilders.get("/members/update") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(member)) + .session(session)) + .andExpect(status().isOk()) + .andExpect(view().name("members/updateMemberForm")); + } + + @Test @Transactional + public void updateFormPost() throws Exception { + Member member =new Member("123","김","123","123","123", + "123","123"); + memberService.join(member); + loginService.login("123", "123"); + MockHttpServletResponse response = new MockHttpServletResponse(); + sessionManager.createSession(member, response); + + mvc.perform(MockMvcRequestBuilders.post("/members/update")) + .andExpect(status().isOk()) + .andExpect(view().name("home")); + + //request에 응답 쿠키 저장 + MockHttpServletRequest request = new MockHttpServletRequest(); + + MockHttpSession session = new MockHttpSession(); + //세션에 로그인 회원 정보 보관. + session.setAttribute(SessionConst.LOGIN_MEMBER, member); + + mvc.perform(MockMvcRequestBuilders.post("/members/update") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(member)) + .session(session)) + .andExpect(status().isOk()) + .andExpect(view().name("members/updateMemberForm")); + + + + Member member2 =new Member("1234","김","1234","1234","1234", + "1234","1234"); + + mvc.perform(MockMvcRequestBuilders.post("/members/update") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(member)) + .session(session) + .flashAttr("member", member2)) + .andExpect(view().name("redirect:/members/logout")); + } +} diff --git a/src/test/java/org/poolc/controller/form/LoginFormControllerTest.java b/src/test/java/org/poolc/controller/form/LoginFormControllerTest.java new file mode 100644 index 0000000..cab4844 --- /dev/null +++ b/src/test/java/org/poolc/controller/form/LoginFormControllerTest.java @@ -0,0 +1,33 @@ +package org.poolc.controller.form; + +import org.junit.jupiter.api.Test; +import org.poolc.domain.Member; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +class LoginFormControllerTest { + + @Test + void getLoginId() { + LoginFormController form = new LoginFormController(); + form.setLoginId("123"); + assertThat("123").isEqualTo(form.getLoginId()); + } + + @Test + void getPassword() { + LoginFormController form = new LoginFormController(); + form.setPassword("123"); + assertThat("123").isEqualTo(form.getPassword()); + } + + @Test + void testEquals() { + LoginFormController form = new LoginFormController(); + LoginFormController form1 = form; + assertThat(form.equals(form1)).isEqualTo(true); + } + + +} \ No newline at end of file diff --git a/src/test/java/org/poolc/controller/session/SessionManagerTest.java b/src/test/java/org/poolc/controller/session/SessionManagerTest.java new file mode 100644 index 0000000..6a7a230 --- /dev/null +++ b/src/test/java/org/poolc/controller/session/SessionManagerTest.java @@ -0,0 +1,45 @@ +package org.poolc.controller.session; + + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.poolc.domain.Member; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; + +import static org.assertj.core.api.Assertions.assertThat; + +class SessionManagerTest { + SessionManager sessionManager = new SessionManager(); + + @Test + void sessionTest(){ + + MockHttpServletResponse response = new MockHttpServletResponse(); + Member member = new Member(); + sessionManager.createSession(member, response); + + //request에 응답 쿠키 저장 + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setCookies(response.getCookies()); + + //session 조회 + Object result = sessionManager.getSession(request); + assertThat(result).isEqualTo(member); + + //session 만료 + sessionManager.expire(request); + Object expired = sessionManager.getSession(request); + assertThat(expired).isEqualTo(null); + } + + @Test + void nullSessionTest(){ + MockHttpServletRequest request = new MockHttpServletRequest(); + assertThat(sessionManager.getSession(request)).isNull(); + sessionManager.expire(request); + } +} diff --git a/src/test/java/org/poolc/domain/MemberTest.java b/src/test/java/org/poolc/domain/MemberTest.java new file mode 100644 index 0000000..5d62bf1 --- /dev/null +++ b/src/test/java/org/poolc/domain/MemberTest.java @@ -0,0 +1,92 @@ +package org.poolc.domain; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + + +class MemberTest { + + @Test + void constructorTest(){ + Member member =new Member(); + member.setUserId("123"); + member.setPassWord("123"); + member.setName("123"); + member.setDepartment("123"); + member.setEmail("123"); + member.setStudentId("123"); + member.setPhoneNum("123"); + Member member2 = new Member("123","123","123", + "123","123","123","123"); + assertThat(member.getUserId()).isEqualTo(member2.getUserId()); + } + + @Test + void getId() { + Member member = new Member(); + member.setId(99999L); + assertThat(99999L).isEqualTo(member.getId()); + } + + @Test + void getUserId() { + Member member = new Member(); + member.setUserId("123"); + assertThat("123").isEqualTo(member.getUserId()); + } + + @Test + void getName() { + Member member = new Member(); + member.setName("123"); + assertThat("123").isEqualTo(member.getName()); + } + + @Test + void getPassWord() { + Member member = new Member(); + member.setPassWord("123"); + assertThat("123").isEqualTo(member.getPassWord()); + } + + @Test + void getEmail() { + Member member = new Member(); + member.setEmail("123"); + assertThat("123").isEqualTo(member.getEmail()); + } + + @Test + void getPhoneNum() { + Member member = new Member(); + member.setPhoneNum("123"); + assertThat("123").isEqualTo(member.getPhoneNum()); + } + + @Test + void getDepartment() { + Member member = new Member(); + member.setDepartment("123"); + assertThat("123").isEqualTo(member.getDepartment()); + } + + @Test + void getStudentId() { + Member member = new Member(); + member.setStudentId("123"); + assertThat("123").isEqualTo(member.getStudentId()); + } + + + + @Test + void testEquals() { + Member member = new Member(); + Member member1 = member; + assertThat(member1.equals(member)).isEqualTo(true); + } + + +} \ No newline at end of file diff --git a/src/test/java/org/poolc/repository/JpaMemberRepositoryIntegrationTest.java b/src/test/java/org/poolc/repository/JpaMemberRepositoryIntegrationTest.java new file mode 100644 index 0000000..a0601c8 --- /dev/null +++ b/src/test/java/org/poolc/repository/JpaMemberRepositoryIntegrationTest.java @@ -0,0 +1,64 @@ +package org.poolc.repository; + +import org.junit.jupiter.api.Test; +import org.poolc.domain.Member; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +@Transactional @SpringBootTest +public class JpaMemberRepositoryIntegrationTest { + + @Autowired + MemberRepository repository; + + @Test + public void saveAndFindById(){ + //given + Member member =new Member("star123","홍길동","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + + //when + repository.save(member); + + //then + Member result = repository.findById(member.getId()).get(); + assertThat(member).isEqualTo(result); + } + + + @Test + public void findByUserId(){ + + Member member1 =new Member("star1234","spring1","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + repository.save(member1); + + Member member2 =new Member("star1234","spring2","good2345!","123@1235","010-1212-12123", + "컴퓨터과학","20121212123"); + repository.save(member2); + + Member result = repository.findByUserId("star1234").get(); + assertThat(result).isEqualTo(member1); + } + + + @Test + public void findAll(){ + Member member1 =new Member("star1234","spring1","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + repository.save(member1); + + Member member2 =new Member("star1234","spring2","good2345!","123@1235","010-1212-12123", + "컴퓨터과학","20121212123"); + repository.save(member2); + + List result = repository.findAll(); + assertThat(result.size()).isEqualTo(2); + } +} diff --git a/src/test/java/org/poolc/repository/MemoryMemberRepositoryTest.java b/src/test/java/org/poolc/repository/MemoryMemberRepositoryTest.java new file mode 100644 index 0000000..a051dce --- /dev/null +++ b/src/test/java/org/poolc/repository/MemoryMemberRepositoryTest.java @@ -0,0 +1,65 @@ +package org.poolc.repository; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.poolc.domain.Member; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@Transactional +public class MemoryMemberRepositoryTest { + + MemoryMemberRepository repository = new MemoryMemberRepository(); + + + @AfterEach + public void afterEach(){ + repository.clearStore(); + } + + @Test + public void saveAndFindById(){ + //given + Member member =new Member("star","spring1","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + + //when + repository.save(member); + + //then + Member result = repository.findById(member.getId()).get(); + assertThat(member).isEqualTo(result); + } + + @Test + public void findByUserId(){ + Member member1 =new Member("star1234","sprin","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + Member member2 =new Member("sta2345","spring2","good2345!","123@1235","010-1212-12123", + "컴퓨터과학","20121212123"); + repository.save(member1); + repository.save(member2); + + Member result = repository.findByUserId("star1234").get(); + assertThat(result).isEqualTo(member1); + } + + + @Test + public void findAll(){ + Member member1 =new Member("star2345","spring1","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + repository.save(member1); + + Member member2 =new Member("star1234","spring2","good2345!","123@1235","010-1212-12123", + "컴퓨터과학","20121212123"); + repository.save(member2); + + List result = repository.findAll(); + assertThat(result.size()).isEqualTo(2); + } +} diff --git a/src/test/java/org/poolc/service/MemberServiceImplTest.java b/src/test/java/org/poolc/service/MemberServiceImplTest.java new file mode 100644 index 0000000..c07acb0 --- /dev/null +++ b/src/test/java/org/poolc/service/MemberServiceImplTest.java @@ -0,0 +1,87 @@ +package org.poolc.service; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.poolc.domain.Member; +import org.poolc.repository.MemoryMemberRepository; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MemberServiceImplTest { + + MemoryMemberRepository repository; + MemberService memberService; + PasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();; + + + //매 동작 전전 + @BeforeEach + public void beforeEach(){ + repository = new MemoryMemberRepository(); + memberService = new MemberServiceImpl(repository,bCryptPasswordEncoder); + } + + + @AfterEach + public void afterEach(){ + repository.clearStore(); + } + + @Test + void SuccessJoin() { + Member member =new Member("star123","홍길동","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + + memberService.join(member); + + Member result = repository.findByUserId("star123").get(); + assertThat(result).isEqualTo(member); + } + + @Test + void DuplicateJoin() { + Member member1 =new Member("star12355","홍길동","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + Member member2 =new Member("star12355","홍길동","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + + memberService.join(member1); + Assertions.assertThatThrownBy(()->memberService.join(member2)) + .isInstanceOf(java.lang.IllegalStateException.class); + } + + @Test + void findMembers() { + Member member1 =new Member("star12355","홍길동","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + Member member2 =new Member("star234555","성종빈","good2345!","123@1235","010-1212-12123", + "컴퓨터과학","201814777"); + + memberService.join(member1); + memberService.join(member2); + + List result = repository.findAll(); + assertThat(result.size()).isEqualTo(2); + } + + @Test + void findOne() { + Member member1 =new Member("star12355","홍길동","good1234!","123@123","010-1212-1212", + "컴퓨터과학","2012121212"); + Member member2 =new Member("star234555","성종빈","good2345!","123@1235","010-1212-12123", + "컴퓨터과학","201814777"); + + memberService.join(member1); + memberService.join(member2); + + Member result = memberService.findOne(member2.getId()).get(); + assertThat(result).isEqualTo(member2); + } + +}