Skip to content

Commit

Permalink
❕ [!HOTFIX] #129 아트보드 접근, accessToken재발급 수정 (#130)
Browse files Browse the repository at this point in the history
* chore: 아트보드 접근 수정

* chore: access토큰 재발급 api수정(헤더값)

* chore: 재발급api jwt 필터거치게 수정

* chore: 아트레터 상세조회, 검색 접근 허용, 아트레터 생성 접근 차단

* chore: 로그인 안 한 유저의 스크랩 조회시 에러처리 추가
  • Loading branch information
oneeee822 authored Feb 13, 2025
1 parent 2afc855 commit 81e1c35
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class ArtletterController {

// POST: 아트레터 등록
@PostMapping
@PreAuthorize("isAuthenticated()")
public ResponseEntity<ApiResponse> createArtletter(@AuthenticationPrincipal CustomUserPrincipal userPrincipal, @RequestBody Map<String, Object> request) {
// 필드 값 추출
Object readTimeObj = request.get("readTime");
Expand Down Expand Up @@ -163,7 +164,6 @@ public ResponseEntity<ApiResponse> searchArtletters(


@PostMapping("/editor-pick")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<ApiResponse> getEditorArtletters(
@AuthenticationPrincipal CustomUserPrincipal userPrincipal,
@RequestBody ArtletterDTO.EditorRequestDto editorRequestDto) {
Expand Down Expand Up @@ -191,7 +191,6 @@ public ResponseEntity<ApiResponse> scrapArtletter(@PathVariable Long letterId, @


@GetMapping("/{letterId}")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<ApiResponse> getArtletterInfo(
@AuthenticationPrincipal CustomUserPrincipal userPrincipal,
@PathVariable("letterId") Long letterId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,17 @@ public Page<Artletter> searchArtletters(String keyword, Pageable pageable) {
@Override
public ArtletterDTO.ListResponseDto getArtletter(CustomUserPrincipal userPrincipal, long letterId) {

Member member = findMemberById(userPrincipal.getMemberId());
Artletter artletter = findArtletterById(letterId);
Artletter artletter = artletterRepository.findById(letterId)
.orElseThrow(() -> new GeneralException(ErrorStatus.LETTERS_NOT_FOUND));

Member member;
if (userPrincipal != null) { //로그인한 경우에만 member 조회
member = memberRepository.findById(userPrincipal.getMemberId())
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));
} else {
member = null;
}


boolean isLiked = artletterLikesRepository.existsByMemberAndArtletter(member, artletter);
int likesCnt = artletterLikesRepository.countByArtletter(artletter);
Expand Down Expand Up @@ -188,14 +197,18 @@ private ArtletterDTO.ListResponseDto buildListResponseDto(Artletter artletter, i

@Override
public ResponseEntity<ApiResponse> getEditorArtletters(CustomUserPrincipal userPrincipal, ArtletterDTO.EditorRequestDto editorRequestDto) {
if (userPrincipal == null) {
throw new GeneralException(ErrorStatus.LOGIN_REQUIRED);
}

if (editorRequestDto == null || editorRequestDto.getArtletterIds() == null || editorRequestDto.getArtletterIds().isEmpty()) {
throw new GeneralException(ErrorStatus.ARTLETTER_ID_REQUIRED);
}
Member member = memberRepository.findById(userPrincipal.getMemberId())
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));

Member member;
if (userPrincipal != null) { //로그인한 경우에만 member 조회
member = memberRepository.findById(userPrincipal.getMemberId())
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));
} else {
member = null;
}

List<Long> artletterIds = editorRequestDto.getArtletterIds();
List<Artletter> artletters = artletterRepository.findByLetterIdIn(artletterIds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public ResponseEntity<ApiResponse> logout(@AuthenticationPrincipal CustomUserPri
}

@PostMapping("/refresh")
public ResponseEntity<ApiResponse> refreshAccessToken(@RequestAttribute("refreshToken") String refreshToken) {
public ResponseEntity<ApiResponse> refreshAccessToken(@RequestHeader("Refresh-Token") String refreshToken) {
return memberService.refreshAccessToken(refreshToken);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,4 @@ public interface MemberService {
MemberResponseDto.IdentityTestSaveResultDto updateIdentityTest(CustomUserPrincipal userPrincipal, MemberRequestDto.IdentityTestSaveDto request);
ResponseEntity<ApiResponse> getMember(CustomUserPrincipal userPrincipal);
ResponseEntity<ApiResponse> processGoogleLogin(String authorizationCode);
boolean existsByEmail(String email);
void registerNewMember(String email);
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,7 @@ public class MemberServiceImpl implements MemberService{
private final JwtUtil jwtUtil;
private final RedisTokenService redisTokenService;

// ✅ 이메일 존재 여부 확인
public boolean existsByEmail(String email) {
return memberRepository.existsByEmail(email);
}

// ✅ 새 회원 등록
public void registerNewMember(String email) {
Member newMember = Member.builder()
.email(email)
.role("ROLE_USER")
.build();
memberRepository.save(newMember);
}

// ✅ JWT 토큰 생성
@Override
@Transactional
public MemberResponseDto.LoginResultDto generateTokensForOidcUser(String email) {
Expand Down Expand Up @@ -134,9 +120,7 @@ public ResponseEntity<ApiResponse> registerMember(CustomUserPrincipal userPrinci
@Override
@Transactional
public ResponseEntity<ApiResponse> updateProfile(CustomUserPrincipal userPrincipal, MemberRequestDto.UpdateProfileDto request) {
if (userPrincipal == null) {
throw new GeneralException(ErrorStatus.LOGIN_REQUIRED);
}


Member member = memberRepository.findById(userPrincipal.getMemberId())
.orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down Expand Up @@ -49,8 +50,16 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
//로그인 없이 접근 가능
.requestMatchers("/.well-known/acme-challenge/**").permitAll()
.requestMatchers("/members/refresh", "/members/google", "/favicon.ico").permitAll()
.requestMatchers("/members/google", "/favicon.ico").permitAll()
.requestMatchers(HttpMethod.GET, "/artletters").permitAll() // 전체 아트레터 조회
.requestMatchers(HttpMethod.GET, "/artletters/search").permitAll() // 검색 API
.requestMatchers(HttpMethod.GET, "/artletters/**").permitAll() //특정 아트레터 조회
.requestMatchers(HttpMethod.GET, "/artletters/recommend-bar/category").permitAll() // 추천 카테고리
.requestMatchers(HttpMethod.GET, "/artletters/recommend-bar/keyword").permitAll() // 추천 키워드
.requestMatchers(HttpMethod.POST, "/artletters/editor-pick").permitAll()

.anyRequest().authenticated()
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
Expand Down Expand Up @@ -78,12 +87,7 @@ private void oidcLoginSuccessHandler(HttpServletRequest request,
OidcUser oidcUser = (OidcUser) authentication.getPrincipal();
String email = oidcUser.getEmail();

// ✅ 이메일 중복 체크 및 회원 등록
if (!memberService.existsByEmail(email)) {
memberService.registerNewMember(email); // 새 회원 등록
}

// ✅ JWT 토큰 발급
//JWT 토큰 발급
MemberResponseDto.LoginResultDto dto = memberService.generateTokensForOidcUser(email);

// SecurityContextHolder에 인증 정보 저장
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,36 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
throws IOException, ServletException {

try {

String requestURI = request.getRequestURI();
String method = request.getMethod();

// 로그인 없이 접근 가능한 경로 리스트
List<String> openEndpoints = List.of(
"/members/google",
"/favicon.ico",
"/artletters/search",
"/artletters/recommend-bar/category",
"/artletters/recommend-bar/keyword",
"/artletters/editor-pick"
);

if (method.equals("GET") && requestURI.startsWith("/artletters")&& !requestURI.contains("scrap")) {
filterChain.doFilter(request, response);
return;
}

if (requestURI.matches("^/artletters/\\d+$")) { // "/artletters/{letterId}" 패턴 허용
filterChain.doFilter(request, response);
return;
}

// 로그인 없이 접근 가능한 경로는 필터를 통과
if (openEndpoints.contains(requestURI)) {
filterChain.doFilter(request, response);
return;
}

String authHeader = request.getHeader("Authorization");

if (authHeader == null || !authHeader.startsWith("Bearer ")) {
Expand Down Expand Up @@ -122,7 +152,5 @@ private void handleRefreshRequest(HttpServletRequest request, String token) {
if (!storedRefreshToken.getRefreshToken().equals(refreshToken)) {
throw new GeneralException(ErrorStatus.INVALID_TOKEN);
}

request.setAttribute("refreshToken", refreshToken);
}
}

0 comments on commit 81e1c35

Please sign in to comment.