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주차 미션 / 서버 3조 김상균 #4

Open
wants to merge 6 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
6 changes: 6 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,17 @@ dependencies {
// H2
runtimeOnly 'com.h2database:h2'

// MySQL
runtimeOnly 'com.mysql:mysql-connector-j'

// JWT (Java JSON Web Token)
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'

// Swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'

// Lombok (Optional)
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.kuit.kuit4serverauth.argumentResolver;

import com.kuit.kuit4serverauth.dto.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(UserInfo.class);
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
String username = (String)request.getAttribute("username");
String role = (String)request.getAttribute("role");
return new UserInfo(username, role);
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.kuit.kuit4serverauth.config;

import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.OpenAPI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(info);
}

Info info = new Info().title("Kuit4 Server Auth").version("0.0.1").description(
"<h3>Kuit4 Server Auth</h3>");
}
18 changes: 14 additions & 4 deletions src/main/java/com/kuit/kuit4serverauth/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
package com.kuit.kuit4serverauth.config;

import com.kuit.kuit4serverauth.argumentResolver.UserInfoArgumentResolver;
import com.kuit.kuit4serverauth.interceptor.AuthInterceptor;
import lombok.RequiredArgsConstructor;
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
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
private final UserInfoArgumentResolver userInfoArgumentResolver;

public WebConfig(AuthInterceptor authInterceptor) {
this.authInterceptor = authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/profile")
.addPathPatterns("/admin");
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO /profile, /admin 앞에 붙이기
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(userInfoArgumentResolver);
}
}
Original file line number Diff line number Diff line change
@@ -1,43 +1,32 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.exception.CustomException;
import com.kuit.kuit4serverauth.exception.ErrorCode;
import com.kuit.kuit4serverauth.model.User;
import com.kuit.kuit4serverauth.dto.LoginRequest;
import com.kuit.kuit4serverauth.dto.TokenDTO;
import com.kuit.kuit4serverauth.repository.UserRepository;
import com.kuit.kuit4serverauth.service.AuthService;
import com.kuit.kuit4serverauth.service.JwtUtil;
import org.springframework.http.HttpStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequiredArgsConstructor
public class AuthController {
private final UserRepository userRepository;
private final JwtUtil jwtUtil;

public AuthController(UserRepository userRepository, JwtUtil jwtUtil) {
this.userRepository = userRepository;
this.jwtUtil = jwtUtil;
}
private final AuthService authService;

@PostMapping("/login")
public ResponseEntity<Map<String, String>> login(@RequestBody Map<String, String> credentials) {
String username = credentials.get("username");
String password = credentials.get("password");

User user = userRepository.findByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
throw new CustomException(ErrorCode.INVALID_USERNAME_OR_PASSWORD);
}
public ResponseEntity<TokenDTO> login(@RequestBody LoginRequest loginRequest) {
return ResponseEntity.ok(authService.login(loginRequest));
}

String token = jwtUtil.generateToken(user.getUsername(), user.getRole());
Map<String, String> response = new HashMap<>();
response.put("token", token);
return ResponseEntity.ok(response);
// 해당 url로 요청을 보내면 RefreshToken을 통해 AccessToken을 새로 발급해줌.
@PostMapping("/refresh-token")
public ResponseEntity<TokenDTO> refreshToken(@RequestBody TokenDTO tokenRequest) {
return ResponseEntity.ok(authService.refresh(tokenRequest));
}
}

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

