upd
This commit is contained in:
64
backend/pom.xml
Normal file
64
backend/pom.xml
Normal file
@@ -0,0 +1,64 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.toyshop</groupId>
|
||||
<artifactId>backend</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.2.5</version>
|
||||
</parent>
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<jjwt.version>0.11.5</jjwt.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
11
backend/src/main/java/com/toyshop/ToyShopApplication.java
Normal file
11
backend/src/main/java/com/toyshop/ToyShopApplication.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.toyshop;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ToyShopApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ToyShopApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.toyshop.config;
|
||||
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.entity.UserRole;
|
||||
import com.toyshop.repository.UserRepository;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class DataInitializer {
|
||||
@Bean
|
||||
public CommandLineRunner initAdmin(UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
||||
return args -> {
|
||||
if (userRepository.countByRole(UserRole.ADMIN) == 0) {
|
||||
User admin = new User();
|
||||
admin.setUsername("admin");
|
||||
admin.setPassword(passwordEncoder.encode("admin123"));
|
||||
admin.setRole(UserRole.ADMIN);
|
||||
userRepository.save(admin);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.toyshop.config;
|
||||
|
||||
import com.toyshop.dto.ApiResponse;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class RestExceptionHandler {
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<?> handleIllegalArgument(IllegalArgumentException ex) {
|
||||
return ApiResponse.fail(ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<?> handleValidation(MethodArgumentNotValidException ex) {
|
||||
String msg = ex.getBindingResult().getAllErrors().isEmpty()
|
||||
? "参数错误"
|
||||
: ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
|
||||
return ApiResponse.fail(msg);
|
||||
}
|
||||
}
|
||||
70
backend/src/main/java/com/toyshop/config/SecurityConfig.java
Normal file
70
backend/src/main/java/com/toyshop/config/SecurityConfig.java
Normal file
@@ -0,0 +1,70 @@
|
||||
package com.toyshop.config;
|
||||
|
||||
import com.toyshop.security.JwtAuthenticationFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
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 java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final com.toyshop.security.CustomUserDetailsService userDetailsService;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
com.toyshop.security.CustomUserDetailsService userDetailsService) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.userDetailsService = userDetailsService;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf(csrf -> csrf.disable())
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/auth/**", "/api/public/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager() {
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setPasswordEncoder(passwordEncoder());
|
||||
return new ProviderManager(provider);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(List.of("*"));
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.toyshop.controller;
|
||||
|
||||
import com.toyshop.dto.*;
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.entity.UserRole;
|
||||
import com.toyshop.repository.UserRepository;
|
||||
import com.toyshop.service.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
private final AuthService authService;
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public AuthController(AuthService authService, UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
||||
this.authService = authService;
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public ApiResponse<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
|
||||
String token = authService.register(request);
|
||||
return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername()));
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<AuthResponse> login(@Valid @RequestBody AuthRequest request) {
|
||||
String token = authService.login(request);
|
||||
return ApiResponse.ok(new AuthResponse(token, "USER", request.getUsername()));
|
||||
}
|
||||
|
||||
@PostMapping("/admin/login")
|
||||
public ApiResponse<AuthResponse> adminLogin(@Valid @RequestBody AuthRequest request) {
|
||||
User user = userRepository.findByUsername(request.getUsername()).orElseThrow();
|
||||
if (user.getRole() != UserRole.ADMIN) {
|
||||
return ApiResponse.fail("非管理员账号");
|
||||
}
|
||||
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
return ApiResponse.fail("用户名或密码错误");
|
||||
}
|
||||
String token = authService.login(request);
|
||||
return ApiResponse.ok(new AuthResponse(token, "ADMIN", request.getUsername()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.toyshop.controller;
|
||||
|
||||
import com.toyshop.dto.ApiResponse;
|
||||
import com.toyshop.entity.Product;
|
||||
import com.toyshop.repository.CarouselRepository;
|
||||
import com.toyshop.repository.NoticeRepository;
|
||||
import com.toyshop.repository.ProductRepository;
|
||||
import com.toyshop.repository.CategoryRepository;
|
||||
import com.toyshop.service.ProductService;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/public")
|
||||
public class PublicController {
|
||||
private final ProductService productService;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final ProductRepository productRepository;
|
||||
private final CarouselRepository carouselRepository;
|
||||
private final NoticeRepository noticeRepository;
|
||||
|
||||
public PublicController(ProductService productService, CategoryRepository categoryRepository,
|
||||
ProductRepository productRepository, CarouselRepository carouselRepository,
|
||||
NoticeRepository noticeRepository) {
|
||||
this.productService = productService;
|
||||
this.categoryRepository = categoryRepository;
|
||||
this.productRepository = productRepository;
|
||||
this.carouselRepository = carouselRepository;
|
||||
this.noticeRepository = noticeRepository;
|
||||
}
|
||||
|
||||
@GetMapping("/home")
|
||||
public ApiResponse<Map<String, Object>> home() {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("carousels", carouselRepository.findAllByOrderBySortOrderAsc());
|
||||
data.put("notices", noticeRepository.findAll());
|
||||
data.put("categories", categoryRepository.findAll());
|
||||
data.put("hot", productService.search(null, null, "sales"));
|
||||
data.put("newest", productService.search(null, null, null));
|
||||
return ApiResponse.ok(data);
|
||||
}
|
||||
|
||||
@GetMapping("/products")
|
||||
public ApiResponse<?> products(@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Long categoryId,
|
||||
@RequestParam(required = false) String sort) {
|
||||
return ApiResponse.ok(productService.search(keyword, categoryId, sort));
|
||||
}
|
||||
|
||||
@GetMapping("/products/{id}")
|
||||
public ApiResponse<Map<String, Object>> productDetail(@PathVariable Long id) {
|
||||
Product product = productRepository.findById(id).orElseThrow();
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("product", product);
|
||||
data.put("images", productService.getImages(product));
|
||||
return ApiResponse.ok(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package com.toyshop.controller.admin;
|
||||
|
||||
import com.toyshop.dto.*;
|
||||
import com.toyshop.entity.*;
|
||||
import com.toyshop.repository.*;
|
||||
import com.toyshop.service.ProductService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public class AdminController {
|
||||
private final UserRepository userRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final ProductRepository productRepository;
|
||||
private final ProductImageRepository productImageRepository;
|
||||
private final OrderRepository orderRepository;
|
||||
private final CarouselRepository carouselRepository;
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final ProductService productService;
|
||||
|
||||
public AdminController(UserRepository userRepository, CategoryRepository categoryRepository,
|
||||
ProductRepository productRepository, ProductImageRepository productImageRepository,
|
||||
OrderRepository orderRepository, CarouselRepository carouselRepository,
|
||||
NoticeRepository noticeRepository, ProductService productService) {
|
||||
this.userRepository = userRepository;
|
||||
this.categoryRepository = categoryRepository;
|
||||
this.productRepository = productRepository;
|
||||
this.productImageRepository = productImageRepository;
|
||||
this.orderRepository = orderRepository;
|
||||
this.carouselRepository = carouselRepository;
|
||||
this.noticeRepository = noticeRepository;
|
||||
this.productService = productService;
|
||||
}
|
||||
|
||||
@GetMapping("/users")
|
||||
public ApiResponse<List<User>> users() {
|
||||
return ApiResponse.ok(userRepository.findAll());
|
||||
}
|
||||
|
||||
@PutMapping("/users/{id}")
|
||||
public ApiResponse<User> updateUserStatus(@PathVariable Long id, @Valid @RequestBody UserStatusRequest request) {
|
||||
User user = userRepository.findById(id).orElseThrow();
|
||||
user.setEnabled(request.getEnabled());
|
||||
return ApiResponse.ok(userRepository.save(user));
|
||||
}
|
||||
|
||||
@GetMapping("/categories")
|
||||
public ApiResponse<List<Category>> categories() {
|
||||
return ApiResponse.ok(categoryRepository.findAll());
|
||||
}
|
||||
|
||||
@PostMapping("/categories")
|
||||
public ApiResponse<Category> createCategory(@Valid @RequestBody CategoryRequest request) {
|
||||
if (categoryRepository.existsByName(request.getName())) {
|
||||
return ApiResponse.fail("分类已存在");
|
||||
}
|
||||
Category category = new Category();
|
||||
category.setName(request.getName());
|
||||
category.setDescription(request.getDescription());
|
||||
return ApiResponse.ok(categoryRepository.save(category));
|
||||
}
|
||||
|
||||
@PutMapping("/categories/{id}")
|
||||
public ApiResponse<Category> updateCategory(@PathVariable Long id, @Valid @RequestBody CategoryRequest request) {
|
||||
Category category = categoryRepository.findById(id).orElseThrow();
|
||||
category.setName(request.getName());
|
||||
category.setDescription(request.getDescription());
|
||||
return ApiResponse.ok(categoryRepository.save(category));
|
||||
}
|
||||
|
||||
@DeleteMapping("/categories/{id}")
|
||||
public ApiResponse<?> deleteCategory(@PathVariable Long id) {
|
||||
categoryRepository.deleteById(id);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
@GetMapping("/products")
|
||||
public ApiResponse<List<Product>> products() {
|
||||
return ApiResponse.ok(productRepository.findAll());
|
||||
}
|
||||
|
||||
@PostMapping("/products")
|
||||
public ApiResponse<Product> createProduct(@Valid @RequestBody ProductRequest request) {
|
||||
Product product = new Product();
|
||||
product.setName(request.getName());
|
||||
product.setDescription(request.getDescription());
|
||||
product.setPrice(request.getPrice());
|
||||
product.setStock(request.getStock());
|
||||
product.setAgeRange(request.getAgeRange());
|
||||
product.setSafetyInfo(request.getSafetyInfo());
|
||||
product.setOnSale(request.isOnSale());
|
||||
if (request.getCategoryId() != null) {
|
||||
product.setCategory(productService.getCategory(request.getCategoryId()));
|
||||
}
|
||||
return ApiResponse.ok(productRepository.save(product));
|
||||
}
|
||||
|
||||
@PutMapping("/products/{id}")
|
||||
public ApiResponse<Product> updateProduct(@PathVariable Long id, @Valid @RequestBody ProductRequest request) {
|
||||
Product product = productRepository.findById(id).orElseThrow();
|
||||
product.setName(request.getName());
|
||||
product.setDescription(request.getDescription());
|
||||
if (request.getPrice() != null) {
|
||||
product.setPrice(request.getPrice());
|
||||
}
|
||||
if (request.getStock() != null) {
|
||||
product.setStock(request.getStock());
|
||||
}
|
||||
product.setAgeRange(request.getAgeRange());
|
||||
product.setSafetyInfo(request.getSafetyInfo());
|
||||
product.setOnSale(request.isOnSale());
|
||||
if (request.getCategoryId() != null) {
|
||||
product.setCategory(productService.getCategory(request.getCategoryId()));
|
||||
}
|
||||
return ApiResponse.ok(productRepository.save(product));
|
||||
}
|
||||
|
||||
@DeleteMapping("/products/{id}")
|
||||
public ApiResponse<?> deleteProduct(@PathVariable Long id) {
|
||||
productRepository.deleteById(id);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
@GetMapping("/products/{id}/images")
|
||||
public ApiResponse<List<ProductImage>> productImages(@PathVariable Long id) {
|
||||
Product product = productRepository.findById(id).orElseThrow();
|
||||
return ApiResponse.ok(productImageRepository.findByProduct(product));
|
||||
}
|
||||
|
||||
@PostMapping("/products/{id}/images")
|
||||
public ApiResponse<ProductImage> addProductImage(@PathVariable Long id, @RequestBody ProductImage body) {
|
||||
Product product = productRepository.findById(id).orElseThrow();
|
||||
ProductImage image = new ProductImage();
|
||||
image.setProduct(product);
|
||||
image.setUrl(body.getUrl());
|
||||
image.setSortOrder(body.getSortOrder() == null ? 0 : body.getSortOrder());
|
||||
return ApiResponse.ok(productImageRepository.save(image));
|
||||
}
|
||||
|
||||
@DeleteMapping("/product-images/{imageId}")
|
||||
public ApiResponse<?> deleteProductImage(@PathVariable Long imageId) {
|
||||
productImageRepository.deleteById(imageId);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
@GetMapping("/orders")
|
||||
public ApiResponse<List<Order>> orders() {
|
||||
return ApiResponse.ok(orderRepository.findAll());
|
||||
}
|
||||
|
||||
@PutMapping("/orders/status")
|
||||
public ApiResponse<Order> updateOrderStatus(@Valid @RequestBody AdminOrderUpdateRequest request) {
|
||||
Order order = orderRepository.findById(request.getOrderId()).orElseThrow();
|
||||
order.setStatus(OrderStatus.valueOf(request.getStatus()));
|
||||
order.setLogisticsNo(request.getLogisticsNo());
|
||||
return ApiResponse.ok(orderRepository.save(order));
|
||||
}
|
||||
|
||||
@GetMapping("/carousels")
|
||||
public ApiResponse<List<Carousel>> carousels() {
|
||||
return ApiResponse.ok(carouselRepository.findAllByOrderBySortOrderAsc());
|
||||
}
|
||||
|
||||
@PostMapping("/carousels")
|
||||
public ApiResponse<Carousel> createCarousel(@Valid @RequestBody CarouselRequest request) {
|
||||
Carousel carousel = new Carousel();
|
||||
carousel.setImageUrl(request.getImageUrl());
|
||||
carousel.setLinkUrl(request.getLinkUrl());
|
||||
carousel.setSortOrder(request.getSortOrder());
|
||||
return ApiResponse.ok(carouselRepository.save(carousel));
|
||||
}
|
||||
|
||||
@PutMapping("/carousels/{id}")
|
||||
public ApiResponse<Carousel> updateCarousel(@PathVariable Long id, @Valid @RequestBody CarouselRequest request) {
|
||||
Carousel carousel = carouselRepository.findById(id).orElseThrow();
|
||||
carousel.setImageUrl(request.getImageUrl());
|
||||
carousel.setLinkUrl(request.getLinkUrl());
|
||||
carousel.setSortOrder(request.getSortOrder());
|
||||
return ApiResponse.ok(carouselRepository.save(carousel));
|
||||
}
|
||||
|
||||
@DeleteMapping("/carousels/{id}")
|
||||
public ApiResponse<?> deleteCarousel(@PathVariable Long id) {
|
||||
carouselRepository.deleteById(id);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
@GetMapping("/notices")
|
||||
public ApiResponse<List<Notice>> notices() {
|
||||
return ApiResponse.ok(noticeRepository.findAll());
|
||||
}
|
||||
|
||||
@PostMapping("/notices")
|
||||
public ApiResponse<Notice> createNotice(@Valid @RequestBody NoticeRequest request) {
|
||||
Notice notice = new Notice();
|
||||
notice.setTitle(request.getTitle());
|
||||
notice.setContent(request.getContent());
|
||||
return ApiResponse.ok(noticeRepository.save(notice));
|
||||
}
|
||||
|
||||
@PutMapping("/notices/{id}")
|
||||
public ApiResponse<Notice> updateNotice(@PathVariable Long id, @Valid @RequestBody NoticeRequest request) {
|
||||
Notice notice = noticeRepository.findById(id).orElseThrow();
|
||||
notice.setTitle(request.getTitle());
|
||||
notice.setContent(request.getContent());
|
||||
return ApiResponse.ok(noticeRepository.save(notice));
|
||||
}
|
||||
|
||||
@DeleteMapping("/notices/{id}")
|
||||
public ApiResponse<?> deleteNotice(@PathVariable Long id) {
|
||||
noticeRepository.deleteById(id);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.toyshop.controller.user;
|
||||
|
||||
import com.toyshop.dto.*;
|
||||
import com.toyshop.entity.*;
|
||||
import com.toyshop.repository.*;
|
||||
import com.toyshop.service.*;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/user")
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
private final UserRepository userRepository;
|
||||
private final AddressRepository addressRepository;
|
||||
private final CartService cartService;
|
||||
private final OrderService orderService;
|
||||
private final OrderRepository orderRepository;
|
||||
private final OrderItemRepository orderItemRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public UserController(UserService userService, UserRepository userRepository, AddressRepository addressRepository,
|
||||
CartService cartService, OrderService orderService, OrderRepository orderRepository,
|
||||
OrderItemRepository orderItemRepository, PasswordEncoder passwordEncoder) {
|
||||
this.userService = userService;
|
||||
this.userRepository = userRepository;
|
||||
this.addressRepository = addressRepository;
|
||||
this.cartService = cartService;
|
||||
this.orderService = orderService;
|
||||
this.orderRepository = orderRepository;
|
||||
this.orderItemRepository = orderItemRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@GetMapping("/profile")
|
||||
public ApiResponse<User> profile() {
|
||||
User user = userService.getCurrentUser();
|
||||
user.setPassword("***");
|
||||
return ApiResponse.ok(user);
|
||||
}
|
||||
|
||||
@PutMapping("/profile")
|
||||
public ApiResponse<User> updateProfile(@RequestBody User body) {
|
||||
User user = userService.getCurrentUser();
|
||||
user.setPhone(body.getPhone());
|
||||
user.setEmail(body.getEmail());
|
||||
user.setAvatar(body.getAvatar());
|
||||
userRepository.save(user);
|
||||
user.setPassword("***");
|
||||
return ApiResponse.ok(user);
|
||||
}
|
||||
|
||||
@PutMapping("/password")
|
||||
public ApiResponse<?> changePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
|
||||
User user = userService.getCurrentUser();
|
||||
if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
|
||||
return ApiResponse.fail("原密码错误");
|
||||
}
|
||||
user.setPassword(passwordEncoder.encode(newPassword));
|
||||
userRepository.save(user);
|
||||
return ApiResponse.ok("修改成功", null);
|
||||
}
|
||||
|
||||
@GetMapping("/addresses")
|
||||
public ApiResponse<List<Address>> addresses() {
|
||||
User user = userService.getCurrentUser();
|
||||
return ApiResponse.ok(addressRepository.findByUser(user));
|
||||
}
|
||||
|
||||
@PostMapping("/addresses")
|
||||
public ApiResponse<Address> addAddress(@Valid @RequestBody AddressRequest request) {
|
||||
User user = userService.getCurrentUser();
|
||||
Address address = new Address();
|
||||
address.setUser(user);
|
||||
address.setReceiverName(request.getReceiverName());
|
||||
address.setReceiverPhone(request.getReceiverPhone());
|
||||
address.setDetail(request.getDetail());
|
||||
address.setDefault(request.isDefault());
|
||||
return ApiResponse.ok(addressRepository.save(address));
|
||||
}
|
||||
|
||||
@PutMapping("/addresses/{id}")
|
||||
public ApiResponse<Address> updateAddress(@PathVariable Long id, @Valid @RequestBody AddressRequest request) {
|
||||
User user = userService.getCurrentUser();
|
||||
Address address = addressRepository.findById(id).orElseThrow();
|
||||
if (!address.getUser().getId().equals(user.getId())) {
|
||||
return ApiResponse.fail("无权限");
|
||||
}
|
||||
address.setReceiverName(request.getReceiverName());
|
||||
address.setReceiverPhone(request.getReceiverPhone());
|
||||
address.setDetail(request.getDetail());
|
||||
address.setDefault(request.isDefault());
|
||||
return ApiResponse.ok(addressRepository.save(address));
|
||||
}
|
||||
|
||||
@DeleteMapping("/addresses/{id}")
|
||||
public ApiResponse<?> deleteAddress(@PathVariable Long id) {
|
||||
User user = userService.getCurrentUser();
|
||||
Address address = addressRepository.findById(id).orElseThrow();
|
||||
if (!address.getUser().getId().equals(user.getId())) {
|
||||
return ApiResponse.fail("无权限");
|
||||
}
|
||||
addressRepository.delete(address);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
@GetMapping("/cart")
|
||||
public ApiResponse<List<CartItem>> cartList() {
|
||||
User user = userService.getCurrentUser();
|
||||
return ApiResponse.ok(cartService.list(user));
|
||||
}
|
||||
|
||||
@PostMapping("/cart")
|
||||
public ApiResponse<?> addToCart(@Valid @RequestBody CartItemRequest request) {
|
||||
User user = userService.getCurrentUser();
|
||||
cartService.add(user, request.getProductId(), request.getQuantity());
|
||||
return ApiResponse.ok("加入成功", null);
|
||||
}
|
||||
|
||||
@PutMapping("/cart/{itemId}")
|
||||
public ApiResponse<?> updateCart(@PathVariable Long itemId, @RequestBody CartItemRequest request) {
|
||||
User user = userService.getCurrentUser();
|
||||
cartService.update(user, itemId, request.getQuantity());
|
||||
return ApiResponse.ok("更新成功", null);
|
||||
}
|
||||
|
||||
@DeleteMapping("/cart/{itemId}")
|
||||
public ApiResponse<?> deleteCart(@PathVariable Long itemId) {
|
||||
User user = userService.getCurrentUser();
|
||||
cartService.remove(user, itemId);
|
||||
return ApiResponse.ok("删除成功", null);
|
||||
}
|
||||
|
||||
@PostMapping("/orders")
|
||||
public ApiResponse<Order> createOrder(@Valid @RequestBody OrderCreateRequest request) {
|
||||
User user = userService.getCurrentUser();
|
||||
return ApiResponse.ok(orderService.createOrder(user, request.getAddressId()));
|
||||
}
|
||||
|
||||
@GetMapping("/orders")
|
||||
public ApiResponse<List<Order>> listOrders() {
|
||||
User user = userService.getCurrentUser();
|
||||
return ApiResponse.ok(orderService.listOrders(user));
|
||||
}
|
||||
|
||||
@GetMapping("/orders/{id}")
|
||||
public ApiResponse<Map<String, Object>> orderDetail(@PathVariable Long id) {
|
||||
User user = userService.getCurrentUser();
|
||||
Order order = orderRepository.findById(id).orElseThrow();
|
||||
if (!order.getUser().getId().equals(user.getId())) {
|
||||
return ApiResponse.fail("无权限");
|
||||
}
|
||||
List<OrderItem> items = orderItemRepository.findByOrder(order);
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("order", order);
|
||||
data.put("items", items);
|
||||
return ApiResponse.ok(data);
|
||||
}
|
||||
|
||||
@PostMapping("/orders/{id}/pay")
|
||||
public ApiResponse<?> pay(@PathVariable Long id) {
|
||||
User user = userService.getCurrentUser();
|
||||
Order order = orderRepository.findById(id).orElseThrow();
|
||||
if (!order.getUser().getId().equals(user.getId())) {
|
||||
return ApiResponse.fail("无权限");
|
||||
}
|
||||
order.setStatus(OrderStatus.PENDING_SHIPMENT);
|
||||
orderRepository.save(order);
|
||||
return ApiResponse.ok("支付成功", null);
|
||||
}
|
||||
}
|
||||
22
backend/src/main/java/com/toyshop/dto/AddressRequest.java
Normal file
22
backend/src/main/java/com/toyshop/dto/AddressRequest.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class AddressRequest {
|
||||
@NotBlank
|
||||
private String receiverName;
|
||||
@NotBlank
|
||||
private String receiverPhone;
|
||||
@NotBlank
|
||||
private String detail;
|
||||
private boolean isDefault;
|
||||
|
||||
public String getReceiverName() { return receiverName; }
|
||||
public void setReceiverName(String receiverName) { this.receiverName = receiverName; }
|
||||
public String getReceiverPhone() { return receiverPhone; }
|
||||
public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; }
|
||||
public String getDetail() { return detail; }
|
||||
public void setDetail(String detail) { this.detail = detail; }
|
||||
public boolean isDefault() { return isDefault; }
|
||||
public void setDefault(boolean aDefault) { isDefault = aDefault; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class AdminOrderUpdateRequest {
|
||||
@NotNull
|
||||
private Long orderId;
|
||||
@NotBlank
|
||||
private String status;
|
||||
private String logisticsNo;
|
||||
|
||||
public Long getOrderId() { return orderId; }
|
||||
public void setOrderId(Long orderId) { this.orderId = orderId; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getLogisticsNo() { return logisticsNo; }
|
||||
public void setLogisticsNo(String logisticsNo) { this.logisticsNo = logisticsNo; }
|
||||
}
|
||||
34
backend/src/main/java/com/toyshop/dto/ApiResponse.java
Normal file
34
backend/src/main/java/com/toyshop/dto/ApiResponse.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
public class ApiResponse<T> {
|
||||
private boolean success;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public ApiResponse() {}
|
||||
|
||||
public ApiResponse(boolean success, String message, T data) {
|
||||
this.success = success;
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> ok(T data) {
|
||||
return new ApiResponse<>(true, "ok", data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> ok(String message, T data) {
|
||||
return new ApiResponse<>(true, message, data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(String message) {
|
||||
return new ApiResponse<>(false, message, null);
|
||||
}
|
||||
|
||||
public boolean isSuccess() { return success; }
|
||||
public void setSuccess(boolean success) { this.success = success; }
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
public T getData() { return data; }
|
||||
public void setData(T data) { this.data = data; }
|
||||
}
|
||||
15
backend/src/main/java/com/toyshop/dto/AuthRequest.java
Normal file
15
backend/src/main/java/com/toyshop/dto/AuthRequest.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class AuthRequest {
|
||||
@NotBlank
|
||||
private String username;
|
||||
@NotBlank
|
||||
private String password;
|
||||
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
public String getPassword() { return password; }
|
||||
public void setPassword(String password) { this.password = password; }
|
||||
}
|
||||
22
backend/src/main/java/com/toyshop/dto/AuthResponse.java
Normal file
22
backend/src/main/java/com/toyshop/dto/AuthResponse.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
public class AuthResponse {
|
||||
private String token;
|
||||
private String role;
|
||||
private String username;
|
||||
|
||||
public AuthResponse() {}
|
||||
|
||||
public AuthResponse(String token, String role, String username) {
|
||||
this.token = token;
|
||||
this.role = role;
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getToken() { return token; }
|
||||
public void setToken(String token) { this.token = token; }
|
||||
public String getRole() { return role; }
|
||||
public void setRole(String role) { this.role = role; }
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
}
|
||||
17
backend/src/main/java/com/toyshop/dto/CarouselRequest.java
Normal file
17
backend/src/main/java/com/toyshop/dto/CarouselRequest.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class CarouselRequest {
|
||||
@NotBlank
|
||||
private String imageUrl;
|
||||
private String linkUrl;
|
||||
private Integer sortOrder = 0;
|
||||
|
||||
public String getImageUrl() { return imageUrl; }
|
||||
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
|
||||
public String getLinkUrl() { return linkUrl; }
|
||||
public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; }
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
|
||||
}
|
||||
15
backend/src/main/java/com/toyshop/dto/CartItemRequest.java
Normal file
15
backend/src/main/java/com/toyshop/dto/CartItemRequest.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class CartItemRequest {
|
||||
@NotNull
|
||||
private Long productId;
|
||||
@NotNull
|
||||
private Integer quantity;
|
||||
|
||||
public Long getProductId() { return productId; }
|
||||
public void setProductId(Long productId) { this.productId = productId; }
|
||||
public Integer getQuantity() { return quantity; }
|
||||
public void setQuantity(Integer quantity) { this.quantity = quantity; }
|
||||
}
|
||||
14
backend/src/main/java/com/toyshop/dto/CategoryRequest.java
Normal file
14
backend/src/main/java/com/toyshop/dto/CategoryRequest.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class CategoryRequest {
|
||||
@NotBlank
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
}
|
||||
15
backend/src/main/java/com/toyshop/dto/NoticeRequest.java
Normal file
15
backend/src/main/java/com/toyshop/dto/NoticeRequest.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class NoticeRequest {
|
||||
@NotBlank
|
||||
private String title;
|
||||
@NotBlank
|
||||
private String content;
|
||||
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
public String getContent() { return content; }
|
||||
public void setContent(String content) { this.content = content; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class OrderCreateRequest {
|
||||
@NotNull
|
||||
private Long addressId;
|
||||
|
||||
public Long getAddressId() { return addressId; }
|
||||
public void setAddressId(Long addressId) { this.addressId = addressId; }
|
||||
}
|
||||
33
backend/src/main/java/com/toyshop/dto/ProductRequest.java
Normal file
33
backend/src/main/java/com/toyshop/dto/ProductRequest.java
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class ProductRequest {
|
||||
@NotBlank
|
||||
private String name;
|
||||
private Long categoryId;
|
||||
private String description;
|
||||
private BigDecimal price;
|
||||
private Integer stock;
|
||||
private String ageRange;
|
||||
private String safetyInfo;
|
||||
private boolean onSale = true;
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public Long getCategoryId() { return categoryId; }
|
||||
public void setCategoryId(Long categoryId) { this.categoryId = categoryId; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
public BigDecimal getPrice() { return price; }
|
||||
public void setPrice(BigDecimal price) { this.price = price; }
|
||||
public Integer getStock() { return stock; }
|
||||
public void setStock(Integer stock) { this.stock = stock; }
|
||||
public String getAgeRange() { return ageRange; }
|
||||
public void setAgeRange(String ageRange) { this.ageRange = ageRange; }
|
||||
public String getSafetyInfo() { return safetyInfo; }
|
||||
public void setSafetyInfo(String safetyInfo) { this.safetyInfo = safetyInfo; }
|
||||
public boolean isOnSale() { return onSale; }
|
||||
public void setOnSale(boolean onSale) { this.onSale = onSale; }
|
||||
}
|
||||
21
backend/src/main/java/com/toyshop/dto/RegisterRequest.java
Normal file
21
backend/src/main/java/com/toyshop/dto/RegisterRequest.java
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class RegisterRequest {
|
||||
@NotBlank
|
||||
private String username;
|
||||
@NotBlank
|
||||
private String password;
|
||||
private String phone;
|
||||
private String email;
|
||||
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
public String getPassword() { return password; }
|
||||
public void setPassword(String password) { this.password = password; }
|
||||
public String getPhone() { return phone; }
|
||||
public void setPhone(String phone) { this.phone = phone; }
|
||||
public String getEmail() { return email; }
|
||||
public void setEmail(String email) { this.email = email; }
|
||||
}
|
||||
11
backend/src/main/java/com/toyshop/dto/UserStatusRequest.java
Normal file
11
backend/src/main/java/com/toyshop/dto/UserStatusRequest.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.toyshop.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class UserStatusRequest {
|
||||
@NotNull
|
||||
private Boolean enabled;
|
||||
|
||||
public Boolean getEnabled() { return enabled; }
|
||||
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
|
||||
}
|
||||
50
backend/src/main/java/com/toyshop/entity/Address.java
Normal file
50
backend/src/main/java/com/toyshop/entity/Address.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "addresses")
|
||||
public class Address {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@Column(nullable = false, length = 50)
|
||||
private String receiverName;
|
||||
|
||||
@Column(nullable = false, length = 20)
|
||||
private String receiverPhone;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String detail;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean isDefault = false;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public User getUser() { return user; }
|
||||
public void setUser(User user) { this.user = user; }
|
||||
public String getReceiverName() { return receiverName; }
|
||||
public void setReceiverName(String receiverName) { this.receiverName = receiverName; }
|
||||
public String getReceiverPhone() { return receiverPhone; }
|
||||
public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; }
|
||||
public String getDetail() { return detail; }
|
||||
public void setDetail(String detail) { this.detail = detail; }
|
||||
public boolean isDefault() { return isDefault; }
|
||||
public void setDefault(boolean aDefault) { isDefault = aDefault; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
}
|
||||
29
backend/src/main/java/com/toyshop/entity/Carousel.java
Normal file
29
backend/src/main/java/com/toyshop/entity/Carousel.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "carousels")
|
||||
public class Carousel {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String imageUrl;
|
||||
|
||||
@Column(length = 255)
|
||||
private String linkUrl;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer sortOrder = 0;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getImageUrl() { return imageUrl; }
|
||||
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
|
||||
public String getLinkUrl() { return linkUrl; }
|
||||
public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; }
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
|
||||
}
|
||||
31
backend/src/main/java/com/toyshop/entity/CartItem.java
Normal file
31
backend/src/main/java/com/toyshop/entity/CartItem.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "cart_items")
|
||||
public class CartItem {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "product_id", nullable = false)
|
||||
private Product product;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer quantity = 1;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public User getUser() { return user; }
|
||||
public void setUser(User user) { this.user = user; }
|
||||
public Product getProduct() { return product; }
|
||||
public void setProduct(Product product) { this.product = product; }
|
||||
public Integer getQuantity() { return quantity; }
|
||||
public void setQuantity(Integer quantity) { this.quantity = quantity; }
|
||||
}
|
||||
24
backend/src/main/java/com/toyshop/entity/Category.java
Normal file
24
backend/src/main/java/com/toyshop/entity/Category.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "categories")
|
||||
public class Category {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
|
||||
@Column(length = 255)
|
||||
private String description;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
}
|
||||
34
backend/src/main/java/com/toyshop/entity/Notice.java
Normal file
34
backend/src/main/java/com/toyshop/entity/Notice.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "notices")
|
||||
public class Notice {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
|
||||
@Column(columnDefinition = "text")
|
||||
private String content;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
public String getContent() { return content; }
|
||||
public void setContent(String content) { this.content = content; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
}
|
||||
78
backend/src/main/java/com/toyshop/entity/Order.java
Normal file
78
backend/src/main/java/com/toyshop/entity/Order.java
Normal file
@@ -0,0 +1,78 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "orders")
|
||||
public class Order {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String orderNo;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private User user;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 30)
|
||||
private OrderStatus status = OrderStatus.PENDING_PAYMENT;
|
||||
|
||||
@Column(nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal totalAmount;
|
||||
|
||||
@Column(nullable = false, length = 50)
|
||||
private String receiverName;
|
||||
|
||||
@Column(nullable = false, length = 20)
|
||||
private String receiverPhone;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String receiverAddress;
|
||||
|
||||
@Column(length = 50)
|
||||
private String logisticsNo;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getOrderNo() { return orderNo; }
|
||||
public void setOrderNo(String orderNo) { this.orderNo = orderNo; }
|
||||
public User getUser() { return user; }
|
||||
public void setUser(User user) { this.user = user; }
|
||||
public OrderStatus getStatus() { return status; }
|
||||
public void setStatus(OrderStatus status) { this.status = status; }
|
||||
public BigDecimal getTotalAmount() { return totalAmount; }
|
||||
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
|
||||
public String getReceiverName() { return receiverName; }
|
||||
public void setReceiverName(String receiverName) { this.receiverName = receiverName; }
|
||||
public String getReceiverPhone() { return receiverPhone; }
|
||||
public void setReceiverPhone(String receiverPhone) { this.receiverPhone = receiverPhone; }
|
||||
public String getReceiverAddress() { return receiverAddress; }
|
||||
public void setReceiverAddress(String receiverAddress) { this.receiverAddress = receiverAddress; }
|
||||
public String getLogisticsNo() { return logisticsNo; }
|
||||
public void setLogisticsNo(String logisticsNo) { this.logisticsNo = logisticsNo; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
}
|
||||
37
backend/src/main/java/com/toyshop/entity/OrderItem.java
Normal file
37
backend/src/main/java/com/toyshop/entity/OrderItem.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
@Table(name = "order_items")
|
||||
public class OrderItem {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "order_id", nullable = false)
|
||||
private Order order;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "product_id", nullable = false)
|
||||
private Product product;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer quantity;
|
||||
|
||||
@Column(nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal price;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public Order getOrder() { return order; }
|
||||
public void setOrder(Order order) { this.order = order; }
|
||||
public Product getProduct() { return product; }
|
||||
public void setProduct(Product product) { this.product = product; }
|
||||
public Integer getQuantity() { return quantity; }
|
||||
public void setQuantity(Integer quantity) { this.quantity = quantity; }
|
||||
public BigDecimal getPrice() { return price; }
|
||||
public void setPrice(BigDecimal price) { this.price = price; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
public enum OrderStatus {
|
||||
PENDING_PAYMENT,
|
||||
PENDING_SHIPMENT,
|
||||
SHIPPED,
|
||||
COMPLETED
|
||||
}
|
||||
82
backend/src/main/java/com/toyshop/entity/Product.java
Normal file
82
backend/src/main/java/com/toyshop/entity/Product.java
Normal file
@@ -0,0 +1,82 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "products")
|
||||
public class Product {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "category_id")
|
||||
private Category category;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "text")
|
||||
private String description;
|
||||
|
||||
@Column(nullable = false, precision = 10, scale = 2)
|
||||
private BigDecimal price;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer stock = 0;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer sales = 0;
|
||||
|
||||
@Column(length = 50)
|
||||
private String ageRange;
|
||||
|
||||
@Column(length = 255)
|
||||
private String safetyInfo;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean onSale = true;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public Category getCategory() { return category; }
|
||||
public void setCategory(Category category) { this.category = category; }
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
public BigDecimal getPrice() { return price; }
|
||||
public void setPrice(BigDecimal price) { this.price = price; }
|
||||
public Integer getStock() { return stock; }
|
||||
public void setStock(Integer stock) { this.stock = stock; }
|
||||
public Integer getSales() { return sales; }
|
||||
public void setSales(Integer sales) { this.sales = sales; }
|
||||
public String getAgeRange() { return ageRange; }
|
||||
public void setAgeRange(String ageRange) { this.ageRange = ageRange; }
|
||||
public String getSafetyInfo() { return safetyInfo; }
|
||||
public void setSafetyInfo(String safetyInfo) { this.safetyInfo = safetyInfo; }
|
||||
public boolean isOnSale() { return onSale; }
|
||||
public void setOnSale(boolean onSale) { this.onSale = onSale; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
}
|
||||
30
backend/src/main/java/com/toyshop/entity/ProductImage.java
Normal file
30
backend/src/main/java/com/toyshop/entity/ProductImage.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "product_images")
|
||||
public class ProductImage {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "product_id", nullable = false)
|
||||
private Product product;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String url;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Integer sortOrder = 0;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public Product getProduct() { return product; }
|
||||
public void setProduct(Product product) { this.product = product; }
|
||||
public String getUrl() { return url; }
|
||||
public void setUrl(String url) { this.url = url; }
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
|
||||
}
|
||||
71
backend/src/main/java/com/toyshop/entity/User.java
Normal file
71
backend/src/main/java/com/toyshop/entity/User.java
Normal file
@@ -0,0 +1,71 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String username;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
|
||||
@Column(length = 20)
|
||||
private String phone;
|
||||
|
||||
@Column(length = 100)
|
||||
private String email;
|
||||
|
||||
@Column(length = 255)
|
||||
private String avatar;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private UserRole role = UserRole.USER;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean enabled = true;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
createdAt = now;
|
||||
updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
public String getPassword() { return password; }
|
||||
public void setPassword(String password) { this.password = password; }
|
||||
public String getPhone() { return phone; }
|
||||
public void setPhone(String phone) { this.phone = phone; }
|
||||
public String getEmail() { return email; }
|
||||
public void setEmail(String email) { this.email = email; }
|
||||
public String getAvatar() { return avatar; }
|
||||
public void setAvatar(String avatar) { this.avatar = avatar; }
|
||||
public UserRole getRole() { return role; }
|
||||
public void setRole(UserRole role) { this.role = role; }
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
}
|
||||
6
backend/src/main/java/com/toyshop/entity/UserRole.java
Normal file
6
backend/src/main/java/com/toyshop/entity/UserRole.java
Normal file
@@ -0,0 +1,6 @@
|
||||
package com.toyshop.entity;
|
||||
|
||||
public enum UserRole {
|
||||
USER,
|
||||
ADMIN
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.Address;
|
||||
import com.toyshop.entity.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface AddressRepository extends JpaRepository<Address, Long> {
|
||||
List<Address> findByUser(User user);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.Carousel;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface CarouselRepository extends JpaRepository<Carousel, Long> {
|
||||
List<Carousel> findAllByOrderBySortOrderAsc();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.CartItem;
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.entity.Product;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
|
||||
List<CartItem> findByUser(User user);
|
||||
Optional<CartItem> findByUserAndProduct(User user, Product product);
|
||||
void deleteByUser(User user);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.Category;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface CategoryRepository extends JpaRepository<Category, Long> {
|
||||
boolean existsByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.Notice;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface NoticeRepository extends JpaRepository<Notice, Long> {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.OrderItem;
|
||||
import com.toyshop.entity.Order;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface OrderItemRepository extends JpaRepository<OrderItem, Long> {
|
||||
List<OrderItem> findByOrder(Order order);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.Order;
|
||||
import com.toyshop.entity.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface OrderRepository extends JpaRepository<Order, Long> {
|
||||
List<Order> findByUserOrderByCreatedAtDesc(User user);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.ProductImage;
|
||||
import com.toyshop.entity.Product;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface ProductImageRepository extends JpaRepository<ProductImage, Long> {
|
||||
List<ProductImage> findByProduct(Product product);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.Product;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
|
||||
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.toyshop.repository;
|
||||
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.entity.UserRole;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
Optional<User> findByUsername(String username);
|
||||
long countByRole(UserRole role);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.toyshop.security;
|
||||
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.repository.UserRepository;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class CustomUserDetailsService implements UserDetailsService {
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public CustomUserDetailsService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
return org.springframework.security.core.userdetails.User
|
||||
.withUsername(user.getUsername())
|
||||
.password(user.getPassword())
|
||||
.roles(user.getRole().name())
|
||||
.disabled(!user.isEnabled())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.toyshop.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider, UserDetailsService userDetailsService) {
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
this.userDetailsService = userDetailsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
|
||||
String token = header.substring(7);
|
||||
try {
|
||||
Claims claims = jwtTokenProvider.parseClaims(token);
|
||||
String username = claims.getSubject();
|
||||
var userDetails = userDetailsService.loadUserByUsername(username);
|
||||
var auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.toyshop.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Key;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
private final Key key;
|
||||
private final long expireSeconds;
|
||||
|
||||
public JwtTokenProvider(@Value("${app.jwt.secret}") String secret,
|
||||
@Value("${app.jwt.expire-hours}") long expireHours) {
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||
this.expireSeconds = expireHours * 3600L;
|
||||
}
|
||||
|
||||
public String generateToken(String username, String role) {
|
||||
Instant now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.setSubject(username)
|
||||
.claim("role", role)
|
||||
.setIssuedAt(Date.from(now))
|
||||
.setExpiration(Date.from(now.plusSeconds(expireSeconds)))
|
||||
.signWith(key, SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parseClaims(String token) {
|
||||
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
|
||||
}
|
||||
}
|
||||
51
backend/src/main/java/com/toyshop/service/AuthService.java
Normal file
51
backend/src/main/java/com/toyshop/service/AuthService.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.toyshop.service;
|
||||
|
||||
import com.toyshop.dto.AuthRequest;
|
||||
import com.toyshop.dto.RegisterRequest;
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.entity.UserRole;
|
||||
import com.toyshop.repository.UserRepository;
|
||||
import com.toyshop.security.JwtTokenProvider;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
public AuthService(UserRepository userRepository, PasswordEncoder passwordEncoder,
|
||||
AuthenticationManager authenticationManager, JwtTokenProvider jwtTokenProvider) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.authenticationManager = authenticationManager;
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
}
|
||||
|
||||
public String register(RegisterRequest request) {
|
||||
if (userRepository.findByUsername(request.getUsername()).isPresent()) {
|
||||
throw new IllegalArgumentException("用户名已存在");
|
||||
}
|
||||
User user = new User();
|
||||
user.setUsername(request.getUsername());
|
||||
user.setPassword(passwordEncoder.encode(request.getPassword()));
|
||||
user.setPhone(request.getPhone());
|
||||
user.setEmail(request.getEmail());
|
||||
user.setRole(UserRole.USER);
|
||||
userRepository.save(user);
|
||||
return jwtTokenProvider.generateToken(user.getUsername(), user.getRole().name());
|
||||
}
|
||||
|
||||
public String login(AuthRequest request) {
|
||||
Authentication authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
|
||||
var userDetails = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
|
||||
var user = userRepository.findByUsername(userDetails.getUsername()).orElseThrow();
|
||||
return jwtTokenProvider.generateToken(user.getUsername(), user.getRole().name());
|
||||
}
|
||||
}
|
||||
53
backend/src/main/java/com/toyshop/service/CartService.java
Normal file
53
backend/src/main/java/com/toyshop/service/CartService.java
Normal file
@@ -0,0 +1,53 @@
|
||||
package com.toyshop.service;
|
||||
|
||||
import com.toyshop.entity.*;
|
||||
import com.toyshop.repository.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class CartService {
|
||||
private final CartItemRepository cartItemRepository;
|
||||
private final ProductRepository productRepository;
|
||||
|
||||
public CartService(CartItemRepository cartItemRepository, ProductRepository productRepository) {
|
||||
this.cartItemRepository = cartItemRepository;
|
||||
this.productRepository = productRepository;
|
||||
}
|
||||
|
||||
public List<CartItem> list(User user) {
|
||||
return cartItemRepository.findByUser(user);
|
||||
}
|
||||
|
||||
public void add(User user, Long productId, Integer quantity) {
|
||||
Product product = productRepository.findById(productId).orElseThrow();
|
||||
CartItem item = cartItemRepository.findByUserAndProduct(user, product)
|
||||
.orElseGet(() -> {
|
||||
CartItem c = new CartItem();
|
||||
c.setUser(user);
|
||||
c.setProduct(product);
|
||||
c.setQuantity(0);
|
||||
return c;
|
||||
});
|
||||
item.setQuantity(item.getQuantity() + quantity);
|
||||
cartItemRepository.save(item);
|
||||
}
|
||||
|
||||
public void update(User user, Long itemId, Integer quantity) {
|
||||
CartItem item = cartItemRepository.findById(itemId).orElseThrow();
|
||||
if (!item.getUser().getId().equals(user.getId())) {
|
||||
throw new IllegalArgumentException("无权限");
|
||||
}
|
||||
item.setQuantity(quantity);
|
||||
cartItemRepository.save(item);
|
||||
}
|
||||
|
||||
public void remove(User user, Long itemId) {
|
||||
CartItem item = cartItemRepository.findById(itemId).orElseThrow();
|
||||
if (!item.getUser().getId().equals(user.getId())) {
|
||||
throw new IllegalArgumentException("无权限");
|
||||
}
|
||||
cartItemRepository.delete(item);
|
||||
}
|
||||
}
|
||||
65
backend/src/main/java/com/toyshop/service/OrderService.java
Normal file
65
backend/src/main/java/com/toyshop/service/OrderService.java
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.toyshop.service;
|
||||
|
||||
import com.toyshop.entity.*;
|
||||
import com.toyshop.repository.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class OrderService {
|
||||
private final OrderRepository orderRepository;
|
||||
private final OrderItemRepository orderItemRepository;
|
||||
private final CartItemRepository cartItemRepository;
|
||||
private final AddressRepository addressRepository;
|
||||
|
||||
public OrderService(OrderRepository orderRepository, OrderItemRepository orderItemRepository,
|
||||
CartItemRepository cartItemRepository, AddressRepository addressRepository) {
|
||||
this.orderRepository = orderRepository;
|
||||
this.orderItemRepository = orderItemRepository;
|
||||
this.cartItemRepository = cartItemRepository;
|
||||
this.addressRepository = addressRepository;
|
||||
}
|
||||
|
||||
public Order createOrder(User user, Long addressId) {
|
||||
Address address = addressRepository.findById(addressId).orElseThrow();
|
||||
if (!address.getUser().getId().equals(user.getId())) {
|
||||
throw new IllegalArgumentException("无权限");
|
||||
}
|
||||
List<CartItem> cartItems = cartItemRepository.findByUser(user);
|
||||
if (cartItems.isEmpty()) {
|
||||
throw new IllegalArgumentException("购物车为空");
|
||||
}
|
||||
BigDecimal total = BigDecimal.ZERO;
|
||||
for (CartItem item : cartItems) {
|
||||
BigDecimal line = item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
|
||||
total = total.add(line);
|
||||
}
|
||||
Order order = new Order();
|
||||
order.setOrderNo("T" + UUID.randomUUID().toString().replace("-", "").substring(0, 16));
|
||||
order.setUser(user);
|
||||
order.setTotalAmount(total);
|
||||
order.setReceiverName(address.getReceiverName());
|
||||
order.setReceiverPhone(address.getReceiverPhone());
|
||||
order.setReceiverAddress(address.getDetail());
|
||||
order.setStatus(OrderStatus.PENDING_PAYMENT);
|
||||
orderRepository.save(order);
|
||||
|
||||
for (CartItem item : cartItems) {
|
||||
OrderItem orderItem = new OrderItem();
|
||||
orderItem.setOrder(order);
|
||||
orderItem.setProduct(item.getProduct());
|
||||
orderItem.setQuantity(item.getQuantity());
|
||||
orderItem.setPrice(item.getProduct().getPrice());
|
||||
orderItemRepository.save(orderItem);
|
||||
}
|
||||
cartItemRepository.deleteByUser(user);
|
||||
return order;
|
||||
}
|
||||
|
||||
public List<Order> listOrders(User user) {
|
||||
return orderRepository.findByUserOrderByCreatedAtDesc(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.toyshop.service;
|
||||
|
||||
import com.toyshop.entity.*;
|
||||
import com.toyshop.repository.*;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class ProductService {
|
||||
private final ProductRepository productRepository;
|
||||
private final ProductImageRepository productImageRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
|
||||
public ProductService(ProductRepository productRepository, ProductImageRepository productImageRepository,
|
||||
CategoryRepository categoryRepository) {
|
||||
this.productRepository = productRepository;
|
||||
this.productImageRepository = productImageRepository;
|
||||
this.categoryRepository = categoryRepository;
|
||||
}
|
||||
|
||||
public List<Product> search(String keyword, Long categoryId, String sort) {
|
||||
Specification<Product> spec = (root, query, cb) -> {
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
if (keyword != null && !keyword.isBlank()) {
|
||||
predicates.add(cb.like(root.get("name"), "%" + keyword + "%"));
|
||||
}
|
||||
if (categoryId != null) {
|
||||
predicates.add(cb.equal(root.get("category").get("id"), categoryId));
|
||||
}
|
||||
predicates.add(cb.isTrue(root.get("onSale")));
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
};
|
||||
Sort sortObj = Sort.by(Sort.Direction.DESC, "createdAt");
|
||||
if ("price".equalsIgnoreCase(sort)) {
|
||||
sortObj = Sort.by(Sort.Direction.ASC, "price");
|
||||
} else if ("sales".equalsIgnoreCase(sort)) {
|
||||
sortObj = Sort.by(Sort.Direction.DESC, "sales");
|
||||
}
|
||||
return productRepository.findAll(spec, sortObj);
|
||||
}
|
||||
|
||||
public List<ProductImage> getImages(Product product) {
|
||||
return productImageRepository.findByProduct(product);
|
||||
}
|
||||
|
||||
public Product saveProduct(Product product) {
|
||||
return productRepository.save(product);
|
||||
}
|
||||
|
||||
public Category getCategory(Long id) {
|
||||
return categoryRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public List<Category> allCategories() {
|
||||
return categoryRepository.findAll();
|
||||
}
|
||||
}
|
||||
25
backend/src/main/java/com/toyshop/service/UserService.java
Normal file
25
backend/src/main/java/com/toyshop/service/UserService.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package com.toyshop.service;
|
||||
|
||||
import com.toyshop.entity.User;
|
||||
import com.toyshop.repository.UserRepository;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public UserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
public User getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null) {
|
||||
throw new IllegalStateException("未登录");
|
||||
}
|
||||
String username = authentication.getName();
|
||||
return userRepository.findByUsername(username).orElseThrow();
|
||||
}
|
||||
}
|
||||
20
backend/src/main/resources/application.yml
Normal file
20
backend/src/main/resources/application.yml
Normal file
@@ -0,0 +1,20 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/toyshop?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
|
||||
username: root
|
||||
password: root
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
open-in-view: false
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
jackson:
|
||||
time-zone: Asia/Shanghai
|
||||
server:
|
||||
port: 8080
|
||||
app:
|
||||
jwt:
|
||||
secret: change-this-secret-for-prod-change-this-secret
|
||||
expire-hours: 24
|
||||
Reference in New Issue
Block a user