Skip to content

Commit 5f7e555

Browse files
authored
[EC-236] feat: 로그인 성능 개선 (#246)
* [EC-236] feat: 로그인 성능 개선 * [EC-236] feat: 이메일 예외처리
1 parent 062ed4b commit 5f7e555

File tree

8 files changed

+44
-24
lines changed

8 files changed

+44
-24
lines changed

api/src/main/java/org/example/educheck/domain/member/service/AuthService.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import jakarta.servlet.http.HttpServletRequest;
66
import jakarta.servlet.http.HttpServletResponse;
77
import lombok.RequiredArgsConstructor;
8+
import lombok.extern.slf4j.Slf4j;
89
import org.example.educheck.domain.course.entity.Course;
910
import org.example.educheck.domain.course.repository.CourseRepository;
1011
import org.example.educheck.domain.member.dto.EmailCheckResponseDto;
@@ -37,6 +38,7 @@
3738
import java.time.LocalDateTime;
3839
import java.util.Optional;
3940

41+
@Slf4j
4042
@Service
4143
@Transactional(readOnly = true)
4244
@RequiredArgsConstructor
@@ -83,22 +85,18 @@ public RegisteredMemberResponseDto signUp(SignUpRequestDto requestDto) {
8385

8486
}
8587

88+
8689
@Transactional
8790
public LoginResponseDto login(LoginRequestDto requestDto, HttpServletResponse response) {
8891

89-
Authentication authenticate = authenticationManager.authenticate(
92+
Authentication authentication = authenticationManager.authenticate(
9093
new UsernamePasswordAuthenticationToken(
9194
requestDto.getEmail(), requestDto.getPassword()
9295
)
9396
);
94-
95-
Member member = memberRepository.findByEmail(requestDto.getEmail())
96-
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 회원입니다.")
97-
);
98-
99-
setTokensInResponse(authenticate, response);
97+
Member member = (Member) authentication.getPrincipal();
98+
setTokensInResponse(authentication, response);
10099
LoginResponseDto loginResponseDto = roleBasedLogin(member);
101-
102100
member.setLastLoginDateTime(LocalDateTime.now());
103101

104102
return loginResponseDto;

api/src/main/java/org/example/educheck/domain/member/service/MyService.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import org.springframework.security.authentication.AuthenticationManager;
1010
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
1111
import org.springframework.security.core.Authentication;
12-
import org.springframework.security.core.context.SecurityContextHolder;
1312
import org.springframework.security.crypto.password.PasswordEncoder;
1413
import org.springframework.stereotype.Service;
1514
import org.springframework.transaction.annotation.Transactional;
@@ -55,7 +54,7 @@ public void updateMyProfile(Member member, UpdateMyProfileRequestDto requestDto)
5554
member.getEmail(), requestDto.getCurrentPassword())
5655
);
5756

58-
SecurityContextHolder.getContext().setAuthentication(authentication); //TODO: 삭제?
57+
// SecurityContextHolder.getContext().setAuthentication(authentication); //TODO: 삭제?
5958

6059
}
6160
memberRepository.save(member);

api/src/main/java/org/example/educheck/global/common/exception/ErrorCode.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
public enum ErrorCode {
1010

1111
//0000 회원
12+
EMAIL_NOT_FOUND(HttpStatus.UNAUTHORIZED, "0000", "인증 정보를 찾을 수 없습니다."),
1213
//1000 예약
1314
RESERVATION_CONFLICT(HttpStatus.CONFLICT, "1000", "해당 시간에는 이미 예약이 있습니다. 다른 시간을 선택해주세요."),
1415

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package org.example.educheck.global.common.exception.custom.auth;
2+
3+
import org.example.educheck.global.common.exception.ErrorCode;
4+
import org.example.educheck.global.common.exception.custom.common.GlobalException;
5+
6+
public class EmailNotFoundException extends GlobalException {
7+
public EmailNotFoundException() {
8+
super(ErrorCode.EMAIL_NOT_FOUND);
9+
}
10+
11+
public EmailNotFoundException(String customMessage) {
12+
super(ErrorCode.EMAIL_NOT_FOUND, customMessage);
13+
}
14+
}

api/src/main/java/org/example/educheck/global/common/exception/handler/GlobalExceptionHandler.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import org.example.educheck.global.common.dto.ApiResponse;
55
import org.example.educheck.global.common.exception.ErrorCode;
66
import org.example.educheck.global.common.exception.custom.LoginValidationException;
7+
import org.example.educheck.global.common.exception.custom.auth.EmailNotFoundException;
78
import org.example.educheck.global.common.exception.custom.common.GlobalException;
89
import org.springframework.http.HttpStatus;
910
import org.springframework.http.ResponseEntity;
@@ -118,4 +119,12 @@ public ResponseEntity<ApiResponse<Object>> handleNoResourceFoundException(NoReso
118119
.body(ApiResponse.error(ErrorCode.RESOURCE_NOT_FOUND.getMessage(),
119120
ErrorCode.RESOURCE_NOT_FOUND.getCode()));
120121
}
122+
123+
@ExceptionHandler(EmailNotFoundException.class)
124+
public ResponseEntity<ApiResponse<Object>> handleEmailNotFoundException(EmailNotFoundException ex) {
125+
return ResponseEntity
126+
.status(ErrorCode.EMAIL_NOT_FOUND.getStatus())
127+
.body(ApiResponse.error(ErrorCode.EMAIL_NOT_FOUND.getMessage(),
128+
ErrorCode.EMAIL_NOT_FOUND.getCode()));
129+
}
121130
}

