|
| 1 | +package com.back.global.security; |
| 2 | + |
| 3 | +import com.back.domain.user.entity.User; |
| 4 | +import com.back.domain.user.repository.UserRepository; |
| 5 | +import com.back.global.exception.CustomException; |
| 6 | +import com.back.global.exception.ErrorCode; |
| 7 | +import lombok.RequiredArgsConstructor; |
| 8 | +import org.springframework.security.core.Authentication; |
| 9 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 10 | +import org.springframework.stereotype.Component; |
| 11 | + |
| 12 | +import java.util.Optional; |
| 13 | + |
| 14 | +/** |
| 15 | + * SecurityContext에 저장된 인증 정보를 바탕으로 |
| 16 | + * 현재 로그인한 사용자 정보를 가져오는 유틸 클래스 |
| 17 | + */ |
| 18 | +@Component |
| 19 | +@RequiredArgsConstructor |
| 20 | +public class CurrentUser { |
| 21 | + private final UserRepository userRepository; |
| 22 | + |
| 23 | + /** |
| 24 | + * 현재 사용자가 인증된 상태인지 확인 |
| 25 | + */ |
| 26 | + public boolean isAuthenticated() { |
| 27 | + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); |
| 28 | + return auth != null |
| 29 | + && auth.isAuthenticated() |
| 30 | + && auth.getPrincipal() instanceof CustomUserDetails; |
| 31 | + } |
| 32 | + |
| 33 | + public Long getUserId() { return getDetails().getUserId(); } |
| 34 | + |
| 35 | + public String getUsername() { return getDetails().getUsername(); } |
| 36 | + |
| 37 | + public String getRole() { return getDetails().getRole(); } |
| 38 | + |
| 39 | + public String getEmail() { return getUserFromDb().getEmail(); } |
| 40 | + |
| 41 | + public String getProvider() { return getUserFromDb().getProvider(); } |
| 42 | + |
| 43 | + public String getProviderId() { return getUserFromDb().getProviderId(); } |
| 44 | + |
| 45 | + public String getStatus() { return getUserFromDb().getUserStatus().name(); } |
| 46 | + |
| 47 | + /** |
| 48 | + * SecurityContext에서 CustomUserDetails 추출 |
| 49 | + */ |
| 50 | + private CustomUserDetails getDetails() { |
| 51 | + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); |
| 52 | + if (auth != null && auth.getPrincipal() instanceof CustomUserDetails details) { |
| 53 | + return details; |
| 54 | + } |
| 55 | + throw new CustomException(ErrorCode.UNAUTHORIZED); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * DB에서 현재 사용자 엔티티 조회 |
| 60 | + */ |
| 61 | + private User getUserFromDb() { |
| 62 | + return userRepository.findById(getDetails().getUserId()).orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); |
| 63 | + } |
| 64 | +} |
0 commit comments