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
@@ -1,10 +1,12 @@
package com.webservice.algorithmchef.config;

import com.google.genai.Client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.genai.Client;


@Configuration
public class GeminiConfig {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

// 1. JWT 헤더가 없거나 'Bearer'가 아닌 경우
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
log.warn("Authorization 헤더가 없거나 Bearer 타입이 아님");
log.debug("헤더에 토큰이 없어 비로그인 상태로 다음 필터 진행: {}", request.getRequestURI());
filterChain.doFilter(request, response);
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package com.webservice.algorithmchef.config;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import lombok.RequiredArgsConstructor;

Expand All @@ -24,6 +28,7 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(org.springframework.security.config.Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable);
Expand All @@ -36,12 +41,30 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/auth/login", "/auth/signUp",
"/auth/findPassword", "/auth/findUserId").permitAll()
//.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated());

http
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

return http.build();
}

// @Bean
// public CorsConfigurationSource corsConfigurationSource() {
// CorsConfiguration configuration = new CorsConfiguration();
//
// // 1. 프론트엔드 포트 확인! (5173인지 3000인지 본인 환경에 맞춰주세요)
// // 둘 다 넣어두면 안전합니다.
// configuration.setAllowedOrigins(List.of("http://localhost:5173"));
//
// configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
// configuration.setAllowedHeaders(List.of("*"));
// configuration.setAllowCredentials(true);
//
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", configuration);
// return source;
// }

}
18 changes: 18 additions & 0 deletions src/main/java/com/webservice/algorithmchef/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.webservice.algorithmchef.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH");
//.allowCredentials(true);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ public ResponseEntity<?> signUp(@RequestBody UserSignUpRequest userSignUpRequest
}
}

