Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8주차 미션 / 서버 2조 김민진 #20

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ dependencies {
// Spring Boot Starter JDBC
implementation 'org.springframework.boot:spring-boot-starter-jdbc'

// H2
runtimeOnly 'com.h2database:h2'
// MySQL
implementation 'mysql:mysql-connector-java:8.0.33'

// JWT (Java JSON Web Token)
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

import com.kuit.kuit4serverauth.interceptor.AuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
Expand All @@ -16,5 +19,7 @@ public WebConfig(AuthInterceptor authInterceptor) {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO /profile, /admin 앞에 붙이기
registry.addInterceptor(authInterceptor)
.addPathPatterns("/profile", "/admin");
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.dto.LoginReqDto;
import com.kuit.kuit4serverauth.dto.LoginResDto;
import com.kuit.kuit4serverauth.dto.RefreshTokenReqDto;
import com.kuit.kuit4serverauth.dto.RefreshTokenResponseDto;
import com.kuit.kuit4serverauth.exception.CustomException;
import com.kuit.kuit4serverauth.exception.ErrorCode;
import com.kuit.kuit4serverauth.model.AuthUser;
import com.kuit.kuit4serverauth.model.User;
import com.kuit.kuit4serverauth.repository.UserRepository;
import com.kuit.kuit4serverauth.service.JwtUtil;
Expand All @@ -11,8 +16,6 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthController {
Expand All @@ -24,20 +27,40 @@ public AuthController(UserRepository userRepository, JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}

/* TODO : dto로 변환 */
@PostMapping("/login")
public ResponseEntity<Map<String, String>> login(@RequestBody Map<String, String> credentials) {
String username = credentials.get("username");
String password = credentials.get("password");
public ResponseEntity<LoginResDto> login(@RequestBody LoginReqDto dto) {
String username = dto.getUsername();
String password = dto.getPassword();

User user = userRepository.findByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
throw new CustomException(ErrorCode.INVALID_USERNAME_OR_PASSWORD);
}

String token = jwtUtil.generateToken(user.getUsername(), user.getRole());
Map<String, String> response = new HashMap<>();
response.put("token", token);
return ResponseEntity.ok(response);
String token = jwtUtil.generateAccessToken(user.getUsername(), user.getRole());
LoginResDto response = LoginResDto.builder()
.token(token)
.build();
return ResponseEntity.status(HttpStatus.OK).body(response);
}

@PostMapping("/refresh")
public ResponseEntity<RefreshTokenResponseDto> refreshToken(@RequestBody RefreshTokenReqDto dto,
AuthUser authUser) {

String accessToken = dto.getAccessToken();

boolean isExpired = jwtUtil.isTokenExpired(accessToken);
if (isExpired) {
String username = authUser.getUsername();
String refreshToken = jwtUtil.generateRefreshToken(username);
RefreshTokenResponseDto response = RefreshTokenResponseDto.builder()
.RefreshToken(refreshToken)
.build();
return ResponseEntity.status(HttpStatus.OK).body(response);
}
throw new CustomException(ErrorCode.INVALID_TOKEN);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.dto.OrderListResDto;
import com.kuit.kuit4serverauth.dto.RestaurantResDto;
import com.kuit.kuit4serverauth.dto.TwiceOrderedResDto;
import com.kuit.kuit4serverauth.enums.Category;
import com.kuit.kuit4serverauth.service.OrderService;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

private final OrderService orderService;

// 기능 요구사항 3 : 특정 회원이 두번 이상 주문한 음식점 조회 (중복 제거)
@GetMapping("/{userId}/twice-ordered")
public ResponseEntity<List<TwiceOrderedResDto>> getTwiceOrderedRestaurant(@PathVariable("userId") Long userId) {
List<TwiceOrderedResDto> response = orderService.getTwiceOrderedRestaurant(userId);
return new ResponseEntity<>(response, HttpStatus.OK);
}

// 기능 요구사항 4 : 카테고리별 인기 음식점 조회 (상위 10개 반환)
@GetMapping("/category-top/{category}")
public ResponseEntity<List<RestaurantResDto>> getTopRestaurantsByCategory(@PathVariable("category") Category category) {
List<RestaurantResDto> response = orderService.getTopRestaurantsByCategory(category);
return new ResponseEntity<>(response, HttpStatus.OK);
}

// 기능 요구사항 5 : 특정 회원의 주문 내역 조회 (가격 순으로 정렬)
@GetMapping("/{userId}/order-list")
public ResponseEntity<List<OrderListResDto>> getUserOrderList(@PathVariable("userId") Long userId) {
List<OrderListResDto> response = orderService.getUserOrderList(userId);
return new ResponseEntity<>(response, HttpStatus.OK);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.dto.RestaurantMenuResDto;
import com.kuit.kuit4serverauth.dto.RestaurantResDto;
import com.kuit.kuit4serverauth.service.RestaurantService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/restaurant")
@RequiredArgsConstructor
public class RestaurantController {

private final RestaurantService restaurantService;

// 기능 요구사항 1 : 최소 주문 금액 이하 음식점 조회
@GetMapping("/least-price")
public ResponseEntity<List<RestaurantResDto>> getRestaurantByLeastDeliveryPrice(@RequestParam("leastPrice") String leastPrice) {
List<RestaurantResDto> response = restaurantService.getRestaurantByLeastDeliveryPrice(leastPrice);
return new ResponseEntity<>(response, HttpStatus.OK);
}

// 기능 요구사항 2 : 특정 메뉴 이름이 포함된 메뉴와 음식점 조회
@GetMapping("/containing-menu")
public ResponseEntity<List<RestaurantMenuResDto>> getRestaurantByContainingMenu(@RequestParam("menu") String menu) {
List<RestaurantMenuResDto> response = restaurantService.getRestaurantByContainingMenu(menu);
return new ResponseEntity<>(response, HttpStatus.OK);
}


}
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.model.AuthUser;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
public class UserController {

@GetMapping("/profile")
public ResponseEntity<String> getProfile(HttpServletRequest request) {
// TODO : 로그인 한 사용자면 username 이용해 "Hello, {username}" 반환하기
String username = (String) request.getAttribute("username");
if (username.equals("user")) {
return ResponseEntity.status(HttpStatus.OK).body("Hello, " + username);
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
}



@GetMapping("/admin")
public ResponseEntity<String> getAdmin(HttpServletRequest request) {
// TODO: role이 admin이면 "Hello, admin" 반환하기

String role = (String) request.getAttribute("role");
if (role.equals("ROLE_ADMIN")) {
return ResponseEntity.status(HttpStatus.OK).body("Hello, admin");
}
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Forbidden");
}

}
12 changes: 12 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/LoginReqDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.kuit.kuit4serverauth.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class LoginReqDto {

private String username;
private String password;
}
11 changes: 11 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/LoginResDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.kuit.kuit4serverauth.dto;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class LoginResDto {

private String token;
}
12 changes: 12 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/MenuNameResDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.kuit.kuit4serverauth.dto;

import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class MenuNameResDto {
private String menuName;
}
22 changes: 22 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/OrderListResDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.kuit.kuit4serverauth.dto;

import lombok.Builder;
import lombok.Getter;

import java.time.LocalDateTime;

@Getter
@Builder
public class OrderListResDto {

private Long orderId;
private LocalDateTime orderDate;
private String restaurantName;
private Long menuId;
private String menuName;
private String optionName;
private Integer optionPrice;
private Double totalPrice;
private Long userId;

}
13 changes: 13 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/RefreshTokenReqDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.kuit.kuit4serverauth.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class RefreshTokenReqDto {

private String accessToken;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.kuit.kuit4serverauth.dto;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class RefreshTokenResponseDto {

private String RefreshToken;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.kuit.kuit4serverauth.dto;

import com.kuit.kuit4serverauth.enums.Category;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class RestaurantMenuResDto {

private Long restaurantId;
private String restaurantName;
private int leastDeliveryPrice;
private String status;
private Category category;
private Long menuId;
private String menuName;

}
17 changes: 17 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/RestaurantResDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.kuit.kuit4serverauth.dto;

import com.kuit.kuit4serverauth.enums.Category;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class RestaurantResDto {

private Long restaurantId;
private String restaurantName;
private int leastDeliveryPrice;
private String status;
private Category category;

}
17 changes: 17 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/TwiceOrderedResDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.kuit.kuit4serverauth.dto;

import com.kuit.kuit4serverauth.enums.Category;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class TwiceOrderedResDto {

private Long userId;
private Long restaurantId;
private String restaurantName;
private int leastDeliveryPrice;
private String status;
private Category category;
}
Loading