api/src/main/java/org/example/educheck/global/security/CustomUserDetailsService.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import lombok.RequiredArgsConstructor;
44
import org.example.educheck.domain.member.repository.MemberRepository;
5+
import org.example.educheck.global.common.exception.custom.auth.EmailNotFoundException;
56
import org.springframework.security.core.userdetails.UserDetails;
67
import org.springframework.security.core.userdetails.UserDetailsService;
78
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -21,7 +22,6 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx
2122
public UserDetails loadUserByEmail(String email) throws UsernameNotFoundException {
2223

2324
return memberRepository.findByEmail(email)
24-
// .orElseThrow(() -> new EmailNotFoundException("사용자를 찾을 수 없습니다.")); // TODO: Exception
25-
.orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다."));
25+
.orElseThrow(() -> new EmailNotFoundException("사용자를 찾을 수 없습니다."));
2626
}
2727
}

api/src/main/java/org/example/educheck/global/security/config/SecurityConfig.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,10 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
3636
.sessionManagement(session -> session
3737
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
3838
.authorizeHttpRequests(auth -> auth
39-
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
40-
.requestMatchers(HttpMethod.POST, SecurityPathConfig.PUBLIC_POST_URLS).permitAll()
41-
.requestMatchers(HttpMethod.GET, SecurityPathConfig.PUBLIC_GET_URLS).permitAll()
42-
.anyRequest().authenticated()
43-
// TODO: 인증 엔드포인트 수정
39+
.requestMatchers(HttpMethod.OPTIONS).permitAll()
40+
.requestMatchers(HttpMethod.POST, SecurityPathConfig.PUBLIC_POST_URLS).permitAll()
41+
.requestMatchers(HttpMethod.GET, SecurityPathConfig.PUBLIC_GET_URLS).permitAll()
42+
.anyRequest().authenticated()
4443
)
4544
// TODO: 비밀번호 예외처리
4645
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)

api/src/main/java/org/example/educheck/global/security/jwt/JwtTokenUtil.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,12 @@
77
import io.jsonwebtoken.security.Keys;
88
import jakarta.annotation.PostConstruct;
99
import lombok.extern.slf4j.Slf4j;
10-
import org.example.educheck.global.common.exception.custom.LoginValidationException;
10+
import org.example.educheck.domain.member.entity.Member;
1111
import org.springframework.beans.factory.annotation.Value;
1212
import org.springframework.security.core.Authentication;
1313
import org.springframework.security.core.GrantedAuthority;
1414
import org.springframework.stereotype.Component;
1515

16-
import java.lang.reflect.Field;
1716
import java.nio.charset.StandardCharsets;
1817
import java.security.MessageDigest;
1918
import java.security.NoSuchAlgorithmException;
@@ -24,7 +23,7 @@
2423
@Component
2524
public class JwtTokenUtil {
2625
public static final long REFRESH_TOKEN_VALIDITY_MILLISECONDS = 1000L * 60 * 60 * 24 * 30;
27-
private static final long ACCESS_TOKEN_VALIDITY_MILLISECONDS = 1000L * 60 * 60 * 24 * 7; // TODO: 개발 후 줄이기
26+
private static final long ACCESS_TOKEN_VALIDITY_MILLISECONDS = 1000L * 60 * 30;
2827
@Value("${JWT_SECRET}")
2928
private String secretKey;
3029

@@ -42,17 +41,18 @@ protected void init() {
4241

4342
private String createToken(Authentication authentication, long validityMilliSeconds) {
4443

45-
log.info("authentication: {}", authentication.getAuthorities());
46-
String email = null;
44+
45+
/* String email = null;
4746
try {
4847
Object principal = authentication.getPrincipal();
4948
Field field = principal.getClass().getDeclaredField("email");
5049
field.setAccessible(true);
5150
email = field.get(principal).toString();
5251
} catch (NoSuchFieldException | IllegalAccessException e) {
5352
throw new LoginValidationException();
54-
}
55-
Claims claims = Jwts.claims().setSubject(email);
53+
}*/
54+
Member member = (Member) authentication.getPrincipal();
55+
Claims claims = Jwts.claims().setSubject(member.getEmail());
5656
claims.put("roles", authentication.getAuthorities()
5757
.stream()
5858
.map(GrantedAuthority::getAuthority)

0 commit comments

Comments
 (0)