Skip to content

Commit 2d9c4ec

Browse files
authored
Merge pull request #77 from IDEA-CAMPUS/refactor/72-task
[Refactor] 72-task dto,mail 등 리펙토링
2 parents 5488ac1 + b850d80 commit 2d9c4ec

File tree

23 files changed

+139
-200
lines changed

23 files changed

+139
-200
lines changed

.idea/vcs.xml

Lines changed: 0 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

ideac-admin/src/main/java/depth/main/ideac/domain/auth/presentation/AuthController.java

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,10 @@
33

44
import depth.main.ideac.domain.admin.application.AdminService;
55
import depth.main.ideac.domain.auth.application.AuthService;
6-
import depth.main.ideac.domain.auth.dto.AuthRes;
7-
import depth.main.ideac.domain.auth.dto.FindIdReq;
8-
import depth.main.ideac.domain.auth.dto.SignInReq;
9-
import depth.main.ideac.domain.auth.dto.SignUpReq;
10-
import depth.main.ideac.domain.user.application.UserService;
11-
import depth.main.ideac.domain.user.domain.User;
6+
import depth.main.ideac.domain.auth.dto.response.AuthRes;
7+
import depth.main.ideac.domain.auth.dto.request.FindIdReq;
8+
import depth.main.ideac.domain.auth.dto.request.SignInReq;
9+
import depth.main.ideac.domain.user.dto.PasswordReq;
1210
import depth.main.ideac.global.payload.ErrorResponse;
1311
import depth.main.ideac.global.payload.Message;
1412
import io.swagger.v3.oas.annotations.Operation;
@@ -22,7 +20,6 @@
2220
import lombok.RequiredArgsConstructor;
2321
import org.springframework.http.ResponseEntity;
2422
import org.springframework.security.access.AccessDeniedException;
25-
import org.springframework.security.access.prepost.PreAuthorize;
2623
import org.springframework.web.bind.annotation.*;
2724

2825
@Tag(name = "Auth API", description = "Authorization 관련 API입니다.")
@@ -66,4 +63,15 @@ public ResponseEntity<?> findId(@Parameter(description = "Schemas의 FindIdReque
6663
return authService.findId(findIdReq);
6764
}
6865

66+
@Operation(summary = "비밀번호 바꾸기", description = "비밀번호를 바꾼다.")
67+
@ApiResponses(value = {
68+
@ApiResponse(responseCode = "200", description = "비밀번호 바꾸기 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Message.class))}),
69+
@ApiResponse(responseCode = "400", description = "비밀번호 바꾸기 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))})
70+
})
71+
@PostMapping(value = "/change-password/{code}")
72+
public ResponseEntity<?> changePassword(@Parameter(description = "Schemas의 PassWordReq를 참고해주세요.")
73+
@Valid @RequestBody PasswordReq passwordReq,
74+
@PathVariable String code) {
75+
return authService.changePassword(passwordReq,code);
76+
}
6977
}

ideac-admin/src/main/java/depth/main/ideac/domain/user/presentation/UserController.java

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,6 @@
2323
public class UserController {
2424

2525
private final UserService userService;
26-
@Operation(summary = "메일 보내기", description = "비밀번호를 찾기위해 메일을 보낸다.")
27-
@ApiResponses(value = {
28-
@ApiResponse(responseCode = "200", description = "비밀번호 바꾸기 성공", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = Message.class))}),
29-
@ApiResponse(responseCode = "400", description = "비밀번호 바꾸기 실패", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))})
30-
})
31-
@PostMapping(value = "/change-password/{code}")
32-
public ResponseEntity<?> changePassword(@Parameter(description = "Schemas의 PassWordReq를 참고해주세요.")
33-
@Valid @RequestBody PasswordReq passwordReq,
34-
@PathVariable String code) {
35-
return userService.changePassword(passwordReq,code);
36-
}
3726

