Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ public HabitSliceResponseDTO getHabits(Long userId, Integer page, Integer size)

@Override
public List<HabitResponseDTO> getDailyHabitCheckedState(Long userId, LocalDate date) {
User currentUser = getCurrentUser(userId);

List<Habit> habits = habitRepository.findAllHabitsWithLogsOnDate(userId, date);

Expand All @@ -71,9 +70,8 @@ public List<HabitResponseDTO> getDailyHabitCheckedState(Long userId, LocalDate d

@Override
public List<HabitWeeklyChecksResponseDTO> getWeeklyChecks(Long userId, LocalDate startDate) {
User currentUser = getCurrentUser(userId);

List<Habit> allHabitsWithLogsOnDateRange = habitRepository.findAllHabitsWithLogsOnDateRange(currentUser.getId(),
List<Habit> allHabitsWithLogsOnDateRange = habitRepository.findAllHabitsWithLogsOnDateRange(userId,
startDate, startDate.plusDays(6));

return allHabitsWithLogsOnDateRange.stream()
Expand All @@ -84,7 +82,6 @@ public List<HabitWeeklyChecksResponseDTO> getWeeklyChecks(Long userId, LocalDate

@Override
public List<HabitMonthlyChecksResponseDTO> getMonthlyChecks(Long userId, YearMonth yearMonth) {
User currentUser = getCurrentUser(userId);

List<Habit> habits = habitRepository.findAllHabitsWithLogsOnMonth(userId, yearMonth);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,13 @@ public class HabitLog extends BaseEntity {
private LocalDate checkedAt = LocalDate.now();

//== 정적 팩토리 생성 메서드 ==//
public static HabitLog createHabitLog(Habit habit) {
public static void createHabitLog(Habit habit) {
HabitLog habitLog = HabitLog.builder()
.habit(habit)
.build();

habit.getHabitLogs().add(habitLog);

return habitLog;
}

//== 더티체킹 메서드 ==//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ public ApiResponse<MemoDetailResponseDTO> getMemoDetail(
}

@PatchMapping("/{memoId}")
@Operation(
summary = "메모 수정",
description = "특정 메모를 수정합니다. 본인이 작성한 메모만 수정이 가능합니다."
)
public ApiResponse<MemoDetailResponseDTO> updateMemo(
@Parameter(description = "메모 ID", required = true, example = "1")
@PathVariable Long memoId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
import org.hibernate.annotations.DynamicUpdate;

import com.indayvidual.server.common.BaseEntity;
import com.indayvidual.server.domain.memo.exception.MemoException;
import com.indayvidual.server.domain.user.entity.User;
import com.indayvidual.server.global.api.code.status.ErrorStatus;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
Expand Down Expand Up @@ -67,21 +65,5 @@ public void updateContent(String content) {
}

//== 비즈니스 로직 ==//
public boolean isOwnerBy(User user) {
return this.user.equals(user);
}

public void ensureOwnership(User user) {
if (!isOwnerBy(user)) {
throw new MemoException(ErrorStatus.MEMO_OWNER_MISMATCH);
}
}

public boolean canDeleteMemo(User user) {
ensureOwnership(user);

user.getMemos().remove(this);

return true;
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.indayvidual.server.domain.memo.repository;

import java.util.Optional;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -9,5 +11,7 @@

@Repository
public interface MemoRepository extends JpaRepository<Memo, Long> {
Optional<Memo> findByIdAndUserId(Long memoId, Long userId);

Slice<Memo> findByUserIdOrderByCreatedAtDescIdDesc(Long userId, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import com.indayvidual.server.domain.memo.exception.MemoException;
import com.indayvidual.server.domain.memo.repository.MemoRepository;
import com.indayvidual.server.domain.user.entity.User;
import com.indayvidual.server.domain.user.exception.UserException;
import com.indayvidual.server.domain.user.repository.UserRepository;
import com.indayvidual.server.global.api.code.status.ErrorStatus;

Expand Down Expand Up @@ -40,36 +39,31 @@ public MemoDetailResponseDTO createMemo(Long userId, CreateMemoRequestDTO reques

@Override
public Void deleteMemo(Long userId, Long memoId) {
User currentUser = getCurrentUser(userId);

Memo memo = getMemo(memoId);
Memo memo = getMemoByMemoIdAndUserId(memoId, userId);

if (memo.canDeleteMemo(currentUser)) {
memoRepository.delete(memo);
}
memoRepository.delete(memo);

return null;
}

@Override
public MemoDetailResponseDTO updateMemo(Long userId, Long memoId, UpdateMemoRequestDTO request) {
User currentUser = getCurrentUser(userId);

Memo memo = getMemo(memoId);
Memo memo = getMemoByMemoIdAndUserId(memoId, userId);

memo.updateTitle(request.getTitle());
memo.updateContent(request.getContent());

return MemoDetailResponseDTO.from(memo);
}

private Memo getMemo(Long memoId) {
return memoRepository.findById(memoId)
.orElseThrow(() -> new MemoException(ErrorStatus.MEMO_NOT_FOUND));
}

private User getCurrentUser(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new UserException(ErrorStatus.USER_NOT_FOUND));
.orElseThrow(() -> new MemoException(ErrorStatus.USER_NOT_FOUND));
}

private Memo getMemoByMemoIdAndUserId(Long memoId, Long userId) {
return memoRepository.findById(memoId)
.orElseThrow(() -> new MemoException(ErrorStatus.MEMO_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
import com.indayvidual.server.domain.memo.entity.Memo;
import com.indayvidual.server.domain.memo.exception.MemoException;
import com.indayvidual.server.domain.memo.repository.MemoRepository;
import com.indayvidual.server.domain.user.entity.User;
import com.indayvidual.server.domain.user.exception.UserException;
import com.indayvidual.server.domain.user.repository.UserRepository;
import com.indayvidual.server.global.api.code.status.ErrorStatus;
import com.indayvidual.server.global.util.Utils;

Expand All @@ -28,7 +25,6 @@
public class MemoQueryServiceImpl implements MemoQueryService {

private final MemoRepository memoRepository;
private final UserRepository userRepository;

@Override
public MemoSliceResponseDTO getMemosWithSlice(Long userId, Integer page, Integer size) {
Expand All @@ -44,17 +40,10 @@ public MemoSliceResponseDTO getMemosWithSlice(Long userId, Integer page, Integer

@Override
public MemoDetailResponseDTO getMemoDetail(Long userId, Long memoId) {
User currentUser = userRepository.findById(userId)
.orElseThrow(() -> new UserException(ErrorStatus.USER_NOT_FOUND));

Memo memo = memoRepository.findById(memoId)
Memo memo = memoRepository.findByIdAndUserId(memoId, userId)
.orElseThrow(() -> new MemoException(ErrorStatus.MEMO_NOT_FOUND));

// 만약 접근하는 사용자가 메모의 소유자가 아니라면 접근 금지
if (!memo.getUser().equals(currentUser)) {
throw new MemoException(ErrorStatus.MEMO_OWNER_MISMATCH);
}

return MemoDetailResponseDTO.from(memo);
}

Expand Down
11 changes: 9 additions & 2 deletions src/main/java/com/indayvidual/server/global/util/Utils.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
package com.indayvidual.server.global.util;

import com.indayvidual.server.global.config.security.JwtUserPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.indayvidual.server.domain.user.exception.UserException;
import com.indayvidual.server.global.api.code.status.ErrorStatus;
import com.indayvidual.server.global.config.security.JwtUserPrincipal;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Utils {

private static final int DEFAULT_PAGE_SIZE = 20;
Expand All @@ -22,7 +29,7 @@ public static int validatePageSize(Integer size) {
public static Long getUserId() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !(auth.getPrincipal() instanceof JwtUserPrincipal jwt)) {
throw new IllegalStateException("인증되지 않은 사용자입니다.");
throw new UserException(ErrorStatus._UNAUTHORIZED);
}
return jwt.userId();
}
Expand Down