diff --git a/src/main/java/com/gdschongik/gdsc/global/exception/ErrorCode.java b/src/main/java/com/gdschongik/gdsc/global/exception/ErrorCode.java index 4bf8434d3..582bdf4af 100644 --- a/src/main/java/com/gdschongik/gdsc/global/exception/ErrorCode.java +++ b/src/main/java/com/gdschongik/gdsc/global/exception/ErrorCode.java @@ -9,16 +9,19 @@ public enum ErrorCode { INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 에러입니다."), - // Jwt + // Auth INVALID_JWT_TOKEN(HttpStatus.UNAUTHORIZED, "유효하지 않은 JWT 토큰입니다."), EXPIRED_JWT_TOKEN(HttpStatus.UNAUTHORIZED, "만료된 JWT 토큰입니다."), + AUTH_NOT_EXIST(HttpStatus.INTERNAL_SERVER_ERROR, "시큐리티 인증 정보가 존재하지 않습니다."), + AUTH_NOT_PARSABLE(HttpStatus.INTERNAL_SERVER_ERROR, "시큐리티 인증 정보 파싱에 실패했습니다."), // Parameter INVALID_QUERY_PARAMETER(HttpStatus.BAD_REQUEST, "잘못된 쿼리 파라미터입니다."), // Member MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND, "존재하지 않는 회원입니다."), - MEMBER_DELETED(HttpStatus.CONFLICT, "탈퇴한 회원입니다."); + MEMBER_DELETED(HttpStatus.CONFLICT, "탈퇴한 회원입니다."), + ; private final HttpStatus status; private final String message; diff --git a/src/main/java/com/gdschongik/gdsc/global/util/MemberUtil.java b/src/main/java/com/gdschongik/gdsc/global/util/MemberUtil.java new file mode 100644 index 000000000..63315d461 --- /dev/null +++ b/src/main/java/com/gdschongik/gdsc/global/util/MemberUtil.java @@ -0,0 +1,41 @@ +package com.gdschongik.gdsc.global.util; + +import com.gdschongik.gdsc.domain.member.dao.MemberRepository; +import com.gdschongik.gdsc.domain.member.domain.Member; +import com.gdschongik.gdsc.global.exception.CustomException; +import com.gdschongik.gdsc.global.exception.ErrorCode; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class MemberUtil { + + private final MemberRepository memberRepository; + + public Long getCurrentMemberId() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + validateAuthenticationNotNull(authentication); + + try { + return Long.parseLong(authentication.getName()); + } catch (NumberFormatException e) { + throw new CustomException(ErrorCode.AUTH_NOT_PARSABLE); + } + } + + private void validateAuthenticationNotNull(Authentication authentication) { + if (authentication == null) { + throw new CustomException(ErrorCode.AUTH_NOT_EXIST); + } + } + + public Member getCurrentMember() { + return memberRepository + .findById(getCurrentMemberId()) + .orElseThrow(() -> new CustomException(ErrorCode.MEMBER_NOT_FOUND)); + } +}