3827
@Operation(summary = "로그아웃", description = "로그아웃 API입니다.")
3928
@ApiResponses(value = {

ideac-core/src/main/java/depth/main/ideac/domain/auth/application/AuthService.java

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,42 @@
33
import depth.main.ideac.domain.auth.domain.Token;
44
import depth.main.ideac.domain.auth.domain.repository.TokenRepository;
55
import depth.main.ideac.domain.auth.dto.*;
6+
import depth.main.ideac.domain.auth.dto.request.FindIdReq;
7+
import depth.main.ideac.domain.auth.dto.request.RefreshTokenReq;
8+
import depth.main.ideac.domain.auth.dto.request.SignInReq;
9+
import depth.main.ideac.domain.auth.dto.request.SignUpReq;
10+
import depth.main.ideac.domain.auth.dto.response.AuthRes;
11+
import depth.main.ideac.domain.mail.domain.Verify;
12+
import depth.main.ideac.domain.mail.domain.repository.MailRepository;
613
import depth.main.ideac.domain.user.domain.Role;
714
import depth.main.ideac.domain.user.domain.Status;
815
import depth.main.ideac.domain.user.domain.User;
916
import depth.main.ideac.domain.user.domain.repository.UserRepository;
17+
import depth.main.ideac.domain.user.dto.PasswordReq;
1018
import depth.main.ideac.global.DefaultAssert;
1119
import depth.main.ideac.global.error.DefaultException;
1220
import depth.main.ideac.global.payload.ApiResponse;
1321
import depth.main.ideac.global.payload.ErrorCode;
1422
import depth.main.ideac.global.payload.Message;
23+
import jakarta.validation.Valid;
1524
import lombok.RequiredArgsConstructor;
25+
import lombok.extern.slf4j.Slf4j;
1626
import org.springframework.http.ResponseEntity;
1727
import org.springframework.security.authentication.AuthenticationManager;
1828
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
1929
import org.springframework.security.core.Authentication;
2030
import org.springframework.security.core.context.SecurityContextHolder;
2131
import org.springframework.security.crypto.password.PasswordEncoder;
2232
import org.springframework.stereotype.Service;
33+
import org.springframework.transaction.annotation.Transactional;
2334

35+
import java.time.LocalDateTime;
2436
import java.util.Optional;
2537

2638

2739
@RequiredArgsConstructor
2840
@Service
41+
@Slf4j
2942
public class AuthService {
3043

3144
private final AuthenticationManager authenticationManager;
@@ -34,14 +47,11 @@ public class AuthService {
3447

3548
private final UserRepository userRepository;
3649
private final TokenRepository tokenRepository;
50+
private final MailRepository mailRepository;
3751

3852
// 회원가입 하기
3953
public ResponseEntity<?> signUp(SignUpReq signUpRequest){
4054

41-
// //검증
42-
// DefaultAssert.isTrue(!userRepository.existsByEmail(signUpRequest.getIdEmail()), "해당 이메일이 존재합니다.");
43-
// DefaultAssert.isTrue(!userRepository.existsByNickname(signUpRequest.getNickname()), "이미 존재하는 닉네임입니다.");
44-
4555
User user = User.builder()
4656
.email(signUpRequest.getIdEmail())
4757
.password(passwordEncoder.encode(signUpRequest.getPassword()))
@@ -70,7 +80,7 @@ public ResponseEntity<?> signUp(SignUpReq signUpRequest){
7080
//로그인 하기
7181
public ResponseEntity<?> signIn(SignInReq signInReq){
7282

73-
83+
System.out.println("signInReq.getEmail() = " + signInReq.getEmail());
7484
Optional<User> user = userRepository.findByEmail(signInReq.getEmail());
7585
DefaultAssert.isTrue(user.isPresent(), "이메일이 틀렸습니다.");
7686

@@ -79,7 +89,6 @@ public ResponseEntity<?> signIn(SignInReq signInReq){
7989
throw new DefaultException(ErrorCode.INVALID_CHECK, "정지되었거나 탈퇴된 유저입니다.");
8090
}
8191

82-
8392
boolean checkPassword = passwordEncoder.matches(signInReq.getPassword(), findUser.getPassword());
8493
DefaultAssert.isTrue(checkPassword, "비밀번호가 틀렸습니다");
8594

@@ -89,7 +98,6 @@ public ResponseEntity<?> signIn(SignInReq signInReq){
8998
signInReq.getPassword()
9099
)
91100
);
92-
93101
SecurityContextHolder.getContext().setAuthentication(authentication);
94102

95103
TokenMapping tokenMapping = customTokenProviderService.createToken(authentication);
@@ -103,20 +111,20 @@ public ResponseEntity<?> signIn(SignInReq signInReq){
103111
AuthRes authResponse = AuthRes.builder()
104112
.accessToken(tokenMapping.getAccessToken())
105113
.refreshToken(token.getRefreshToken()).build();
106-
107114
return ResponseEntity.ok(authResponse);
108115
}
109116

110117
// 핸드폰번호로 아이디(이메일) 찾기
111118
public ResponseEntity<?> findId(FindIdReq findIdReq) {
119+
System.out.println("findIdReq.getPhoneNumber() = " + findIdReq.getPhoneNumber());
112120
Optional<User> findUser = userRepository.findByPhoneNumber(findIdReq.getPhoneNumber());
113121
DefaultAssert.isTrue(findUser.isPresent(), "해당이메일을 갖고 있는 유저가 없습니다.");
114-
122+
115123
User user = findUser.get();
124+
System.out.println("user.getEmail() = " + user.getEmail());
116125
ApiResponse apiResponse = ApiResponse.builder()
117126
.check(true)
118127
.information(user.getEmail())
119-
.message("가입하신 아이디를 찾아왔어요!")
120128
.build();
121129
return ResponseEntity.ok(apiResponse);
122130
}
@@ -164,21 +172,51 @@ private boolean valid(String refreshToken){
164172
return true;
165173
}
166174

175+
// 닉네임 중복검증
167176
public ResponseEntity<?> doubleCheckNickname(String nickname) {
168177
ApiResponse apiResponse = ApiResponse.builder()
169178
.check(true)
170179
.information(userRepository.findByNickname(nickname).isEmpty())
171-
.message("닉네임 검증 완료")
172180
.build();
173181
return ResponseEntity.ok(apiResponse);
174182
}
175183

184+
// 이메일 중복검증
176185
public ResponseEntity<?> doubleCheckEmail(String email) {
177186
ApiResponse apiResponse = ApiResponse.builder()
178187
.check(true)
179188
.information(userRepository.findByEmail(email).isEmpty())
180-
.message("이메일 검증 완료")
181189
.build();
182190
return ResponseEntity.ok(apiResponse);
183191
}
192+
193+
@Transactional
194+
public ResponseEntity<?> changePassword(@Valid PasswordReq passwordReq, String code){
195+
196+
//검증
197+
DefaultAssert.isTrue(passwordReq.getPassword().equals(passwordReq.getRePassword()), "비밀번호가 서로 다릅니다.");
198+
//만료시간 검증
199+
Verify verify = mailRepository.findByCode(code);
200+
201+
if (verify == null){
202+
throw new DefaultException(ErrorCode.INVALID_CHECK, "이미변경되었습니다.");
203+
}
204+
205+
DefaultAssert.isTrue(verify.checkExpiration(LocalDateTime.now()), "만료되었습니다.");
206+
207+
Optional<User> findUser = userRepository.findByEmail(verify.getEmail());
208+
209+
User user = findUser.get();
210+
user.updatePassWord(passwordEncoder.encode(passwordReq.getPassword()));
211+
212+
// 인증완료 후 삭제
213+
mailRepository.delete(verify);
214+
215+
ApiResponse apiResponse = ApiResponse.builder()
216+
.check(true)
217+
.information(null)
218+
.build();
219+
220+
return ResponseEntity.ok(apiResponse);
221+
}
184222
}

ideac-core/src/main/java/depth/main/ideac/domain/auth/application/CustomDefaultOAuth2UserService.java

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,12 @@ private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2
4343

4444
Optional<User> userOptional = userRepository.findByEmail(oAuth2UserInfo.getEmail());
4545
User user;
46-
if(userOptional.isPresent()) {
47-
user = userOptional.get();
48-
DefaultAssert.isAuthentication(user.getProvider().equals(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId())));
49-
// user = updateExistingUser(user, oAuth2UserInfo);
50-
} else {
51-
user = registerNewUser(oAuth2UserRequest, oAuth2UserInfo);
52-
log.info("통과1");
53-
54-
}
46+
user = registerNewUser(oAuth2UserRequest, oAuth2UserInfo);
5547

5648
return UserPrincipal.create(user, oAuth2User.getAttributes());
5749
}
5850

51+
// oauth2 회원 등록
5952
private User registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) {
6053
User user = User.builder()
6154
.provider(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()))
@@ -67,12 +60,4 @@ private User registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo
6760
.build();
6861
return userRepository.save(user);
6962
}
70-
71-
// private User updateExistingUser(User user, OAuth2UserInfo oAuth2UserInfo) {
72-
//// 추후 사용시 바뀔예정인 함수
73-
//// user.updateName(oAuth2UserInfo.getName());
74-
//// user.updateImageUrl(oAuth2UserInfo.getImageUrl());
75-
//
76-
// return userRepository.save(user);
77-
// }
7863
}

ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/FindIdReq.java renamed to ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/request/FindIdReq.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package depth.main.ideac.domain.auth.dto;
1+
package depth.main.ideac.domain.auth.dto.request;
22

