mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 13:49:19 +08:00
初始化项目
This commit is contained in:
+40
@@ -0,0 +1,40 @@
|
||||
package top.xyquan.ecomdmbbackend.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 权限控制注解
|
||||
* 用于标记需要权限验证的接口
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequirePermission {
|
||||
|
||||
/**
|
||||
* 权限码,如 "company:create", "user:read"
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* 权限描述
|
||||
*/
|
||||
String description() default "";
|
||||
|
||||
/**
|
||||
* 是否允许超级管理员访问(默认允许)
|
||||
*/
|
||||
boolean allowSuper() default true;
|
||||
|
||||
/**
|
||||
* 是否允许公司管理员访问(默认允许)
|
||||
*/
|
||||
boolean allowCompany() default true;
|
||||
|
||||
/**
|
||||
* 是否允许普通用户访问(需要根据岗位权限判断)
|
||||
*/
|
||||
boolean allowUser() default true;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package top.xyquan.ecomdmbbackend.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 角色权限注解
|
||||
* 用于简单的角色权限控制
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequireRole {
|
||||
|
||||
/**
|
||||
* 允许的角色列表
|
||||
*/
|
||||
String[] value() default {};
|
||||
|
||||
/**
|
||||
* 权限描述
|
||||
*/
|
||||
String description() default "";
|
||||
|
||||
/**
|
||||
* 是否允许超级管理员访问(默认允许)
|
||||
*/
|
||||
boolean allowSuper() default true;
|
||||
|
||||
/**
|
||||
* 是否允许公司管理员访问(默认允许)
|
||||
*/
|
||||
boolean allowCompany() default true;
|
||||
|
||||
/**
|
||||
* 是否允许普通用户访问(默认不允许)
|
||||
*/
|
||||
boolean allowUser() default false;
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package top.xyquan.ecomdmbbackend.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.service.PermissionCheckService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 权限验证切面
|
||||
* 用于拦截带有@RequirePermission注解的方法并进行权限验证
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class PermissionAspect {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final PermissionCheckService permissionCheckService;
|
||||
|
||||
public PermissionAspect(CurrentUserContext currentUserContext, PermissionCheckService permissionCheckService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.permissionCheckService = permissionCheckService;
|
||||
}
|
||||
|
||||
@Around("@annotation(top.xyquan.ecomdmbbackend.common.annotation.RequirePermission)")
|
||||
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequirePermission annotation = method.getAnnotation(RequirePermission.class);
|
||||
|
||||
if (annotation == null) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
// 获取当前用户信息
|
||||
String role = currentUserContext.getCurrentUserPayload().getRole();
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long positionId = currentUserContext.getCurrentUserPayload().getPositionId();
|
||||
|
||||
log.debug("权限验证 - 用户角色: {}, 公司ID: {}, 岗位ID: {}, 权限码: {}",
|
||||
role, companyId, positionId, annotation.value());
|
||||
|
||||
// 根据角色进行权限验证
|
||||
boolean hasPermission = false;
|
||||
|
||||
switch (role) {
|
||||
case "super":
|
||||
hasPermission = annotation.allowSuper();
|
||||
break;
|
||||
case "company":
|
||||
hasPermission = annotation.allowCompany();
|
||||
break;
|
||||
case "user":
|
||||
hasPermission = annotation.allowUser() &&
|
||||
permissionCheckService.hasPermissionByPosition(positionId, annotation.value(), companyId);
|
||||
break;
|
||||
default:
|
||||
throw new BusinessException("未知的用户角色: " + role);
|
||||
}
|
||||
|
||||
if (!hasPermission) {
|
||||
log.warn("权限验证失败 - 用户角色: {}, 权限码: {}, 描述: {}",
|
||||
role, annotation.value(), annotation.description());
|
||||
throw new BusinessException("权限不足: " + annotation.description());
|
||||
}
|
||||
|
||||
log.debug("权限验证通过 - 用户角色: {}, 权限码: {}", role, annotation.value());
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package top.xyquan.ecomdmbbackend.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 角色权限验证切面
|
||||
* 用于简单的角色权限控制
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class RoleAspect {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public RoleAspect(CurrentUserContext currentUserContext) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Around("@annotation(top.xyquan.ecomdmbbackend.common.annotation.RequireRole)")
|
||||
public Object checkRole(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequireRole annotation = method.getAnnotation(RequireRole.class);
|
||||
|
||||
if (annotation == null) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
// 获取当前用户角色
|
||||
String role = currentUserContext.getCurrentUserPayload().getRole();
|
||||
|
||||
log.debug("角色权限验证 - 用户角色: {}, 注解配置: {}", role, annotation.description());
|
||||
|
||||
// 根据角色进行权限验证
|
||||
boolean hasPermission = false;
|
||||
|
||||
switch (role) {
|
||||
case "super":
|
||||
hasPermission = annotation.allowSuper();
|
||||
break;
|
||||
case "company":
|
||||
hasPermission = annotation.allowCompany();
|
||||
break;
|
||||
case "user":
|
||||
hasPermission = annotation.allowUser();
|
||||
break;
|
||||
default:
|
||||
throw new BusinessException("未知的用户角色: " + role);
|
||||
}
|
||||
|
||||
// 检查是否在允许的角色列表中
|
||||
if (annotation.value().length > 0) {
|
||||
hasPermission = hasPermission && Arrays.asList(annotation.value()).contains(role);
|
||||
}
|
||||
|
||||
if (!hasPermission) {
|
||||
log.warn("角色权限验证失败 - 用户角色: {}, 描述: {}", role, annotation.description());
|
||||
throw new BusinessException("权限不足: " + annotation.description());
|
||||
}
|
||||
|
||||
log.debug("角色权限验证通过 - 用户角色: {}", role);
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
/**
|
||||
* AOP配置类
|
||||
* 启用AspectJ自动代理,确保权限控制切面正常工作
|
||||
*/
|
||||
@Configuration
|
||||
@EnableAspectJAutoProxy(proxyTargetClass = true)
|
||||
public class AopConfig {
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.License;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Knife4j配置
|
||||
*/
|
||||
@Configuration
|
||||
public class Knife4jConfig {
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("ECOM-DMB-Backend API")
|
||||
.description("ECOM-DMB-Backend 后端服务API文档,支持多模块接口管理")
|
||||
.version("1.0.0")
|
||||
.contact(new Contact()
|
||||
.name("开发团队")
|
||||
.email("1564467676@qq.com")
|
||||
.url("https://xyquan.top"))
|
||||
.license(new License()
|
||||
.name("MIT License")
|
||||
.url("https://xyquan.top/licenses/MIT")));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MyBatis Plus配置
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
/**
|
||||
* 分页插件
|
||||
*/
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动填充处理器
|
||||
*/
|
||||
@Bean
|
||||
public MetaObjectHandler metaObjectHandler() {
|
||||
return new MetaObjectHandler() {
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.common.filter.JwtAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
|
||||
|
||||
/**
|
||||
* Spring Security配置
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
public SecurityConfig(JwtUtils jwtUtils, JwtAuthenticationFilter jwtAuthenticationFilter) {
|
||||
this.jwtUtils = jwtUtils;
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/auth/**").permitAll()
|
||||
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
|
||||
"/swagger-ui/**", "/swagger-ui.html")
|
||||
.permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Web配置
|
||||
*/
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
// 配置静态资源处理
|
||||
registry.addResourceHandler("/static/**")
|
||||
.addResourceLocations("classpath:/static/");
|
||||
|
||||
// 配置上传文件访问 - 使用绝对路径
|
||||
registry.addResourceHandler("/static/uploads/**")
|
||||
.addResourceLocations("file:./static/uploads/");
|
||||
|
||||
// 配置Swagger UI资源
|
||||
registry.addResourceHandler("/swagger-ui/**")
|
||||
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
|
||||
|
||||
registry.addResourceHandler("/webjars/**")
|
||||
.addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true)
|
||||
.maxAge(3600);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.common.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 业务异常
|
||||
*/
|
||||
@Getter
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private final String code;
|
||||
|
||||
public BusinessException(String message) {
|
||||
super(message);
|
||||
this.code = "BUSINESS_ERROR";
|
||||
}
|
||||
|
||||
public BusinessException(String code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package top.xyquan.ecomdmbbackend.common.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.FieldError;
|
||||
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;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* 处理业务异常
|
||||
*/
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleBusinessException(BusinessException e) {
|
||||
return ApiResponse.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理运行时异常
|
||||
*/
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleRuntimeException(RuntimeException e) {
|
||||
return ApiResponse.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理参数验证异常
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleValidationException(MethodArgumentNotValidException e) {
|
||||
String message = e.getBindingResult().getFieldErrors().stream()
|
||||
.map(FieldError::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
return ApiResponse.fail("参数验证失败: " + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理绑定异常
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleBindException(BindException e) {
|
||||
String message = e.getFieldErrors().stream()
|
||||
.map(FieldError::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
return ApiResponse.fail("参数绑定失败: " + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理认证异常
|
||||
*/
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public ApiResponse<String> handleAuthenticationException(AuthenticationException e) {
|
||||
return ApiResponse.fail("认证失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理权限异常
|
||||
*/
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public ApiResponse<String> handleAccessDeniedException(AccessDeniedException e) {
|
||||
return ApiResponse.fail("权限不足: " + e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理404异常
|
||||
*/
|
||||
@ExceptionHandler(NoHandlerFoundException.class)
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public ApiResponse<String> handleNoHandlerFoundException(NoHandlerFoundException e) {
|
||||
return ApiResponse.fail("请求的资源不存在: " + e.getRequestURL());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理其他异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ApiResponse<String> handleException(Exception e) {
|
||||
// 记录详细错误信息到日志
|
||||
e.printStackTrace();
|
||||
return ApiResponse.fail("系统内部错误: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package top.xyquan.ecomdmbbackend.common.filter;
|
||||
|
||||
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.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* JWT认证过滤器
|
||||
*/
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
public JwtAuthenticationFilter(JwtUtils jwtUtils) {
|
||||
this.jwtUtils = jwtUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// 添加调试日志
|
||||
logger.debug("JWT Filter处理请求: " + request.getMethod() + " " + request.getRequestURI());
|
||||
|
||||
try {
|
||||
// 从请求头中获取JWT Token
|
||||
String token = getTokenFromRequest(request);
|
||||
|
||||
if (StringUtils.hasText(token) && jwtUtils.validateToken(token)) {
|
||||
// 从Token中获取用户ID
|
||||
String userId = jwtUtils.getUserIdFromToken(token);
|
||||
Long companyId = jwtUtils.getCompanyIdFromToken(token);
|
||||
|
||||
if (StringUtils.hasText(userId)) {
|
||||
// 创建认证信息,将token作为credentials传递
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
userId, token, null);
|
||||
|
||||
// 设置认证信息到Security上下文
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
logger.debug("JWT认证成功,用户ID: " + userId);
|
||||
logger.debug("JWT认证成功,公司ID: " + companyId);
|
||||
}
|
||||
} else {
|
||||
logger.debug("JWT Token无效或为空");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Token验证失败,不设置认证信息,继续执行过滤器链
|
||||
logger.debug("JWT Token验证失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求头中获取JWT Token
|
||||
*/
|
||||
private String getTokenFromRequest(HttpServletRequest request) {
|
||||
String bearerToken = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.common.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class PageQueryDTO<T> {
|
||||
|
||||
//页码,从1开始
|
||||
@NotNull(message = "页码不能为空")
|
||||
@Min(value = 1, message = "页码必须大于0")
|
||||
private Integer page = 1;
|
||||
|
||||
//每页大小
|
||||
@NotNull(message = "每页大小不能为空")
|
||||
@Min(value = 1, message = "每页大小必须大于0")
|
||||
private Integer pageSize = 10;
|
||||
|
||||
// 查询条件
|
||||
private T filters;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.common.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class PageResultVO<T> implements Serializable {
|
||||
private List<T> list; // 当前页数据
|
||||
private Long total; // 总条数
|
||||
private Integer page; // 当前页码
|
||||
private Integer pageSize; // 每页条数
|
||||
private Integer totalPages; // 总页数
|
||||
private Boolean hasNextPage; // 是否有下一页
|
||||
private Boolean hasPrevPage; // 是否有上一页
|
||||
|
||||
// 构造函数
|
||||
public PageResultVO(List<T> list, Long total, Integer page, Integer pageSize) {
|
||||
this.list = list;
|
||||
this.total = total;
|
||||
this.page = page;
|
||||
this.pageSize = pageSize;
|
||||
this.totalPages = (int) Math.ceil((double) total / pageSize);
|
||||
this.hasNextPage = page < this.totalPages;
|
||||
this.hasPrevPage = page > 1;
|
||||
}
|
||||
|
||||
// 静态工厂方法,用于创建分页响应对象
|
||||
public static <T> PageResultVO<T> create(List<T> list, Long total, Integer page, Integer pageSize) {
|
||||
return new PageResultVO<>(list, total, page, pageSize);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package top.xyquan.ecomdmbbackend.common.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ApiResponse<T> {
|
||||
private int code;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
return new ApiResponse<>(0, "操作成功", data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(String message, T data) {
|
||||
return new ApiResponse<>(0, message, data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success() {
|
||||
return new ApiResponse<>(0, "操作成功", null);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(String message) {
|
||||
return new ApiResponse<>(1, message, null);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(int code, String message) {
|
||||
return new ApiResponse<>(code, message, null);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user