Skip to content

Commit

Permalink
Merge pull request #1 from hightuv/회원가입-기능추가
Browse files Browse the repository at this point in the history
로그인, 회원가입 기능추가
  • Loading branch information
hightuv authored Mar 24, 2024
2 parents 475b4df + 55119b7 commit 59bd7d9
Show file tree
Hide file tree
Showing 13 changed files with 369 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/login", "/register").permitAll()
.requestMatchers("/login", "/register", "/css/**", "/images/**")
.permitAll()
.anyRequest().authenticated()
)
.formLogin(formLogin -> formLogin
Expand Down
51 changes: 37 additions & 14 deletions src/main/java/com/example/WebOrder/controller/LoginController.java
Original file line number Diff line number Diff line change
@@ -1,62 +1,85 @@
package com.example.WebOrder.controller;

import com.example.WebOrder.dto.LoginDto;
import com.example.WebOrder.dto.RegisterDto;
import com.example.WebOrder.dto.LoginFormDto;
import com.example.WebOrder.dto.UserFormDto;
import com.example.WebOrder.entity.User;
import com.example.WebOrder.service.LoginService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Slf4j
@Controller
public class LoginController {
private final LoginService loginService;
private final PasswordEncoder passwordEncoder;

public LoginController(LoginService loginService) {
public LoginController(LoginService loginService, PasswordEncoder passwordEncoder) {
this.loginService = loginService;
this.passwordEncoder = passwordEncoder;
}

@GetMapping("/index")
public String getIndex(){
return "/html/index";
}
@GetMapping("/login")
public String getLoginForm(){
public String getLoginForm(@ModelAttribute("loginFormDto") LoginFormDto dto){
log.info("로그인 폼 소환");
return "/html/login";
return "html/loginForm";
}

@PostMapping("/login")
public String login(LoginDto dto){
public String login(@Valid @ModelAttribute ("loginFormDto") LoginFormDto dto, BindingResult bindingResult){
log.info("로그인 시도");
if (loginService.isLoginAttemptValid(dto)){
log.info("로그인 성공");
return "/html/index";
return "html/index";
}
else {
log.info("로그인 실패");
return "redirect:/login?error=true";
bindingResult.reject("loginFail", "아이디 또는 비밀번호가 맞지 않습니다.");
return "html/loginForm";
}
}

@GetMapping("/register")
public String getRegisterForm(){
public String registerForm(@ModelAttribute("userFormDto") UserFormDto dto) {
log.info("회원가입 폼 소환");
return "/html/register";
return "html/registerForm";
}

@PostMapping("/register")
public String register(RegisterDto dto){
public String register(@Valid UserFormDto dto, BindingResult bindingResult){
log.info("회원가입 시도");
if (loginService.usernameExists(dto.getUsername())){
if (bindingResult.hasErrors()) {
log.info("회원가입 실패");
return "html/registerForm";
}

if (loginService.findByUsername(dto.getUsername()).isPresent()){
log.info("username 중복");
return "redirect:/register?error=true";
}

if (!dto.getPassword().equals(dto.getPasswordCheck())) {
bindingResult.rejectValue("passwordCheck", "passwordNotSame", "비밀번호를 다시 확인해주세요.");
return "html/registerForm";
}
else {
log.info("회원가입 성공");
loginService.createUser(dto);
return "redirect:/login";
User user = new User();
user.setUsername(dto.getUsername());
user.setPassword(passwordEncoder.encode(dto.getPassword()));
user.setName(dto.getName());
loginService.join(user);
return "redirect:/";
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.example.WebOrder.dto;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class LoginDto {
public class LoginFormDto {
@NotEmpty
private String username;
@NotEmpty
private String password;
}
23 changes: 23 additions & 0 deletions src/main/java/com/example/WebOrder/dto/UserFormDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.WebOrder.dto;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;

@Getter
@Setter
public class UserFormDto {
@NotEmpty(message = "아이디는 필수 입력 값입니다.")
private String username;

@NotEmpty(message = "비밀번호는 필수 입력 값입니다.")
@Length(min = 8, max = 16, message = "비밀번호는 8자 이상, 16자 이하로 입력해주세요.")
private String password;

@NotEmpty(message = "비밀번호를 한 번 더 입력해주세요.")
private String passwordCheck;

@NotEmpty(message = "이름은 필수 입력 값입니다.")
private String name;
}
6 changes: 6 additions & 0 deletions src/main/java/com/example/WebOrder/entity/Seat.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import java.util.ArrayList;
import java.util.List;

import static jakarta.persistence.FetchType.LAZY;

@Entity
@Getter @Setter
public class Seat {
Expand All @@ -17,6 +19,10 @@ public class Seat {

private String name;

@ManyToOne(fetch = LAZY)
@JoinColumn(name = "user_id")
private User user;

@OneToMany(mappedBy = "seat", cascade = CascadeType.ALL)
private List<Order> orders = new ArrayList<>();

Expand Down
5 changes: 4 additions & 1 deletion src/main/java/com/example/WebOrder/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@Entity
@Getter
@Setter
@ToString
@ToString(of = {"id", "username"})
@EqualsAndHashCode
public class User implements UserDetails {
@Id
Expand All @@ -26,6 +26,9 @@ public class User implements UserDetails {
@Column(nullable = false)
private String password;

@Column(nullable = false)
private String name;

@OneToMany(mappedBy = "user")
private List<Seat> seats = new ArrayList<>();

Expand Down
37 changes: 19 additions & 18 deletions src/main/java/com/example/WebOrder/service/LoginService.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package com.example.WebOrder.service;

import com.example.WebOrder.dto.LoginDto;
import com.example.WebOrder.dto.RegisterDto;
import com.example.WebOrder.dto.LoginFormDto;
import com.example.WebOrder.dto.UserFormDto;
import com.example.WebOrder.entity.User;
import com.example.WebOrder.repository.UserRepository;
import org.apache.tomcat.websocket.AuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -26,34 +25,23 @@ public LoginService(UserRepository userRepository, PasswordEncoder passwordEncod
this.passwordEncoder = passwordEncoder;
}




@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findByUsername(username).get();
}

public Boolean isLoginAttemptValid(LoginDto dto){
Optional<User> optionalUser = userRepository.findByUsername(dto.getUsername());
public Boolean isLoginAttemptValid(LoginFormDto dto){
Optional<User> findUser = userRepository.findByUsername(dto.getUsername());

if (optionalUser.isEmpty()) throw new UsernameNotFoundException("유저가 존재하지 않습니다.");
if (findUser.isEmpty()) throw new UsernameNotFoundException("유저가 존재하지 않습니다.");

User user = optionalUser.get();
User user = findUser.get();

if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) throw new RuntimeException("비밀번호가 일치하지 않습니다.");

return true;
}

public User createUser(RegisterDto dto){
User user = new User();
user.setUsername(dto.getUsername());
user.setPassword(passwordEncoder.encode(dto.getPassword()));

return userRepository.save(user);
}

public Boolean usernameExists(String username){
return userRepository.existsByUsername(username);
}
Expand All @@ -66,4 +54,17 @@ public Boolean isCurrentUserAuthenticated(Long userId){
}
return false;
}

/**
* 회원가입
*/
public Long join(User user) {
userRepository.save(user);
return user.getId();
}

public Optional<User> findByUsername(String username) {
return userRepository.findByUsername(username);
}
}

82 changes: 82 additions & 0 deletions src/main/resources/static/css/loginForm.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
.body {
overflow:hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width:100vw;
height:100vh;
}
.logo {
background-color:rgba(157.25000202655792, 157.25000202655792, 157.25000202655792, 1);
width:130px;
height:130px;
margin-bottom: 20px;
}
.login-form {
width:320px;
height:auto;
position:relative;
margin-top: 20px;
}
.form-group {
width:320px;
height:79px;
position:relative;
margin-top:15px;
}
.form-label {
color:rgba(64.00000378489494, 64.00000378489494, 64.00000378489494, 1);
position:relative;
font-family:Noto Sans KR, sans-serif;
text-align:left;
font-size:16px;
letter-spacing:0;
}
.form-input-text {
background-color: rgba(255, 255, 255, 1);
width: 320px;
height: 50px;
position: relative;
font-family: Noto Sans KR, sans-serif;
text-align: left;
font-size: 14px;
border-radius: 5px;
border: 1px solid rgba(174.00000482797623, 174.00000482797623, 174.00000482797623, 1);
}

.login-button {
background-color:rgba(91.46796986460686, 96.86175003647804, 226.31249696016312, 1);
width:320px;
height:55px;
color:rgba(255, 255, 255, 1);
font-family:Noto Sans KR, sans-serif;
text-align:center;
font-size:16px;
letter-spacing:0;
position:relative;
margin-top: 20%;
}
.global-error {
border-color: #dc3545;
color: #dc3545;
font-family:Noto Sans KR, sans-serif;
font-size:12px;
letter-spacing:0;
}
.ask-register {
color:rgba(102.00000151991844, 102.00000151991844, 102.00000151991844, 1);
font-family:Noto Sans KR, sans-serif;
font-size:16px;
letter-spacing:0;
display: flex;
align-items: center;
position:relative;
margin-top: 10%;
}
Loading

0 comments on commit 59bd7d9

Please sign in to comment.