import com.kuit.kuit4serverauth.dto.StoreCategoryOrderCountDTO;
import com.kuit.kuit4serverauth.service.CategoryService;
import lombok.RequiredArgsConstructor;
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.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class CategoryController {

private final CategoryService categoryService;

@GetMapping("/categories/{category_id}/most-ordered-store")
public ResponseEntity<List<StoreCategoryOrderCountDTO>> getMostOrderedStoreByCategory(@PathVariable("category_id") Long category_id) {
List<StoreCategoryOrderCountDTO> mostOrderedStore = categoryService.findMostOrderedStoreByCategory(category_id);
return ResponseEntity.ok(mostOrderedStore);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.dto.MenuStoreDTO;
import com.kuit.kuit4serverauth.service.MenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class MenuController {

private final MenuService menuService;

@GetMapping("/menus")
public ResponseEntity<List<MenuStoreDTO>> search(@RequestParam("menuName") String menuName) {
List<MenuStoreDTO> list = menuService.findMenuAndStoreNameByMenuName(menuName);

return ResponseEntity.ok(list);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.kuit.kuit4serverauth.controller;

import com.kuit.kuit4serverauth.model.Store;
import com.kuit.kuit4serverauth.service.StoreService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class StoreController {

private final StoreService storeService;

@GetMapping("/stores")
public ResponseEntity<List<Store>> getStores(@RequestParam("minimumOrderPrice") Integer minimumOrderPrice,
@RequestParam("status") String status) {
List<Store> stores = storeService.findStoresByConditions(minimumOrderPrice, status);

return ResponseEntity.ok(stores);
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,50 @@
package com.kuit.kuit4serverauth.controller;

import jakarta.servlet.http.HttpServletRequest;
import com.kuit.kuit4serverauth.dto.OrderInfoDTO;
import com.kuit.kuit4serverauth.dto.UserInfo;
import com.kuit.kuit4serverauth.model.Store;
import com.kuit.kuit4serverauth.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequiredArgsConstructor
public class UserController {

private final UserService userService;

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

@GetMapping("/admin")
public ResponseEntity<String> getAdmin(HttpServletRequest request) {
// TODO: role이 admin이면 "Hello, admin" 반환하기
public ResponseEntity<String> getAdmin(UserInfo userInfo) {
if (userInfo.getRole() != null && userInfo.getRole().equals("ROLE_ADMIN")) {
return ResponseEntity.ok("Hello, admin");
}
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Forbidden");
}

@GetMapping("/users/{userId}/orders")
public ResponseEntity<List<OrderInfoDTO>> getUsersAllOrders(@PathVariable Long userId) {
List<OrderInfoDTO> usersAllOrders = userService.findUsersAllOrders(userId);
return ResponseEntity.ok(usersAllOrders);
}

@GetMapping("/users/{userId}/ordered-stores")
public ResponseEntity<List<Store>> getStoresWithMultipleOrders(@PathVariable Long userId,
@RequestParam("minOrderCount") int minOrderCount) {
List<Store> stores = userService.findStoresWithMultipleOrders(userId, minOrderCount);
return ResponseEntity.ok(stores);
}
}
12 changes: 12 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/LoginRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.kuit.kuit4serverauth.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class LoginRequest {

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

import com.kuit.kuit4serverauth.model.Menu;
import com.kuit.kuit4serverauth.model.Store;
import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class MenuStoreDTO {
private Store store;
private Menu menu;
}
18 changes: 18 additions & 0 deletions src/main/java/com/kuit/kuit4serverauth/dto/OrderInfoDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.kuit.kuit4serverauth.dto;

import com.kuit.kuit4serverauth.model.Order;
import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class OrderInfoDTO {

Order order;
int totalPrice;
String storeName;
String menuName;

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

import com.kuit.kuit4serverauth.model.Category;
import com.kuit.kuit4serverauth.model.Store;
import lombok.*;

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class StoreCategoryOrderCountDTO {

Store store;
Category category;
int orderCount;

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

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class TokenDTO {

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

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

@Getter
@RequiredArgsConstructor
public class UserInfo {

private final String username;
private final String role;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
public enum ErrorCode {
INVALID_USERNAME_OR_PASSWORD(401, "Invalid username or password"),
INVALID_TOKEN(401, "Invalid or expired token"),
INVALID_REFRESH_TOKEN(401, "Invalid or expired refresh token"),
MISSING_AUTH_HEADER(401, "Missing or invalid Authorization header"),
FORBIDDEN_ACCESS(403, "Access denied"),
INTERNAL_SERVER_ERROR(500, "Internal server error");
Expand Down
Loading