@Transactional
@PatchMapping("/findPassword")
public ResponseEntity<?> findPassword(@RequestBody FindPasswordRequest fPasswordRequest){
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ public class BoardController {
// 게시글 목록 조회(게시판)
@GetMapping("/posts")
public ResponseEntity<BoardPostListResponse> getPostList(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "createdAt,desc") String sort,
@RequestParam(required = false) String filter
@RequestParam(defaultValue = "0",value="page") int page,
@RequestParam(defaultValue = "20",value="size") int size,
@RequestParam(defaultValue = "createdAt,desc",value="sort") String sort,
@RequestParam(required = false,value="filter") String filter
) {
BoardPostListResponse response = boardService.getPostList(page, size, sort, filter);
return ResponseEntity.ok(response);
Expand All @@ -55,10 +55,10 @@ public ResponseEntity<Map<String, String>> createPost(
// 게시글 조회
@GetMapping("/post/{postId}")
public ResponseEntity<BoardPostResponse> getPostDetail(
@PathVariable Long postId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "createdAt,asc") String sort
@PathVariable("postId") Long postId,
@RequestParam(defaultValue = "0",value="page") int page,
@RequestParam(defaultValue = "20",value="size") int size,
@RequestParam(defaultValue = "createdAt,asc",value="sort") String sort
) {
try {
BoardPostResponse response = boardService.getPostDetail(postId, page, size, sort);
Expand All @@ -71,7 +71,7 @@ public ResponseEntity<BoardPostResponse> getPostDetail(
// 댓글 작성
@PostMapping("/post/{postId}/comment")
public ResponseEntity<Map<String, String>> createComment(
@PathVariable Long postId,
@PathVariable("postId") Long postId,
@RequestBody BoardCommentRequest requestDto,
@AuthenticationPrincipal UserDetails userDetails
) {
Expand All @@ -91,10 +91,10 @@ public ResponseEntity<Map<String, String>> createComment(
// 대댓글 조회
@GetMapping("/comments/{commentId}/replies")
public ResponseEntity<CommentReplyListResponse> getReplies(
@PathVariable Long commentId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "createdAt,asc") String sort
@PathVariable("commentId") Long commentId,
@RequestParam(defaultValue = "0",value="page") int page,
@RequestParam(defaultValue = "10",value="size") int size,
@RequestParam(defaultValue = "createdAt,asc",value="sort") String sort
) {
try {
CommentReplyListResponse response = boardService.getReplies(commentId, page, size, sort);
Expand All @@ -107,7 +107,7 @@ public ResponseEntity<CommentReplyListResponse> getReplies(
// 게시글 수정
@PutMapping("/post/{postId}")
public ResponseEntity<Map<String, String>> updatePost(
@PathVariable Long postId,
@PathVariable("postId") Long postId,
@RequestBody BoardPostRequest requestDto,
@AuthenticationPrincipal UserDetails userDetails
) {
Expand All @@ -133,7 +133,7 @@ public ResponseEntity<Map<String, String>> updatePost(
// 게시글 삭제
@DeleteMapping("/post/{postId}")
public ResponseEntity<Map<String, String>> deletePost(
@PathVariable Long postId,
@PathVariable("postId") Long postId,
@AuthenticationPrincipal UserDetails userDetails
) {
if (userDetails == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public ResponseEntity<List<GeminiRecipeResponse>> recommendCondition(@RequestBod
@PostMapping("/expir")
public ResponseEntity<List<GeminiRecipeResponse>> recommendExpir(@RequestBody ExpirRequest request) {
log.info("재료 추천 요청 - userId: {}", request.userId());
log.info("요청한 재료",request);
return ResponseEntity.ok(
recipeService.recommendExpir(request.userId(), request.ingredients(), request.excludedTitles())
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

@RestController
@RequestMapping("/api/recipes")
@CrossOrigin(origins = "http://localhost:3000")
//@CrossOrigin(origins = "http://localhost:3000")
public class RecipeSearchController {

private final RecipeService recipeService;
Expand All @@ -20,7 +20,7 @@ public RecipeSearchController(RecipeService recipeService) {
}

@GetMapping("/search")
public ResponseEntity<?> getRandomRecipe(@RequestParam String ingredient) {
public ResponseEntity<?> getRandomRecipe(@RequestParam("ingredient") String ingredient) {

Recipe recipe = recipeService.getRandomRecipeByIngredient(ingredient);

Expand All @@ -32,7 +32,7 @@ public ResponseEntity<?> getRandomRecipe(@RequestParam String ingredient) {
}

@GetMapping("/search-multi")
public ResponseEntity<?> getRandomRecipeMultiple(@RequestParam String ingredients) {
public ResponseEntity<?> getRandomRecipeMultiple(@RequestParam("ingredients") String ingredients) {

List<String> ingList =
Arrays.stream(ingredients.split(","))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:3000")
//@CrossOrigin(origins = "http://localhost:3000")
@RequiredArgsConstructor
public class SttController {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import com.webservice.algorithmchef.dto.fridgeingredient.ChangeFridgeIngredientRequest;
import com.webservice.algorithmchef.dto.fridgeingredient.ChangeFridgeIngredientResponse;
import com.webservice.algorithmchef.dto.userfridge.FridgeBatchUpdateRequest;
import com.webservice.algorithmchef.dto.userfridge.PageUserFridgeResponse;
import com.webservice.algorithmchef.dto.userfridge.UserFridgeRequest;
import com.webservice.algorithmchef.dto.userfridge.UserFridgeResponse;
import com.webservice.algorithmchef.service.UserFridgeService;
Expand All @@ -44,28 +43,22 @@ public ResponseEntity<?> registerIngredients(@RequestBody UserFridgeRequest frid
}

@GetMapping("/ingredients")
public ResponseEntity<?> retrieve(
@RequestParam(value="category",required = false)String category,
@RequestParam(value="name",required = false)String name,
@RequestParam(value="page", defaultValue = "0")int page,
@RequestParam(value="size", defaultValue = "10")int size,
@AuthenticationPrincipal UserDetails userDetails){
try {
String userId = userDetails.getUsername();
PageUserFridgeResponse response = null;
if(category != null) {
response = userFridgeService.filteredByCategory(userId, category, size, page);
}else if(name != null) {
response = userFridgeService.filteredByName(userId, name, size, page);
}else {
response = userFridgeService.retrieveAll(userId, size, page);
}
return ResponseEntity.ok(response);
}catch(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}

}
public ResponseEntity<?> retrieve(
@RequestParam(value = "category", required = false) String category,
@AuthenticationPrincipal UserDetails userDetails) {
try {
String userId = userDetails.getUsername();
UserFridgeResponse response;
if (category != null) {
response = userFridgeService.filteredByCategory(userId, category);
} else {
response = userFridgeService.retrieveAll(userId);
}
return ResponseEntity.ok(response);
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}

@PatchMapping("/ingredient/update")
public ResponseEntity<?> updatePurchasedDate(@RequestBody ChangeFridgeIngredientRequest request,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ public static class BoardPostSimple {
private String createdAt;
private String category;
private String content; // 목록 미리보기용
private Long postId;

public static BoardPostSimple from(BoardPost post) {
return BoardPostSimple.builder()
.title(post.getTitle())
.postId(post.getPostId())
// User 엔티티의 userId (로그인 아이디) 사용
.userId(post.getUser().getUserId())
// 날짜 포맷팅 (yyyy-MM-dd)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ public class ChangeFridgeIngredientRequest {

private Long ingredientId;
private LocalDateTime purchasedDate;
private LocalDateTime expiredDate;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class GeminiRecipeRequest {

// 1. 성향 기반 추천 요청
Expand All @@ -21,8 +23,11 @@ public record ConditionRequest(

// 3. 임박한 재료 추천 요청
public record ExpirRequest(
@JsonProperty("userId")
String userId,
@JsonProperty("excludedTitles")
List<String> excludedTitles,
@JsonProperty("ingredients")
List<String> ingredients // 소비기한 임박 재료
) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

import com.webservice.algorithmchef.model.User;

import lombok.Getter;

@Getter
public class FindPasswordResponse {

private String userId;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.webservice.algorithmchef.dto.user;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class UserLoginRequest {

private String userId;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package com.webservice.algorithmchef.repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;

import com.webservice.algorithmchef.model.Fridge;
import com.webservice.algorithmchef.model.FridgeIngredient;

public interface FridgeIngredientRepository extends JpaRepository<FridgeIngredient, Long> {

Page<FridgeIngredient> findByFridge(Fridge fridge,Pageable pageable);
Page<FridgeIngredient> findByFridgeAndIngredient_NameContaining(Fridge fridge,String name,Pageable pageable);
Page<FridgeIngredient> findByFridgeAndIngredient_Category(Fridge fridge,String category,Pageable pageable);
List<FridgeIngredient> findByFridge(Fridge fridge,Sort sort);
//Page<FridgeIngredient> findByFridgeAndIngredient_NameContaining(Fridge fridge,String name,Pageable pageable);
List<FridgeIngredient> findByFridgeAndIngredient_Category(Fridge fridge,String category,Sort sort);
Optional<FridgeIngredient> findByIdAndFridge(Long id, Fridge fridge);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.webservice.algorithmchef.model.User;

public interface UserRepository extends JpaRepository<User, Long> {

public Optional<User> findByUserId(String userId);
public Optional<User> findByEmailAndBirthDate(String email,LocalDateTime birthDate);
@Query("SELECT u FROM User u LEFT JOIN FETCH u.userPreference WHERE u.userId = :userId")
Optional<User> findByUserIdWithPreference(@Param("userId") String userId);

}
Loading