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
@@ -0,0 +1,35 @@
package com.fastcampus.book_bot.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);

// ObjectMapper에 JSR310 모듈 추가
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

// Key는 String으로, Value는 JSON으로 직렬화
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));

template.afterPropertiesSet();
return template;
}
}
21 changes: 21 additions & 0 deletions src/main/java/com/fastcampus/book_bot/common/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.fastcampus.book_bot.common.config;

import com.fastcampus.book_bot.common.intercept.AuthInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

private final AuthInterceptor authInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/order/**", "/api/order/**")
.excludePathPatterns("/login", "/register");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.fastcampus.book_bot.common.intercept;

import com.fastcampus.book_bot.common.utils.JwtUtil;
import com.fastcampus.book_bot.domain.user.User;
import com.fastcampus.book_bot.service.auth.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

private final UserService userService;
private final JwtUtil jwtUtil;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try {
String authorization = request.getHeader("Authorization");
if (authorization == null || !authorization.startsWith("Bearer ")) {
response.sendRedirect("/login");
return false;
}

String accessToken = authorization.substring(7);

if (jwtUtil.isTokenExpired(accessToken)) {
response.sendRedirect("/login");
return false;
}

Integer userId = jwtUtil.extractUserId(accessToken);

User currentUser = userService.getUserById(userId);

request.setAttribute("currentUser", currentUser);

return true;
} catch (Exception e) {
log.error("interceptor: 인증 실패: {}", e.getMessage());
try {
response.sendRedirect("/login");
} catch (IOException ioException) {
log.error("리다이렉트 실패", ioException);
}
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,46 @@
package com.fastcampus.book_bot.controller;

import com.fastcampus.book_bot.domain.book.Book;
import com.fastcampus.book_bot.service.order.BestSellerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
@RequiredArgsConstructor
@Slf4j
public class MainController {

private final BestSellerService bestSellerService;

@GetMapping
public String main() {
public String main(Model model) {
try {
// 월간 베스트셀러 데이터 조회 및 캐시 업데이트
bestSellerService.getMonthBestSeller();
List<Book> monthlyBestSellers = bestSellerService.getMonthBestSeller();

// 주간 베스트셀러 데이터 조회 및 캐시 업데이트
bestSellerService.getWeekBestSeller();
List<Book> weeklyBestSellers = bestSellerService.getWeekBestSeller();

// 모델에 데이터 추가
model.addAttribute("monthlyBestSellers", monthlyBestSellers);
model.addAttribute("weeklyBestSellers", weeklyBestSellers);

log.info("BestSellers loaded - Monthly: {}, Weekly: {}",
monthlyBestSellers.size(), weeklyBestSellers.size());

} catch (Exception e) {
log.error("Error loading bestsellers", e);
// 에러 발생시 빈 리스트로 처리
model.addAttribute("monthlyBestSellers", List.of());
model.addAttribute("weeklyBestSellers", List.of());
}

return "index";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.fastcampus.book_bot.controller.order;

import com.fastcampus.book_bot.common.response.SuccessApiResponse;
import com.fastcampus.book_bot.domain.user.User;
import com.fastcampus.book_bot.dto.order.OrdersDTO;
import com.fastcampus.book_bot.service.order.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -17,10 +19,13 @@ public class OrderController {
private final OrderService orderService;

@PostMapping("/complete")
public ResponseEntity<SuccessApiResponse<Void>> orderComplete(OrdersDTO ordersDTO) {
public ResponseEntity<SuccessApiResponse<Void>> orderComplete(OrdersDTO ordersDTO,
HttpServletRequest request) {

orderService.orderBook(ordersDTO);
User user = (User) request.getAttribute("currentUser");

return ResponseEntity.ok(SuccessApiResponse.of(""));
orderService.saveOrder(user, ordersDTO);

return ResponseEntity.ok(SuccessApiResponse.of("엔티티 저장 완료"));
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,37 @@
package com.fastcampus.book_bot.controller.order;

import com.fastcampus.book_bot.domain.user.User;
import com.fastcampus.book_bot.dto.order.OrderCalculationResult;
import com.fastcampus.book_bot.dto.order.OrdersDTO;
import com.fastcampus.book_bot.service.grade.GradeStrategyFactory;
import com.fastcampus.book_bot.service.order.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@RequiredArgsConstructor
public class OrderViewController {

private final OrderService orderService;

@PostMapping("/order")
public String order(@ModelAttribute("orderForm") OrdersDTO ordersDTO) {
public String order(@ModelAttribute("orderForm") OrdersDTO ordersDTO,
HttpServletRequest request,
Model model) {

User user = (User) request.getAttribute("currentUser");
OrderCalculationResult result = orderService.calculateOrder(ordersDTO, user);

model.addAttribute("calculationResult", result);
model.addAttribute("currentUser", user);
model.addAttribute("userGrade", user.getUserGrade());
model.addAttribute("userPoints", user.getPoint());

return "order/order";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class User {
@Column(name = "USER_ID", nullable = false, updatable = false)
private Integer userId;

@ManyToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "GRADE_ID", nullable = false, insertable = false)
private UserGrade userGrade;

Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading