-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
#10 auth service
- Loading branch information
Showing
15 changed files
with
323 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
src/main/java/com/book/backend/domain/auth/controller/AuthController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
package com.book.backend.domain.auth.controller; | ||
|
||
import com.book.backend.domain.auth.dto.LoginDto; | ||
import com.book.backend.domain.auth.dto.SignupDto; | ||
import com.book.backend.domain.auth.service.AuthService; | ||
import com.book.backend.domain.user.dto.UserDto; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.validation.Valid; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.web.bind.annotation.*; | ||
|
||
@RestController | ||
@RequestMapping("/api/auth") | ||
@RequiredArgsConstructor | ||
@Slf4j | ||
public class AuthController { | ||
|
||
private final AuthService authService; | ||
|
||
@PostMapping("/signup") | ||
public ResponseEntity<UserDto> signup(@Valid @RequestBody SignupDto signupDto) { | ||
log.info("signup 호출"); | ||
UserDto userDto = authService.signup(signupDto); | ||
return ResponseEntity.ok(userDto); | ||
} | ||
|
||
@PostMapping("/login") | ||
public ResponseEntity<UserDto> login(@Valid @RequestBody LoginDto loginDto) { | ||
log.info("login 호출"); | ||
UserDto userDto = authService.login(loginDto); | ||
return ResponseEntity.ok(userDto); | ||
} | ||
|
||
@PostMapping("/logout") | ||
public ResponseEntity<Void> logout(HttpServletRequest request) { | ||
log.info("logout 호출"); | ||
request.getSession().invalidate(); | ||
SecurityContextHolder.clearContext(); | ||
return new ResponseEntity<>(HttpStatus.OK); | ||
} | ||
|
||
@DeleteMapping("/delete") | ||
public ResponseEntity<Void> deleteAccount(HttpServletRequest request) { | ||
log.info("deleteAccount 호출"); | ||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); | ||
String loginId = authentication.getName(); | ||
|
||
authService.deleteAccountByLoginId(loginId); | ||
request.getSession().invalidate(); | ||
SecurityContextHolder.clearContext(); | ||
|
||
return new ResponseEntity<>(HttpStatus.NO_CONTENT); | ||
} | ||
} |
17 changes: 17 additions & 0 deletions
17
src/main/java/com/book/backend/domain/auth/dto/LoginDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package com.book.backend.domain.auth.dto; | ||
|
||
import jakarta.validation.constraints.NotBlank; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
import lombok.Setter; | ||
|
||
@Getter | ||
@Setter | ||
@NoArgsConstructor | ||
public class LoginDto { | ||
@NotBlank(message = "아이디는 필수 입력값입니다.") | ||
private String loginId; | ||
|
||
@NotBlank(message = "비밀번호는 필수 입력값입니다.") | ||
private String password; | ||
} |
40 changes: 40 additions & 0 deletions
40
src/main/java/com/book/backend/domain/auth/dto/SignupDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package com.book.backend.domain.auth.dto; | ||
|
||
import jakarta.validation.constraints.Email; | ||
import jakarta.validation.constraints.NotBlank; | ||
import jakarta.validation.constraints.Past; | ||
import jakarta.validation.constraints.Pattern; | ||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
import lombok.Setter; | ||
|
||
import java.time.LocalDate; | ||
|
||
@Getter | ||
@Setter | ||
@NoArgsConstructor | ||
public class SignupDto { | ||
@NotBlank(message = "아이디는 필수 입력값입니다.") | ||
private String loginId; | ||
|
||
@NotBlank(message = "닉네임은 필수 입력값입니다.") | ||
private String nickname; | ||
|
||
@Pattern(regexp = "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\\W)(?=\\S+$).{8,16}", | ||
message = "비밀번호는 숫자, 영문자, 특수문자를 포함한 8~16자리여야 합니다.") | ||
private String password; | ||
|
||
@NotBlank(message = "성별은 필수 입력값입니다.") | ||
@Pattern(regexp = "NOT_SELECTED|MAN|WOMAN", message = "성별은 NOT_SELECTED, MAN, WOMAN 중 하나여야 합니다.") | ||
private String gender; | ||
|
||
@Past(message = "현재 날짜보다 이전 날짜여야 합니다.") | ||
private LocalDate birthDate; | ||
|
||
@Email(message = "유효한 이메일 주소여야 합니다.") | ||
private String email; | ||
|
||
@Pattern(regexp = "010-\\d{4}-\\d{4}", message = "전화번호는 010-XXXX-XXXX 형태여야 합니다.") | ||
private String phone; | ||
|
||
} |
32 changes: 32 additions & 0 deletions
32
src/main/java/com/book/backend/domain/auth/mapper/AuthMapper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package com.book.backend.domain.auth.mapper; | ||
|
||
import com.book.backend.domain.auth.dto.SignupDto; | ||
import com.book.backend.domain.user.entity.Gender; | ||
import com.book.backend.domain.user.entity.User; | ||
import lombok.RequiredArgsConstructor; | ||
import org.modelmapper.ModelMapper; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class AuthMapper { | ||
|
||
private final ModelMapper mapper; | ||
private final PasswordEncoder passwordEncoder; | ||
|
||
public User convertToUser(SignupDto signupDto) { | ||
User user = mapper.map(signupDto, User.class); | ||
user.setGender(convertStringToGender(signupDto.getGender())); | ||
user.setPassword(passwordEncoder.encode(signupDto.getPassword())); | ||
return user; | ||
} | ||
|
||
private Gender convertStringToGender(String gender) { | ||
return switch (gender) { | ||
case "MAN" -> Gender.G1; | ||
case "WOMAN" -> Gender.G2; | ||
default -> Gender.G0; | ||
}; | ||
} | ||
} |
73 changes: 73 additions & 0 deletions
73
src/main/java/com/book/backend/domain/auth/service/AuthService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package com.book.backend.domain.auth.service; | ||
|
||
import com.book.backend.domain.auth.dto.LoginDto; | ||
import com.book.backend.domain.auth.dto.SignupDto; | ||
import com.book.backend.domain.auth.mapper.AuthMapper; | ||
import com.book.backend.domain.user.dto.UserDto; | ||
import com.book.backend.domain.user.entity.User; | ||
import com.book.backend.domain.user.mapper.UserMapper; | ||
import com.book.backend.domain.user.repository.UserRepository; | ||
import com.book.backend.exception.CustomException; | ||
import com.book.backend.exception.ErrorCode; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
import java.time.LocalDateTime; | ||
import java.util.Optional; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
@Transactional(readOnly = true) | ||
public class AuthService { | ||
private final UserRepository userRepository; | ||
private final AuthMapper authMapper; | ||
private final UserMapper userMapper; | ||
private final AuthenticationManager authenticationManager; | ||
|
||
@Transactional | ||
public UserDto signup(SignupDto signupDto) { | ||
Optional<User> userOptional = userRepository.findByLoginId(signupDto.getLoginId()); | ||
|
||
if (userOptional.isPresent()) { | ||
throw new CustomException(ErrorCode.LOGIN_ID_DUPLICATED); | ||
} | ||
|
||
User user = authMapper.convertToUser(signupDto); | ||
user.setRegDate(LocalDateTime.now()); | ||
|
||
User savedUser = userRepository.save(user); | ||
|
||
return userMapper.convertToUserDto(savedUser); | ||
} | ||
|
||
public UserDto login(LoginDto loginDto) { | ||
try { | ||
// 사용자 인증 시도 | ||
Authentication authentication = authenticationManager.authenticate( | ||
new UsernamePasswordAuthenticationToken(loginDto.getLoginId(), loginDto.getPassword())); | ||
|
||
// 인증 성공 시 SecurityContextHolder에 인증 정보 저장 | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
|
||
User user = userRepository.findByLoginId(loginDto.getLoginId()) | ||
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); | ||
|
||
return userMapper.convertToUserDto(user); | ||
} catch (AuthenticationException e) { | ||
throw new CustomException(ErrorCode.INVALID_CREDENTIALS); | ||
} | ||
} | ||
|
||
@Transactional | ||
public void deleteAccountByLoginId(String loginId) { | ||
User user = userRepository.findByLoginId(loginId) | ||
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); | ||
userRepository.delete(user); | ||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
src/main/java/com/book/backend/domain/user/dto/UserDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package com.book.backend.domain.user.dto; | ||
|
||
import lombok.*; | ||
|
||
import java.time.LocalDate; | ||
import java.time.LocalDateTime; | ||
|
||
@Getter | ||
@Setter | ||
@Builder | ||
@NoArgsConstructor | ||
@AllArgsConstructor | ||
public class UserDto { | ||
private Long userId; | ||
|
||
private LocalDateTime regDate; | ||
|
||
private String loginId; | ||
|
||
private String password; | ||
|
||
private String gender; | ||
|
||
private LocalDate birthDate; | ||
|
||
private String email; | ||
|
||
private String phone; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
27 changes: 27 additions & 0 deletions
27
src/main/java/com/book/backend/domain/user/mapper/UserMapper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package com.book.backend.domain.user.mapper; | ||
|
||
import com.book.backend.domain.user.dto.UserDto; | ||
import com.book.backend.domain.user.entity.User; | ||
import com.book.backend.exception.CustomException; | ||
import com.book.backend.exception.ErrorCode; | ||
import lombok.RequiredArgsConstructor; | ||
import org.modelmapper.ModelMapper; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class UserMapper { | ||
|
||
private final ModelMapper mapper; | ||
|
||
public UserDto convertToUserDto(User user) { | ||
if (user == null) { | ||
throw new CustomException(ErrorCode.USER_NOT_FOUND); | ||
} | ||
|
||
UserDto userDto = mapper.map(user, UserDto.class); | ||
userDto.setGender(user.getGender().name()); | ||
|
||
return userDto; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
src/main/java/com/book/backend/global/ModelMapperConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package com.book.backend.global; | ||
|
||
import org.modelmapper.ModelMapper; | ||
import org.modelmapper.convention.MatchingStrategies; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
|
||
@Configuration | ||
public class ModelMapperConfig { | ||
|
||
@Bean | ||
public ModelMapper modelMapper() { | ||
ModelMapper mapper = new ModelMapper(); | ||
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); | ||
return mapper; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.