33
import io.swagger.v3.oas.annotations.media.Schema;
44
import jakarta.validation.constraints.NotBlank;

ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/RefreshTokenReq.java renamed to ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/request/RefreshTokenReq.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
package depth.main.ideac.domain.auth.dto;
1+
package depth.main.ideac.domain.auth.dto.request;
22

33
import io.swagger.v3.oas.annotations.media.Schema;
44
import jakarta.validation.constraints.NotBlank;
55
import jakarta.validation.constraints.NotNull;
66
import lombok.Builder;
7-
import lombok.Data;
7+
import lombok.Getter;
88

9-
@Data
9+
@Getter
1010
public class RefreshTokenReq {
1111

1212
@Schema( type = "string", example = "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE2NTI3OTgxOTh9.6CoxHB_siOuz6PxsxHYQCgUT1_QbdyKTUwStQDutEd1-cIIARbQ0cyrnAmpIgi3IBoLRaqK7N1vXO42nYy4g5g", description="refresh token 입니다." )

ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/SignInReq.java renamed to ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/request/SignInReq.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
1-
package depth.main.ideac.domain.auth.dto;
1+
package depth.main.ideac.domain.auth.dto.request;
22

33
import io.swagger.v3.oas.annotations.media.Schema;
44
import jakarta.validation.constraints.Email;
55
import jakarta.validation.constraints.NotBlank;
6-
import jakarta.validation.constraints.NotNull;
76
import jakarta.validation.constraints.Pattern;
8-
import lombok.Data;
97
import lombok.Getter;
108

119

12-
@Data
10+
@Getter
1311
public class SignInReq {
1412

1513
@Schema( type = "string", example = "idea00@naver.com", description="계정 이메일 입니다.")

ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/SignUpReq.java renamed to ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/request/SignUpReq.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
package depth.main.ideac.domain.auth.dto;
1+
package depth.main.ideac.domain.auth.dto.request;
22

33
import io.swagger.v3.oas.annotations.media.Schema;
4-
import jakarta.validation.constraints.Email;
54
import jakarta.validation.constraints.NotBlank;
65
import jakarta.validation.constraints.Pattern;
76
import jakarta.validation.constraints.Size;
8-
import lombok.Data;
97
import lombok.Getter;
108

119
@Getter

ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/AuthRes.java renamed to ideac-core/src/main/java/depth/main/ideac/domain/auth/dto/response/AuthRes.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
package depth.main.ideac.domain.auth.dto;
1+
package depth.main.ideac.domain.auth.dto.response;
22

33
import io.swagger.v3.oas.annotations.media.Schema;
44
import lombok.Builder;
5-
import lombok.Data;
5+
import lombok.Getter;
66

7-
@Data
7+
@Getter
88
public class AuthRes {
99

1010
@Schema( type = "string", example = "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE2NTI3OTgxOTh9.6CoxHB_siOuz6PxsxHYQCgUT1_QbdyKTUwStQDutEd1-cIIARbQ0cyrnAmpIgi3IBoLRaqK7N1vXO42nYy4g5g" , description="access token 을 출력합니다.")

ideac-core/src/main/java/depth/main/ideac/domain/idea_post/IdeaPost.java

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,4 @@ public class IdeaPost extends BaseEntity {
4444
private User user;
4545

4646
private Long hits;
47-
48-
// public void updateIdea(UpdateIdeaReq updateIdeaReq) {
49-
// this.title = updateIdeaReq.getTitle();
50-
// this.simpleDescription = updateIdeaReq.getSimpleDescription();
51-
// this.detailedDescription = updateIdeaReq.getDetailedDescription();
52-
// this.url1 = updateIdeaReq.getUrl1();
53-
// this.url2 = updateIdeaReq.getUrl2();
54-
// }
5547
}

ideac-core/src/main/java/depth/main/ideac/domain/mail/application/MailService.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ public class MailService {
2727
private final JavaMailSender javaMailSender;
2828
private final UserRepository userRepository;
2929
private final MailRepository mailRepository;
30-
private final PasswordEncoder passwordEncoder;
3130
@Transactional
3231
public ResponseEntity<?> sendEmail(FindPasswordReq findPasswordReq) {
3332
// 이메일이 존재하는지 확인
@@ -45,10 +44,13 @@ public ResponseEntity<?> sendEmail(FindPasswordReq findPasswordReq) {
4544
simpleMailMessage.setTo(receiveList);
4645

4746
// 2. 메일 제목 설정
48-
simpleMailMessage.setSubject("test_title");
47+
simpleMailMessage.setSubject("IDEA CAMPUS 비밀번호 재설정");
4948

5049
// 3. 메일 내용 설정
51-
simpleMailMessage.setText("http://localhost:8080/mail/send-email/" + code);
50+
simpleMailMessage.setText("안녕하세요. IDEA CAMPUS입니다.\n" +
51+
"서비스 이용을 위한 하단 계정의 비밀번호 재설정 이메일 요청 메일입니다.\n" +
52+
"‘비밀번호 재설정’ 버튼을 클릭하여 재설정이 완료하실 수 있습니다." +
53+
"http://localhost:8080/mail/send-email/" + code);
5254

5355
// 4. 메일 전송
5456
javaMailSender.send(simpleMailMessage);
@@ -60,7 +62,6 @@ public ResponseEntity<?> sendEmail(FindPasswordReq findPasswordReq) {
6062
ApiResponse apiResponse = ApiResponse.builder()
6163
.check(true)
6264
.information(verify.getCode())
63-
.message("메일을 보냈어요!")
6465
.build();
6566

6667
return ResponseEntity.ok(apiResponse);

0 commit comments

Comments
 (0)